UNPKG

104 kBTypeScriptView Raw
1
2import * as React from "react";
3import { CookieParseOptions, CookieParseOptions as CookieParseOptions$1, CookieSerializeOptions, CookieSerializeOptions as CookieSerializeOptions$1 } from "cookie-es";
4import { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, unstable_HistoryRouter } from "react-router/internal/react-server-client";
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 /**
1018 * <docs-warning>This prop is currently unstable and may change in minor or patch
1019 * releases.</docs-warning>
1020 *
1021 * A promise (or value) to read using React's `use()` API in client components.
1022 * Unlike `resolve` in client components, this accepts promise-like values
1023 * without modifying the source promise.
1024 *
1025 * `errorElement` handles promise rejections. Errors thrown while rendering
1026 * children bubble to the nearest React error boundary.
1027 *
1028 * ```tsx
1029 * <Await unstable_promise={reviewsPromise} errorElement={<ReviewsError />}>
1030 * {(reviews) => <Reviews items={reviews} />}
1031 * </Await>
1032 * ```
1033 *
1034 * Pass exactly one of `unstable_promise` or `resolve`.
1035 */
1036 unstable_promise?: never;
1037 /**
1038 * When using a function, the resolved value is provided as the parameter.
1039 *
1040 * ```tsx [2]
1041 * <Await resolve={reviewsPromise}>
1042 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
1043 * </Await>
1044 * ```
1045 *
1046 * When using React elements, {@link useAsyncValue} will provide the
1047 * resolved value:
1048 *
1049 * ```tsx [2]
1050 * <Await resolve={reviewsPromise}>
1051 * <Reviews />
1052 * </Await>
1053 *
1054 * function Reviews() {
1055 * const resolvedReviews = useAsyncValue();
1056 * return <div>...</div>;
1057 * }
1058 * ```
1059 */
1060 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
1061 /**
1062 * The error element renders instead of the `children` when the
1063 * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1064 * rejects.
1065 *
1066 * When using `resolve`, errors thrown while rendering `children` are
1067 * also caught and rendered here. With `unstable_promise`, only promise
1068 * rejections are handled; errors thrown while rendering `children` bubble to
1069 * the nearest React error boundary.
1070 *
1071 * ```tsx
1072 * <Await resolve={reviewsPromise} errorElement={<div>Oops</div>}>
1073 * <Reviews />
1074 * </Await>
1075 * ```
1076 *
1077 * To provide a more contextual error, you can use the {@link useAsyncError} in a
1078 * child component
1079 *
1080 * ```tsx
1081 * <Await resolve={reviewsPromise} errorElement={<ReviewsError />}>
1082 * <Reviews />
1083 * </Await>
1084 *
1085 * function ReviewsError() {
1086 * const error = useAsyncError();
1087 * return <div>Error loading reviews: {error.message}</div>;
1088 * }
1089 * ```
1090 *
1091 * If you do not provide an `errorElement`, the rejected value will bubble up
1092 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
1093 * and be accessible via the {@link useRouteError} hook.
1094 */
1095 errorElement?: React.ReactNode;
1096 /**
1097 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
1098 * returned from a [`loader`](../../start/framework/route-module#loader) to be
1099 * resolved and rendered.
1100 *
1101 * ```tsx
1102 * import { Await, useLoaderData } from "react-router";
1103 *
1104 * export async function loader() {
1105 * let reviews = getReviews(); // not awaited
1106 * let book = await getBook();
1107 * return {
1108 * book,
1109 * reviews, // this is a promise
1110 * };
1111 * }
1112 *
1113 * export default function Book() {
1114 * const {
1115 * book,
1116 * reviews, // this is the same promise
1117 * } = useLoaderData();
1118 *
1119 * return (
1120 * <div>
1121 * <h1>{book.title}</h1>
1122 * <p>{book.description}</p>
1123 * <React.Suspense fallback={<ReviewsSkeleton />}>
1124 * <Await
1125 * // and is the promise we pass to Await
1126 * resolve={reviews}
1127 * >
1128 * <Reviews />
1129 * </Await>
1130 * </React.Suspense>
1131 * </div>
1132 * );
1133 * }
1134 * ```
1135 */
1136 resolve: Resolve;
1137}
1138interface AwaitPromiseProps<Resolve> extends Omit<AwaitProps<Resolve>, "resolve" | "unstable_promise"> {
1139 resolve?: never;
1140 /**
1141 * A promise (or value) to read using React's `use()` API in client components.
1142 * Unlike `resolve` in client components, this accepts promise-like values
1143 * without modifying the source promise.
1144 *
1145 * `errorElement` handles promise rejections. Errors thrown while rendering
1146 * children bubble to the nearest React error boundary.
1147 *
1148 * ```tsx
1149 * <Await unstable_promise={reviewsPromise} errorElement={<ReviewsError />}>
1150 * {(reviews) => <Reviews items={reviews} />}
1151 * </Await>
1152 * ```
1153 *
1154 * Pass exactly one of `unstable_promise` or `resolve`.
1155 */
1156 unstable_promise: Resolve;
1157}
1158/**
1159 * Used to render promise values with automatic error handling.
1160 *
1161 * Passing the promise through `resolve` uses React Router-specific promise tracking, while passing
1162 * it through `unstable_promise` uses React's built-in [`use()`](https://react.dev/reference/react/use)
1163 * API.
1164 *
1165 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
1166 *
1167 * <docs-warning>The `unstable_promise` prop is currently unstable and may change in minor or patch
1168 * releases. We plan to stabilize `<Await promise>` and deprecate `<Await resolve>` during v8, and then
1169 * drop `<Await resolve>` in v9. Please see below for minor `errorElement` behavioral differences
1170 * between the two approaches.</docs-warning>
1171 *
1172 * @example
1173 * import { Await, useLoaderData } from "react-router";
1174 *
1175 * export async function loader() {
1176 * // not awaited
1177 * const reviews = getReviews();
1178 * // awaited (blocks the transition)
1179 * const book = await fetch("/api/book").then((res) => res.json());
1180 * return { book, reviews };
1181 * }
1182 *
1183 * function Book() {
1184 * const { book, reviews } = useLoaderData();
1185 * return (
1186 * <div>
1187 * <h1>{book.title}</h1>
1188 * <p>{book.description}</p>
1189 * <React.Suspense fallback={<ReviewsSkeleton />}>
1190 * <Await resolve={reviews} errorElement={<BookError />}>
1191 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
1192 * </Await>
1193 * </React.Suspense>
1194 * </div>
1195 * );
1196 * }
1197 *
1198 * @public
1199 * @category Components
1200 * @mode framework
1201 * @mode data
1202 * @param props Props
1203 * @param {AwaitProps.children} props.children n/a
1204 * @param {AwaitProps.errorElement} props.errorElement n/a
1205 * @param {AwaitProps.resolve} props.resolve n/a
1206 * @param {AwaitProps.unstable_promise} props.unstable_promise n/a
1207 * @returns React element for the rendered awaited value
1208 */
1209declare function Await$1<Resolve>(props: AwaitProps<Resolve> | AwaitPromiseProps<Resolve>): React.JSX.Element;
1210//#endregion
1211//#region lib/router/instrumentation.d.ts
1212type ServerInstrumentation = {
1213 handler?: InstrumentRequestHandlerFunction;
1214 route?: InstrumentRouteFunction;
1215};
1216type ClientInstrumentation = {
1217 router?: InstrumentRouterFunction;
1218 route?: InstrumentRouteFunction;
1219};
1220type InstrumentRequestHandlerFunction = (handler: InstrumentableRequestHandler) => void;
1221type InstrumentRouterFunction = (router: InstrumentableRouter) => void;
1222type InstrumentRouteFunction = (route: InstrumentableRoute) => void;
1223/**
1224 * Route metadata available after React Router has matched an instrumented
1225 * request, navigation, or fetcher call.
1226 */
1227type InstrumentationResultMeta = {
1228 url: LoaderFunctionArgs["url"];
1229 pattern: string;
1230 params: LoaderFunctionArgs["params"];
1231};
1232/**
1233 * Result returned by route-level instrumented handler calls, such as
1234 * instrumented loaders, actions, middleware, and lazy route functions.
1235 */
1236type InstrumentationHandlerResult = {
1237 status: "success";
1238 error: undefined;
1239} | {
1240 status: "error";
1241 error: Error;
1242};
1243/**
1244 * Result returned by client-side router instrumented navigation and fetcher
1245 * calls.
1246 */
1247type InstrumentationClientRouterResult = InstrumentationHandlerResult & {
1248 meta: InstrumentationResultMeta | undefined;
1249};
1250/**
1251 * Result returned by server request handler instrumentation.
1252 */
1253type InstrumentationServerHandlerResult = InstrumentationHandlerResult & {
1254 statusCode: number;
1255 meta: InstrumentationResultMeta | undefined;
1256};
1257type InstrumentFunction<T, TInnerResult = InstrumentationHandlerResult> = (handler: () => Promise<TInnerResult>, info: T) => Promise<void>;
1258type ReadonlyRequest = {
1259 method: string;
1260 url: string;
1261 headers: Pick<Headers, "get">;
1262};
1263type ReadonlyContext = Pick<RouterContextProvider, "get">;
1264type InstrumentableRoute = {
1265 id: string;
1266 index: boolean | undefined;
1267 path: string | undefined;
1268 instrument(instrumentations: RouteInstrumentations): void;
1269};
1270type RouteInstrumentations = {
1271 lazy?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1272 "lazy.loader"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1273 "lazy.action"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1274 "lazy.middleware"?: InstrumentFunction<RouteLazyInstrumentationInfo>;
1275 middleware?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1276 loader?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1277 action?: InstrumentFunction<RouteHandlerInstrumentationInfo>;
1278};
1279type RouteLazyInstrumentationInfo = undefined;
1280type RouteHandlerInstrumentationInfo = Readonly<Omit<LoaderFunctionArgs, "request" | "context"> & {
1281 request: ReadonlyRequest;
1282 context: ReadonlyContext;
1283}>;
1284type InstrumentableRouter = {
1285 instrument(instrumentations: RouterInstrumentations): void;
1286};
1287type RouterInstrumentations = {
1288 navigate?: InstrumentFunction<RouterNavigationInstrumentationInfo, InstrumentationClientRouterResult>;
1289 fetch?: InstrumentFunction<RouterFetchInstrumentationInfo, InstrumentationClientRouterResult>;
1290};
1291type RouterNavigationInstrumentationInfo = Readonly<{
1292 to: string | number;
1293 currentUrl: string;
1294 formMethod?: HTMLFormMethod;
1295 formEncType?: FormEncType;
1296 formData?: FormData;
1297 body?: any;
1298}>;
1299type RouterFetchInstrumentationInfo = Readonly<{
1300 href: string;
1301 currentUrl: string;
1302 fetcherKey: string;
1303 formMethod?: HTMLFormMethod;
1304 formEncType?: FormEncType;
1305 formData?: FormData;
1306 body?: any;
1307}>;
1308type InstrumentableRequestHandler = {
1309 instrument(instrumentations: RequestHandlerInstrumentations): void;
1310};
1311type RequestHandlerInstrumentations = {
1312 request?: InstrumentFunction<RequestHandlerInstrumentationInfo, InstrumentationServerHandlerResult>;
1313};
1314type RequestHandlerInstrumentationInfo = Readonly<{
1315 request: ReadonlyRequest;
1316 context: ReadonlyContext | undefined;
1317}>;
1318//#endregion
1319//#region lib/router/router.d.ts
1320/**
1321 * A Router instance manages all navigation and data loading/mutations
1322 */
1323interface Router$1 {
1324 /**
1325 * @private
1326 * PRIVATE - DO NOT USE
1327 *
1328 * Return the basename for the router
1329 */
1330 get basename(): RouterInit["basename"];
1331 /**
1332 * @private
1333 * PRIVATE - DO NOT USE
1334 *
1335 * Return the future config for the router
1336 */
1337 get future(): FutureConfig;
1338 /**
1339 * @private
1340 * PRIVATE - DO NOT USE
1341 *
1342 * Return the current state of the router
1343 */
1344 get state(): RouterState;
1345 /**
1346 * @private
1347 * PRIVATE - DO NOT USE
1348 *
1349 * Return the routes for this router instance
1350 */
1351 get routes(): DataRouteObject[];
1352 /**
1353 * @private
1354 * PRIVATE - DO NOT USE
1355 *
1356 * Match routes against a location using the router's configured route
1357 * matching implementation.
1358 */
1359 match(locationArg: Partial<Location$1> | string): DataRouteMatch[] | null;
1360 /**
1361 * @private
1362 * PRIVATE - DO NOT USE
1363 *
1364 * Return the manifest for this router instance
1365 */
1366 get manifest(): RouteManifest;
1367 /**
1368 * @private
1369 * PRIVATE - DO NOT USE
1370 *
1371 * Return the window associated with the router
1372 */
1373 get window(): RouterInit["window"];
1374 /**
1375 * @private
1376 * PRIVATE - DO NOT USE
1377 *
1378 * Initialize the router, including adding history listeners and kicking off
1379 * initial data fetches. Returns a function to cleanup listeners and abort
1380 * any in-progress loads
1381 */
1382 initialize(): Router$1;
1383 /**
1384 * @private
1385 * PRIVATE - DO NOT USE
1386 *
1387 * Subscribe to router.state updates
1388 *
1389 * @param fn function to call with the new state
1390 */
1391 subscribe(fn: RouterSubscriber): () => void;
1392 /**
1393 * @private
1394 * PRIVATE - DO NOT USE
1395 *
1396 * Enable scroll restoration behavior in the router
1397 *
1398 * @param savedScrollPositions Object that will manage positions, in case
1399 * it's being restored from sessionStorage
1400 * @param getScrollPosition Function to get the active Y scroll position
1401 * @param getKey Function to get the key to use for restoration
1402 */
1403 enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
1404 /**
1405 * @private
1406 * PRIVATE - DO NOT USE
1407 *
1408 * Navigate forward/backward in the history stack
1409 * @param to Delta to move in the history stack
1410 */
1411 navigate(to: number): Promise<void>;
1412 /**
1413 * Navigate to the given path
1414 * @param to Path to navigate to
1415 * @param opts Navigation options (method, submission, etc.)
1416 */
1417 navigate(to: To | null, opts?: RouterNavigateOptions): Promise<void>;
1418 /**
1419 * @private
1420 * PRIVATE - DO NOT USE
1421 *
1422 * Trigger a fetcher load/submission
1423 *
1424 * @param key Fetcher key
1425 * @param routeId Route that owns the fetcher
1426 * @param href href to fetch
1427 * @param opts Fetcher options, (method, submission, etc.)
1428 */
1429 fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): Promise<void>;
1430 /**
1431 * @private
1432 * PRIVATE - DO NOT USE
1433 *
1434 * Trigger a revalidation of all current route loaders and fetcher loads
1435 */
1436 revalidate(): Promise<void>;
1437 /**
1438 * @private
1439 * PRIVATE - DO NOT USE
1440 *
1441 * Utility function to create an href for the given location
1442 * @param location
1443 */
1444 createHref(location: Location$1 | URL): string;
1445 /**
1446 * @private
1447 * PRIVATE - DO NOT USE
1448 *
1449 * Utility function to create a URL for the given location
1450 * @param location
1451 */
1452 createURL?(to: To): URL;
1453 /**
1454 * @private
1455 * PRIVATE - DO NOT USE
1456 *
1457 * Utility function to URL encode a destination path according to the internal
1458 * history implementation
1459 * @param to
1460 */
1461 encodeLocation(to: To): Path;
1462 /**
1463 * @private
1464 * PRIVATE - DO NOT USE
1465 *
1466 * Get/create a fetcher for the given key
1467 * @param key
1468 */
1469 getFetcher<TData = any>(key: string): Fetcher<TData>;
1470 /**
1471 * @internal
1472 * PRIVATE - DO NOT USE
1473 *
1474 * Reset the fetcher for a given key
1475 * @param key
1476 */
1477 resetFetcher(key: string, opts?: {
1478 reason?: unknown;
1479 }): void;
1480 /**
1481 * @private
1482 * PRIVATE - DO NOT USE
1483 *
1484 * Delete the fetcher for a given key
1485 * @param key
1486 */
1487 deleteFetcher(key: string): void;
1488 /**
1489 * @private
1490 * PRIVATE - DO NOT USE
1491 *
1492 * Cleanup listeners and abort any in-progress loads
1493 */
1494 dispose(): void;
1495 /**
1496 * @private
1497 * PRIVATE - DO NOT USE
1498 *
1499 * Get a navigation blocker
1500 * @param key The identifier for the blocker
1501 * @param fn The blocker function implementation
1502 */
1503 getBlocker(key: string, fn: BlockerFunction): Blocker;
1504 /**
1505 * @private
1506 * PRIVATE - DO NOT USE
1507 *
1508 * Delete a navigation blocker
1509 * @param key The identifier for the blocker
1510 */
1511 deleteBlocker(key: string): void;
1512 /**
1513 * @private
1514 * PRIVATE DO NOT USE
1515 *
1516 * Patch additional children routes into an existing parent route
1517 * @param routeId The parent route id or a callback function accepting `patch`
1518 * to perform batch patching
1519 * @param children The additional children routes
1520 * @param unstable_allowElementMutations Allow mutation or route elements on
1521 * existing routes. Intended for RSC-usage
1522 * only.
1523 */
1524 patchRoutes(routeId: string | null, children: RouteObject[], unstable_allowElementMutations?: boolean): void;
1525 /**
1526 * @private
1527 * PRIVATE - DO NOT USE
1528 *
1529 * HMR needs to pass in-flight route updates to React Router
1530 * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)
1531 */
1532 _internalSetRoutes(routes: RouteObject[]): void;
1533 /**
1534 * @private
1535 * PRIVATE - DO NOT USE
1536 *
1537 * Cause subscribers to re-render. This is used to force a re-render.
1538 */
1539 _internalSetStateDoNotUseOrYouWillBreakYourApp(state: Partial<RouterState>): void;
1540 /**
1541 * @private
1542 * PRIVATE - DO NOT USE
1543 *
1544 * Internal fetch AbortControllers accessed by unit tests
1545 */
1546 _internalFetchControllers: Map<string, AbortController>;
1547}
1548/**
1549 * State maintained internally by the router. During a navigation, all states
1550 * reflect the "old" location unless otherwise noted.
1551 */
1552interface RouterState {
1553 /**
1554 * The action of the most recent navigation
1555 */
1556 historyAction: Action;
1557 /**
1558 * The current location reflected by the router
1559 */
1560 location: Location$1;
1561 /**
1562 * The current set of route matches
1563 */
1564 matches: DataRouteMatch[];
1565 /**
1566 * Tracks whether we've completed our initial data load
1567 */
1568 initialized: boolean;
1569 /**
1570 * Tracks whether we should be rendering a HydrateFallback during hydration
1571 */
1572 renderFallback: boolean;
1573 /**
1574 * Current scroll position we should start at for a new view
1575 * - number -> scroll position to restore to
1576 * - false -> do not restore scroll at all (used during submissions/revalidations)
1577 * - null -> don't have a saved position, scroll to hash or top of page
1578 */
1579 restoreScrollPosition: number | false | null;
1580 /**
1581 * Indicate whether this navigation should skip resetting the scroll position
1582 * if we are unable to restore the scroll position
1583 */
1584 preventScrollReset: boolean;
1585 /**
1586 * Tracks the state of the current navigation
1587 */
1588 navigation: Navigation;
1589 /**
1590 * Tracks any in-progress revalidations
1591 */
1592 revalidation: RevalidationState;
1593 /**
1594 * Data from the loaders for the current matches
1595 */
1596 loaderData: RouteData;
1597 /**
1598 * Data from the action for the current matches
1599 */
1600 actionData: RouteData | null;
1601 /**
1602 * Errors caught from loaders for the current matches
1603 */
1604 errors: RouteData | null;
1605 /**
1606 * Map of current fetchers
1607 */
1608 fetchers: Map<string, Fetcher>;
1609 /**
1610 * Map of current blockers
1611 */
1612 blockers: Map<string, Blocker>;
1613}
1614/**
1615 * Data that can be passed into hydrate a Router from SSR
1616 */
1617type HydrationState = Partial<Pick<RouterState, "loaderData" | "actionData" | "errors">>;
1618/**
1619 * Future flags to toggle new feature behavior
1620 */
1621interface FutureConfig {
1622 /** @internal Enables application-controlled Framework route discovery. */
1623 unstable_customRouteDiscovery?: boolean;
1624 /** Enables route-pattern matching after calling `unstable_preloadRoutePattern()`. */
1625 unstable_routePatternMatching?: boolean;
1626}
1627/**
1628 * Initialization options for createRouter
1629 */
1630interface RouterInit {
1631 routes: RouteObject[];
1632 history: History;
1633 basename?: string;
1634 getContext?: () => MaybePromise<RouterContextProvider>;
1635 instrumentations?: ClientInstrumentation[];
1636 mapRouteProperties?: MapRoutePropertiesFunction;
1637 future?: Partial<FutureConfig>;
1638 hydrationRouteProperties?: string[];
1639 hydrationData?: HydrationState;
1640 window?: Window;
1641 dataStrategy?: DataStrategyFunction;
1642 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1643}
1644/**
1645 * State returned from a server-side query() call
1646 */
1647interface StaticHandlerContext {
1648 basename: Router$1["basename"];
1649 location: RouterState["location"];
1650 matches: RouterState["matches"];
1651 loaderData: RouterState["loaderData"];
1652 actionData: RouterState["actionData"];
1653 errors: RouterState["errors"];
1654 statusCode: number;
1655 loaderHeaders: Record<string, Headers>;
1656 actionHeaders: Record<string, Headers>;
1657 _deepestRenderedBoundaryId?: string | null;
1658 /** @private */
1659 _match: StaticHandler["match"];
1660}
1661/**
1662 * A StaticHandler instance manages a singular SSR navigation/fetch event
1663 */
1664interface StaticHandler {
1665 /**
1666 * The set of data routes managed by this handler
1667 */
1668 dataRoutes: DataRouteObject[];
1669 /** @private Estimated route metadata visits per regex match. */
1670 readonly _matchCost?: number;
1671 /**
1672 * @private
1673 * PRIVATE - DO NOT USE
1674 *
1675 * Match routes against a location using the handler's configured route
1676 * matching implementation.
1677 */
1678 match(locationArg: Partial<Location$1> | string): DataRouteMatch[] | null;
1679 /**
1680 * Perform a query for a given request - executing all matched route
1681 * loaders/actions. Used for document requests.
1682 *
1683 * @param request The request to query
1684 * @param opts Optional query options
1685 * @param opts.dataStrategy Alternate dataStrategy implementation
1686 * @param opts.filterMatchesToLoad Predicate function to filter which matches should be loaded
1687 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1688 * to generate a response to bubble back up the middleware chain
1689 * @param opts.requestContext Context object to pass to loaders/actions
1690 * @param opts.skipLoaderErrorBubbling Skip loader error bubbling
1691 * @param opts.skipRevalidation Skip revalidation after action submission
1692 * @param opts.normalizePath Normalize the request path
1693 */
1694 query(request: Request, opts?: {
1695 requestContext?: unknown;
1696 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1697 skipLoaderErrorBubbling?: boolean;
1698 skipRevalidation?: boolean;
1699 dataStrategy?: DataStrategyFunction<unknown>;
1700 generateMiddlewareResponse?: (query: (r: Request, args?: {
1701 filterMatchesToLoad?: (match: DataRouteMatch) => boolean;
1702 }) => Promise<StaticHandlerContext | Response>) => MaybePromise<Response>;
1703 normalizePath?: (request: Request) => Path;
1704 }): Promise<StaticHandlerContext | Response>;
1705 /**
1706 * Perform a query for a specific route. Used for resource requests.
1707 *
1708 * @param request The request to query
1709 * @param opts Optional queryRoute options
1710 * @param opts.dataStrategy Alternate dataStrategy implementation
1711 * @param opts.generateMiddlewareResponse To enable middleware, provide a function
1712 * to generate a response to bubble back up the middleware chain
1713 * @param opts.requestContext Context object to pass to loaders/actions
1714 * @param opts.routeId The ID of the route to query
1715 * @param opts.normalizePath Normalize the request path
1716 */
1717 queryRoute(request: Request, opts?: {
1718 routeId?: string;
1719 requestContext?: unknown;
1720 dataStrategy?: DataStrategyFunction<unknown>;
1721 generateMiddlewareResponse?: (queryRoute: (r: Request) => Promise<Response>) => MaybePromise<Response>;
1722 normalizePath?: (request: Request) => Path;
1723 }): Promise<any>;
1724}
1725type ViewTransitionOpts = {
1726 currentLocation: Location$1;
1727 nextLocation: Location$1;
1728};
1729/**
1730 * Subscriber function signature for changes to router state
1731 */
1732interface RouterSubscriber {
1733 (state: RouterState, opts: {
1734 deletedFetchers: string[];
1735 newErrors: RouteData | null;
1736 viewTransitionOpts?: ViewTransitionOpts;
1737 flushSync: boolean;
1738 }): void;
1739}
1740/**
1741 * Function signature for determining the key to be used in scroll restoration
1742 * for a given location
1743 */
1744interface GetScrollRestorationKeyFunction {
1745 (location: Location$1, matches: UIMatch[]): string | null;
1746}
1747/**
1748 * Function signature for determining the current scroll position
1749 */
1750interface GetScrollPositionFunction {
1751 (): number;
1752}
1753/**
1754 * - "route": relative to the route hierarchy so `..` means remove all segments
1755 * of the current route even if it has many. For example, a `route("posts/:id")`
1756 * would have both `:id` and `posts` removed from the url.
1757 * - "path": relative to the pathname so `..` means remove one segment of the
1758 * pathname. For example, a `route("posts/:id")` would have only `:id` removed
1759 * from the url.
1760 */
1761type RelativeRoutingType = "route" | "path";
1762type BaseNavigateOrFetchOptions = {
1763 preventScrollReset?: boolean;
1764 relative?: RelativeRoutingType;
1765 flushSync?: boolean;
1766 defaultShouldRevalidate?: boolean;
1767};
1768type BaseNavigateOptions = BaseNavigateOrFetchOptions & {
1769 replace?: boolean;
1770 state?: any;
1771 fromRouteId?: string;
1772 /**
1773 * @deprecated Use React's `<ViewTransition>` component instead. See the
1774 * [migration guide](https://reactrouter.com/how-to/view-transitions).
1775 */
1776 viewTransition?: boolean;
1777 mask?: To;
1778};
1779type BaseSubmissionOptions = {
1780 formMethod?: HTMLFormMethod;
1781 formEncType?: FormEncType;
1782} & ({
1783 formData: FormData;
1784 body?: undefined;
1785} | {
1786 formData?: undefined;
1787 body: any;
1788});
1789/**
1790 * Options for a navigate() call for a normal (non-submission) navigation
1791 */
1792type LinkNavigateOptions = BaseNavigateOptions;
1793/**
1794 * Options for a navigate() call for a submission navigation
1795 */
1796type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;
1797/**
1798 * Options to pass to navigate() for a navigation
1799 */
1800type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
1801/**
1802 * Options for a fetch() load
1803 */
1804type LoadFetchOptions = BaseNavigateOrFetchOptions;
1805/**
1806 * Options for a fetch() submission
1807 */
1808type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;
1809/**
1810 * Options to pass to fetch()
1811 */
1812type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
1813/**
1814 * Potential states for state.navigation
1815 */
1816type NavigationStates = {
1817 Idle: {
1818 state: "idle";
1819 location: undefined;
1820 matches: undefined;
1821 historyAction: undefined;
1822 formMethod: undefined;
1823 formAction: undefined;
1824 formEncType: undefined;
1825 formData: undefined;
1826 json: undefined;
1827 text: undefined;
1828 };
1829 Loading: {
1830 state: "loading";
1831 location: Location$1;
1832 matches: DataRouteMatch[];
1833 historyAction: Action;
1834 formMethod: Submission["formMethod"] | undefined;
1835 formAction: Submission["formAction"] | undefined;
1836 formEncType: Submission["formEncType"] | undefined;
1837 formData: Submission["formData"] | undefined;
1838 json: Submission["json"] | undefined;
1839 text: Submission["text"] | undefined;
1840 };
1841 Submitting: {
1842 state: "submitting";
1843 location: Location$1;
1844 matches: DataRouteMatch[];
1845 historyAction: Action;
1846 formMethod: Submission["formMethod"];
1847 formAction: Submission["formAction"];
1848 formEncType: Submission["formEncType"];
1849 formData: Submission["formData"];
1850 json: Submission["json"];
1851 text: Submission["text"];
1852 };
1853};
1854type Navigation = NavigationStates[keyof NavigationStates];
1855type RevalidationState = "idle" | "loading";
1856/**
1857 * Potential states for fetchers
1858 */
1859type FetcherStates<TData = any> = {
1860 /**
1861 * The fetcher is not calling a loader or action
1862 *
1863 * ```tsx
1864 * fetcher.state === "idle"
1865 * ```
1866 */
1867 Idle: {
1868 state: "idle";
1869 formMethod: undefined;
1870 formAction: undefined;
1871 formEncType: undefined;
1872 text: undefined;
1873 formData: undefined;
1874 json: undefined;
1875 /**
1876 * If the fetcher has never been called, this will be undefined.
1877 */
1878 data: TData | undefined;
1879 };
1880 /**
1881 * The fetcher is loading data from a {@link LoaderFunction | loader} from a
1882 * call to {@link FetcherWithComponents.load | `fetcher.load`}.
1883 *
1884 * ```tsx
1885 * // somewhere
1886 * <button onClick={() => fetcher.load("/some/route") }>Load</button>
1887 *
1888 * // the state will update
1889 * fetcher.state === "loading"
1890 * ```
1891 */
1892 Loading: {
1893 state: "loading";
1894 formMethod: Submission["formMethod"] | undefined;
1895 formAction: Submission["formAction"] | undefined;
1896 formEncType: Submission["formEncType"] | undefined;
1897 text: Submission["text"] | undefined;
1898 formData: Submission["formData"] | undefined;
1899 json: Submission["json"] | undefined;
1900 data: TData | undefined;
1901 };
1902 /**
1903 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`}.
1904 ```tsx
1905 // somewhere
1906 <input
1907 onChange={e => {
1908 fetcher.submit(event.currentTarget.form, { method: "post" });
1909 }}
1910 />
1911 // the state will update
1912 fetcher.state === "submitting"
1913 // and formData will be available
1914 fetcher.formData
1915 ```
1916 */
1917 Submitting: {
1918 state: "submitting";
1919 formMethod: Submission["formMethod"];
1920 formAction: Submission["formAction"];
1921 formEncType: Submission["formEncType"];
1922 text: Submission["text"];
1923 formData: Submission["formData"];
1924 json: Submission["json"];
1925 data: TData | undefined;
1926 };
1927};
1928type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
1929interface BlockerBlocked {
1930 state: "blocked";
1931 reset: () => void;
1932 proceed: () => void;
1933 location: Location$1;
1934}
1935interface BlockerUnblocked {
1936 state: "unblocked";
1937 reset: undefined;
1938 proceed: undefined;
1939 location: undefined;
1940}
1941interface BlockerProceeding {
1942 state: "proceeding";
1943 reset: undefined;
1944 proceed: undefined;
1945 location: Location$1;
1946}
1947type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
1948type BlockerFunction = (args: {
1949 currentLocation: Location$1;
1950 nextLocation: Location$1;
1951 historyAction: Action;
1952}) => boolean;
1953interface CreateStaticHandlerOptions {
1954 basename?: string;
1955 mapRouteProperties?: MapRoutePropertiesFunction;
1956 instrumentations?: Pick<ServerInstrumentation, "route">[];
1957 future?: Partial<FutureConfig>;
1958}
1959/**
1960 * Create a static handler to perform server-side data loading
1961 *
1962 * @example
1963 * export async function handleRequest(request: Request) {
1964 * let { query, dataRoutes } = createStaticHandler(routes);
1965 * let context = await query(request);
1966 *
1967 * if (context instanceof Response) {
1968 * return context;
1969 * }
1970 *
1971 * let router = createStaticRouter(dataRoutes, context);
1972 * return new Response(
1973 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1974 * { headers: { "Content-Type": "text/html" } }
1975 * );
1976 * }
1977 *
1978 * @public
1979 * @category Data Routers
1980 * @mode data
1981 * @param routes The {@link RouteObject | route objects} to create a static
1982 * handler for
1983 * @param opts Options
1984 * @param opts.basename The base URL for the static handler (default: `/`)
1985 * @param opts.future Future flags for the static handler
1986 * @returns A static handler that can be used to query data for the provided
1987 * routes
1988 */
1989declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
1990//#endregion
1991//#region lib/router/links.d.ts
1992type Primitive = null | undefined | string | number | boolean | symbol | bigint;
1993type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
1994interface HtmlLinkProps {
1995 /**
1996 * Address of the hyperlink
1997 */
1998 href?: string;
1999 /**
2000 * How the element handles crossorigin requests
2001 */
2002 crossOrigin?: "anonymous" | "use-credentials";
2003 /**
2004 * Relationship between the document containing the hyperlink and the destination resource
2005 */
2006 rel: LiteralUnion<"alternate" | "dns-prefetch" | "icon" | "manifest" | "modulepreload" | "next" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "search" | "stylesheet", string>;
2007 /**
2008 * Applicable media: "screen", "print", "(max-width: 764px)"
2009 */
2010 media?: string;
2011 /**
2012 * Integrity metadata used in Subresource Integrity checks
2013 */
2014 integrity?: string;
2015 /**
2016 * Language of the linked resource
2017 */
2018 hrefLang?: string;
2019 /**
2020 * Hint for the type of the referenced resource
2021 */
2022 type?: string;
2023 /**
2024 * Referrer policy for fetches initiated by the element
2025 */
2026 referrerPolicy?: "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
2027 /**
2028 * Sizes of the icons (for rel="icon")
2029 */
2030 sizes?: string;
2031 /**
2032 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2033 */
2034 as?: LiteralUnion<"audio" | "audioworklet" | "document" | "embed" | "fetch" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt", string>;
2035 /**
2036 * Color to use when customizing a site's icon (for rel="mask-icon")
2037 */
2038 color?: string;
2039 /**
2040 * Whether the link is disabled
2041 */
2042 disabled?: boolean;
2043 /**
2044 * The title attribute has special semantics on this element: Title of the link; CSS style sheet set name.
2045 */
2046 title?: string;
2047 /**
2048 * Images to use in different situations, e.g., high-resolution displays,
2049 * small monitors, etc. (for rel="preload")
2050 */
2051 imageSrcSet?: string;
2052 /**
2053 * Image sizes for different page layouts (for rel="preload")
2054 */
2055 imageSizes?: string;
2056}
2057interface HtmlLinkPreloadImage extends HtmlLinkProps {
2058 /**
2059 * Relationship between the document containing the hyperlink and the destination resource
2060 */
2061 rel: "preload";
2062 /**
2063 * Potential destination for a preload request (for rel="preload" and rel="modulepreload")
2064 */
2065 as: "image";
2066 /**
2067 * Address of the hyperlink
2068 */
2069 href?: string;
2070 /**
2071 * Images to use in different situations, e.g., high-resolution displays,
2072 * small monitors, etc. (for rel="preload")
2073 */
2074 imageSrcSet: string;
2075 /**
2076 * Image sizes for different page layouts (for rel="preload")
2077 */
2078 imageSizes?: string;
2079}
2080/**
2081 * Represents a `<link>` element.
2082 *
2083 * WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
2084 */
2085type HtmlLinkDescriptor = (HtmlLinkProps & Pick<Required<HtmlLinkProps>, "href">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "imageSizes">) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, "href"> & {
2086 imageSizes?: never;
2087});
2088interface PageLinkDescriptor extends Omit<HtmlLinkDescriptor, "href" | "rel" | "type" | "sizes" | "imageSrcSet" | "imageSizes" | "as" | "color" | "title"> {
2089 /**
2090 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
2091 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
2092 * element. If not provided in Framework Mode, it will default to any
2093 * {@link ServerRouter | `<ServerRouter nonce>`} prop.
2094 */
2095 nonce?: string | undefined;
2096 /**
2097 * The absolute path of the page to prefetch, e.g. `/absolute/path`.
2098 */
2099 page: string;
2100}
2101type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
2102//#endregion
2103//#region lib/server-runtime/single-fetch.d.ts
2104type Serializable = undefined | null | boolean | string | symbol | number | Array<Serializable> | {
2105 [key: PropertyKey]: Serializable;
2106} | bigint | Date | URL | RegExp | Error | Map<Serializable, Serializable> | Set<Serializable> | Promise<Serializable>;
2107//#endregion
2108//#region lib/types/utils.d.ts
2109type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
2110type IsAny<T> = 0 extends 1 & T ? true : false;
2111type Func = (...args: any[]) => unknown;
2112//#endregion
2113//#region lib/types/serializes-to.d.ts
2114/**
2115 * A brand that can be applied to a type to indicate that it will serialize
2116 * to a specific type when transported to the client from a loader.
2117 * Only use this if you have additional serialization/deserialization logic
2118 * in your application.
2119 */
2120type unstable_SerializesTo<T> = {
2121 unstable__ReactRouter_SerializesTo: [T];
2122};
2123//#endregion
2124//#region lib/types/route-data.d.ts
2125type 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;
2126type VoidToUndefined<T> = Equal<T, void> extends true ? undefined : T;
2127type DataFrom<T> = IsAny<T> extends true ? undefined : T extends Func ? VoidToUndefined<Awaited<ReturnType<T>>> : undefined;
2128type ClientData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? U : T;
2129type ServerData<T> = T extends Response ? never : T extends DataWithResponseInit<infer U> ? Serialize<U> : Serialize<T>;
2130type ServerDataFrom<T> = ServerData<DataFrom<T>>;
2131type ClientDataFrom<T> = ClientData<DataFrom<T>>;
2132type ClientDataFunctionArgs<Params> = {
2133 /**
2134 * 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.
2135 *
2136 * @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.
2137 **/
2138 request: Request;
2139 /**
2140 * A URL instance representing the application location being navigated to or
2141 * fetched.
2142 *
2143 * In Framework mode, this is a normalized URL with React-Router-specific
2144 * implementation details removed (`.data` suffixes, `index`/`_routes` search
2145 * params). For the raw incoming URL, use `request.url`.
2146 */
2147 url: URL;
2148 /**
2149 * {@link https://reactrouter.com/start/framework/routing#dynamic-segments Dynamic route params} for the current route.
2150 * @example
2151 * // app/routes.ts
2152 * route("teams/:teamId", "./team.tsx"),
2153 *
2154 * // app/team.tsx
2155 * export function clientLoader({
2156 * params,
2157 * }: Route.ClientLoaderArgs) {
2158 * params.teamId;
2159 * // ^ string
2160 * }
2161 **/
2162 params: Params;
2163 /**
2164 * Matched un-interpolated route pattern for the current path (i.e., /blog/:slug).
2165 * Mostly useful as a identifier to aggregate on for logging/tracing/etc.
2166 */
2167 pattern: string;
2168 /**
2169 * An instance of `RouterContextProvider` that can be used to access context
2170 * values from your route middlewares. You may pass in initial context values
2171 * in your `<HydratedRouter getContext>` prop.
2172 */
2173 context: Readonly<RouterContextProvider>;
2174};
2175type SerializeFrom<T> = T extends ((...args: infer Args) => unknown) ? Args extends [ClientLoaderFunctionArgs | ClientActionFunctionArgs | ClientDataFunctionArgs<unknown>] ? ClientDataFrom<T> : ServerDataFrom<T> : T;
2176//#endregion
2177//#region lib/dom/ssr/routeModules.d.ts
2178/**
2179 * A function that handles data mutations for a route on the client
2180 */
2181type ClientActionFunction = (args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
2182/**
2183 * Arguments passed to a route `clientAction` function
2184 */
2185type ClientActionFunctionArgs = ActionFunctionArgs & {
2186 serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;
2187};
2188/**
2189 * A function that loads data for a route on the client
2190 */
2191type ClientLoaderFunction = ((args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & {
2192 hydrate?: boolean;
2193};
2194/**
2195 * Arguments passed to a route `clientLoader` function
2196 */
2197type ClientLoaderFunctionArgs = LoaderFunctionArgs & {
2198 serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;
2199};
2200type HeadersArgs = {
2201 loaderHeaders: Headers;
2202 parentHeaders: Headers;
2203 actionHeaders: Headers;
2204 errorHeaders: Headers | undefined;
2205};
2206/**
2207 * A function that returns HTTP headers to be used for a route. These headers
2208 * will be merged with (and take precedence over) headers from parent routes.
2209 */
2210interface HeadersFunction {
2211 (args: HeadersArgs): Headers | HeadersInit;
2212}
2213/**
2214 * A function that defines `<link>` tags to be inserted into the `<head>` of
2215 * the document on route transitions.
2216 *
2217 * @see https://reactrouter.com/start/framework/route-module#meta
2218 */
2219interface LinksFunction {
2220 (): LinkDescriptor[];
2221}
2222interface MetaMatch<RouteId extends string = string, Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown> {
2223 id: RouteId;
2224 pathname: DataRouteMatch["pathname"];
2225 loaderData: Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown;
2226 handle?: RouteHandle;
2227 params: DataRouteMatch["params"];
2228 meta: MetaDescriptor[];
2229 error?: unknown;
2230}
2231type 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]>;
2232interface MetaArgs<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2233 loaderData: (Loader extends LoaderFunction | ClientLoaderFunction ? SerializeFrom<Loader> : unknown) | undefined;
2234 params: Params;
2235 location: Location$1;
2236 matches: MetaMatches<MatchLoaders>;
2237 error?: unknown;
2238}
2239/**
2240 * A function that returns an array of data objects to use for rendering
2241 * metadata HTML tags in a route. These tags are not rendered on descendant
2242 * routes in the route hierarchy. In other words, they will only be rendered on
2243 * the route in which they are exported.
2244 *
2245 * @param Loader - The type of the current route's loader function
2246 * @param MatchLoaders - Mapping from a parent route's filepath to its loader
2247 * function type
2248 *
2249 * Note that parent route filepaths are relative to the `app/` directory.
2250 *
2251 * For example, if this meta function is for `/sales/customers/$customerId`:
2252 *
2253 * ```ts
2254 * // app/root.tsx
2255 * const loader = () => ({ hello: "world" })
2256 * export type Loader = typeof loader
2257 *
2258 * // app/routes/sales.tsx
2259 * const loader = () => ({ salesCount: 1074 })
2260 * export type Loader = typeof loader
2261 *
2262 * // app/routes/sales/customers.tsx
2263 * const loader = () => ({ customerCount: 74 })
2264 * export type Loader = typeof loader
2265 *
2266 * // app/routes/sales/customers/$customersId.tsx
2267 * import type { Loader as RootLoader } from "../../../root"
2268 * import type { Loader as SalesLoader } from "../../sales"
2269 * import type { Loader as CustomersLoader } from "../../sales/customers"
2270 *
2271 * const loader = () => ({ name: "Customer name" })
2272 *
2273 * const meta: MetaFunction<typeof loader, {
2274 * "root": RootLoader,
2275 * "routes/sales": SalesLoader,
2276 * "routes/sales/customers": CustomersLoader,
2277 * }> = ({ loaderData, matches }) => {
2278 * const { name } = loaderData
2279 * // ^? string
2280 * const { customerCount } = matches.find((match) => match.id === "routes/sales/customers").loaderData
2281 * // ^? number
2282 * const { salesCount } = matches.find((match) => match.id === "routes/sales").loaderData
2283 * // ^? number
2284 * const { hello } = matches.find((match) => match.id === "root").loaderData
2285 * // ^? "world"
2286 * }
2287 * ```
2288 */
2289interface MetaFunction<Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record<string, LoaderFunction | ClientLoaderFunction | unknown> = Record<string, unknown>> {
2290 (args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
2291}
2292type MetaDescriptor = {
2293 charSet: "utf-8";
2294} | {
2295 title: string;
2296} | {
2297 name: string;
2298 content: string;
2299} | {
2300 property: string;
2301 content: string;
2302} | {
2303 httpEquiv: string;
2304 content: string;
2305} | {
2306 "script:ld+json": LdJsonObject | LdJsonObject[];
2307} | {
2308 tagName: "meta" | "link";
2309 [name: string]: string;
2310} | {
2311 [name: string]: unknown;
2312};
2313type LdJsonObject = { [Key in string]: LdJsonValue } & { [Key in string]?: LdJsonValue | undefined };
2314type LdJsonArray = LdJsonValue[] | readonly LdJsonValue[];
2315type LdJsonPrimitive = string | number | boolean | null;
2316type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
2317/**
2318 * A React component that is rendered for a route.
2319 */
2320/**
2321 * An arbitrary object that is associated with a route.
2322 *
2323 * @see https://reactrouter.com/how-to/using-handle
2324 */
2325type RouteHandle = unknown;
2326//#endregion
2327//#region lib/rsc/server.rsc.d.ts
2328declare function getRequest(): Request;
2329declare const redirect: typeof redirect$1;
2330declare const redirectDocument: typeof redirectDocument$1;
2331declare const replace$1: typeof replace$2;
2332declare const Await: typeof Await$1;
2333type RSCRouteConfigEntryBase = {
2334 action?: ActionFunction;
2335 clientAction?: ClientActionFunction;
2336 clientLoader?: ClientLoaderFunction;
2337 clientMiddleware?: MiddlewareFunction<any>[];
2338 ErrorBoundary?: React.ComponentType<any>;
2339 handle?: any;
2340 headers?: HeadersFunction;
2341 HydrateFallback?: React.ComponentType<any>;
2342 Layout?: React.ComponentType<any>;
2343 links?: LinksFunction;
2344 loader?: LoaderFunction;
2345 meta?: MetaFunction;
2346 middleware?: MiddlewareFunction<any>[];
2347 shouldRevalidate?: ShouldRevalidateFunction;
2348};
2349type RSCRouteConfigEntry = RSCRouteConfigEntryBase & {
2350 id: string;
2351 path?: string;
2352 Component?: React.ComponentType<any>;
2353 lazy?: () => Promise<RSCRouteConfigEntryBase & ({
2354 default?: React.ComponentType<any>;
2355 Component?: never;
2356 } | {
2357 default?: never;
2358 Component?: React.ComponentType<any>;
2359 })>;
2360} & ({
2361 index: true;
2362} | {
2363 children?: RSCRouteConfigEntry[];
2364});
2365type RSCRouteConfig = Array<RSCRouteConfigEntry>;
2366type RSCRouteManifest = {
2367 clientAction?: ClientActionFunction;
2368 clientLoader?: ClientLoaderFunction;
2369 clientMiddleware?: MiddlewareFunction<any>[];
2370 element?: React.ReactElement | false;
2371 errorElement?: React.ReactElement;
2372 handle?: any;
2373 hasAction: boolean;
2374 hasComponent: boolean;
2375 hasLoader: boolean;
2376 hydrateFallbackElement?: React.ReactElement;
2377 id: string;
2378 index?: boolean;
2379 links?: LinksFunction;
2380 meta?: MetaFunction;
2381 parentId?: string;
2382 path?: string;
2383 shouldRevalidate?: ShouldRevalidateFunction;
2384};
2385type RSCRouteMatch = RSCRouteManifest & {
2386 params: Params;
2387 pathname: string;
2388 pathnameBase: string;
2389};
2390type RSCRenderPayload = {
2391 type: "render";
2392 actionData: Record<string, any> | null;
2393 basename: string | undefined;
2394 clientVersion?: string;
2395 errors: Record<string, any> | null;
2396 loaderData: Record<string, any>;
2397 location: Location$1;
2398 routeDiscovery: RouteDiscovery;
2399 matches: RSCRouteMatch[];
2400 patches?: Promise<RSCRouteManifest[]>;
2401 formState?: ReactFormState;
2402};
2403type RSCManifestPayload = {
2404 type: "manifest";
2405 patches: Promise<RSCRouteManifest[]>;
2406};
2407type RSCActionPayload = {
2408 type: "action";
2409 actionResult: Promise<unknown>;
2410 rerender?: Promise<RSCRenderPayload | RSCRedirectPayload>;
2411};
2412type RSCRedirectPayload = {
2413 type: "redirect";
2414 status: number;
2415 location: string;
2416 replace: boolean;
2417 reload: boolean;
2418 actionResult?: Promise<unknown>;
2419};
2420type RSCPayload = RSCRenderPayload | RSCManifestPayload | RSCActionPayload | RSCRedirectPayload;
2421type RSCMatch = {
2422 statusCode: number;
2423 headers: Headers;
2424 payload: RSCPayload;
2425};
2426type DecodeActionFunction = (formData: FormData) => Promise<() => Promise<unknown>>;
2427type DecodeFormStateFunction = (result: unknown, formData: FormData) => Promise<ReactFormState | undefined>;
2428type DecodeReplyFunction = (reply: FormData | string, options: {
2429 temporaryReferences: unknown;
2430}) => Promise<unknown[]>;
2431type LoadServerActionFunction = (id: string) => Promise<Function>;
2432type RouteDiscovery = {
2433 mode: "lazy";
2434 manifestPath?: string | undefined;
2435} | {
2436 mode: "initial";
2437};
2438/**
2439 * Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2440 * and returns an [RSC](https://react.dev/reference/rsc/server-components)
2441 * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2442 * encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2443 * enabled client router.
2444 *
2445 * Treat every React Server Function as a public endpoint. Server Functions are
2446 * not inherently associated with a route. Any route middleware that runs is
2447 * selected from the URL used to call a Server Function, but the client controls
2448 * both the Server Function identifier and the URL. Perform all access control
2449 * checks within each Server Function, or use a route action for
2450 * middleware-driven access control.
2451 *
2452 * @example
2453 * import {
2454 * createTemporaryReferenceSet,
2455 * decodeAction,
2456 * decodeReply,
2457 * loadServerAction,
2458 * renderToReadableStream,
2459 * } from "@vitejs/plugin-rsc/rsc";
2460 * import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2461 *
2462 * matchRSCServerRequest({
2463 * createTemporaryReferenceSet,
2464 * decodeAction,
2465 * decodeFormState,
2466 * decodeReply,
2467 * loadServerAction,
2468 * request,
2469 * routes: routes(),
2470 * generateResponse(match) {
2471 * return new Response(
2472 * renderToReadableStream(match.payload),
2473 * {
2474 * status: match.statusCode,
2475 * headers: match.headers,
2476 * }
2477 * );
2478 * },
2479 * });
2480 *
2481 * @name unstable_matchRSCServerRequest
2482 * @public
2483 * @category RSC
2484 * @mode data
2485 * @param opts Options
2486 * @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2487 * @param opts.basename The basename to use when matching the request.
2488 * @param opts.createTemporaryReferenceSet A function that returns a temporary
2489 * reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2490 * stream.
2491 * @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2492 * function, responsible for loading a server action.
2493 * @param opts.decodeFormState A function responsible for decoding form state for
2494 * progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2495 * using your `react-server-dom-xyz/server`'s `decodeFormState`.
2496 * @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2497 * function, used to decode the server function's arguments and bind them to the
2498 * implementation for invocation by the router.
2499 * @param opts.generateResponse A function responsible for using your
2500 * `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2501 * encoding the {@link unstable_RSCPayload}.
2502 * @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2503 * `loadServerAction` function, used to load a server action by ID.
2504 * @param opts.clientVersion A version derived from the client build output used
2505 * to detect stale clients during lazy route discovery.
2506 * @param opts.onError An optional error handler that will be called with any
2507 * errors that occur during the request processing.
2508 * @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2509 * to match against.
2510 * @param opts.requestContext An instance of {@link RouterContextProvider}
2511 * that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2512 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2513 * @param opts.routeDiscovery The route discovery configuration, used to determine how the router should discover new routes during navigations.
2514 * @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2515 * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2516 * that contains the [RSC](https://react.dev/reference/rsc/server-components)
2517 * data for hydration.
2518 */
2519declare function matchRSCServerRequest({
2520 allowedActionOrigins,
2521 createTemporaryReferenceSet,
2522 basename,
2523 decodeReply,
2524 requestContext,
2525 routeDiscovery,
2526 loadServerAction,
2527 decodeAction,
2528 decodeFormState,
2529 clientVersion,
2530 onError,
2531 request,
2532 routes,
2533 generateResponse: encodeResponse
2534}: {
2535 allowedActionOrigins?: string[];
2536 createTemporaryReferenceSet: () => unknown;
2537 basename?: string;
2538 decodeReply?: DecodeReplyFunction;
2539 decodeAction?: DecodeActionFunction;
2540 decodeFormState?: DecodeFormStateFunction;
2541 requestContext?: RouterContextProvider;
2542 loadServerAction?: LoadServerActionFunction;
2543 clientVersion?: string;
2544 onError?: (error: unknown) => void;
2545 request: Request;
2546 routes: RSCRouteConfigEntry[];
2547 routeDiscovery?: RouteDiscovery;
2548 generateResponse: (match: RSCMatch, {
2549 onError,
2550 temporaryReferences
2551 }: {
2552 onError(error: unknown): string | undefined;
2553 temporaryReferences: unknown;
2554 }) => Response;
2555}): Promise<Response>;
2556//#endregion
2557//#region lib/types/register.d.ts
2558/**
2559 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
2560 * React Router should handle this for you via type generation.
2561 *
2562 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
2563 */
2564interface Register {}
2565type AnyParams = Record<string, string | undefined>;
2566type AnyPages = Record<string, {
2567 params: AnyParams;
2568}>;
2569type Pages = Register extends {
2570 pages: infer Registered extends AnyPages;
2571} ? Registered : AnyPages;
2572//#endregion
2573//#region lib/href.d.ts
2574type Args = { [K in keyof Pages]: ToArgs<Pages[K]["params"]> };
2575type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [Params];
2576/**
2577 * Returns a resolved URL path for the specified route.
2578 *
2579 * Param values are percent-encoded for use in a path segment: characters that
2580 * would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
2581 * are escaped, while characters that RFC 3986 allows literally in a path
2582 * segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
2583 * encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
2584 * delimiters and must be escaped. Splat (`*`) values are encoded per segment,
2585 * preserving `/` separators.
2586 *
2587 * See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
2588 *
2589 * @example
2590 * const h = href("/:lang?/about", { lang: "en" })
2591 * // -> `/en/about`
2592 *
2593 * <Link to={href("/products/:id", { id: "abc123" })} />
2594 *
2595 * @public
2596 * @category Utils
2597 * @mode framework
2598 * @param path The route path to resolve
2599 * @param args The route params to use when resolving the path
2600 * @returns The resolved URL path
2601 */
2602declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
2603//#endregion
2604//#region lib/server-runtime/cookies.d.ts
2605interface CookieSignatureOptions {
2606 /**
2607 * An array of secrets that may be used to sign/unsign the value of a cookie.
2608 *
2609 * The array makes it easy to rotate secrets. New secrets should be added to
2610 * the beginning of the array. `cookie.serialize()` will always use the first
2611 * value in the array, but `cookie.parse()` may use any of them so that
2612 * cookies that were signed with older secrets still work.
2613 */
2614 secrets?: string[];
2615}
2616type CookieOptions = CookieParseOptions & CookieSerializeOptions & CookieSignatureOptions;
2617/**
2618 * A HTTP cookie.
2619 *
2620 * A Cookie is a logical container for metadata about a HTTP cookie; its name
2621 * and options. But it doesn't contain a value. Instead, it has `parse()` and
2622 * `serialize()` methods that allow a single instance to be reused for
2623 * parsing/encoding multiple different values.
2624 *
2625 * @see https://remix.run/utils/cookies#cookie-api
2626 */
2627interface Cookie {
2628 /**
2629 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
2630 */
2631 readonly name: string;
2632 /**
2633 * True if this cookie uses one or more secrets for verification.
2634 */
2635 readonly isSigned: boolean;
2636 /**
2637 * The Date this cookie expires.
2638 *
2639 * Note: This is calculated at access time using `maxAge` when no `expires`
2640 * option is provided to `createCookie()`.
2641 */
2642 readonly expires?: Date;
2643 /**
2644 * Parses a raw `Cookie` header and returns the value of this cookie or
2645 * `null` if it's not present.
2646 */
2647 parse(cookieHeader: string | null, options?: CookieParseOptions): Promise<any>;
2648 /**
2649 * Serializes the given value to a string and returns the `Set-Cookie`
2650 * header.
2651 */
2652 serialize(value: any, options?: CookieSerializeOptions): Promise<string>;
2653}
2654/**
2655 * Creates a logical container for managing a browser cookie from the server.
2656 *
2657 * @public
2658 * @category Utils
2659 * @mode framework
2660 * @mode data
2661 * @param name The name of the cookie.
2662 * @param cookieOptions Options for parsing and serializing the cookie.
2663 * @returns A {@link Cookie} object for parsing and serializing the cookie.
2664 */
2665declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
2666/**
2667 * A function that determines whether a value is a React Router {@link Cookie}
2668 * object.
2669 *
2670 * @public
2671 * @category Utils
2672 * @mode framework
2673 * @mode data
2674 * @param object The value to check.
2675 * @returns `true` if the value is a React Router {@link Cookie} object;
2676 * otherwise, `false`.
2677 */
2678type IsCookieFunction = (object: any) => object is Cookie;
2679/**
2680 * Returns `true` if a value is a React Router {@link Cookie} object.
2681 *
2682 * @public
2683 * @category Utils
2684 * @mode framework
2685 * @mode data
2686 * @param object The value to check.
2687 * @returns `true` if the value is a React Router {@link Cookie} object;
2688 * otherwise, `false`.
2689 */
2690declare const isCookie: IsCookieFunction;
2691//#endregion
2692//#region lib/server-runtime/sessions.d.ts
2693/**
2694 * An object of name/value pairs to be used in the session.
2695 */
2696interface SessionData {
2697 [name: string]: any;
2698}
2699/**
2700 * Session persists data across HTTP requests.
2701 *
2702 * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
2703 */
2704interface Session<Data = SessionData, FlashData = Data> {
2705 /**
2706 * A unique identifier for this session.
2707 *
2708 * Note: This will be the empty string for newly created sessions and
2709 * sessions that are not backed by a database (i.e. cookie-based sessions).
2710 */
2711 readonly id: string;
2712 /**
2713 * The raw data contained in this session.
2714 *
2715 * This is useful mostly for SessionStorage internally to access the raw
2716 * session data to persist.
2717 */
2718 readonly data: FlashSessionData<Data, FlashData>;
2719 /**
2720 * Returns `true` if the session has a value for the given `name`, `false`
2721 * otherwise.
2722 */
2723 has(name: (keyof Data | keyof FlashData) & string): boolean;
2724 /**
2725 * Returns the value for the given `name` in this session.
2726 */
2727 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;
2728 /**
2729 * Sets a value in the session for the given `name`.
2730 */
2731 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
2732 /**
2733 * Sets a value in the session that is only valid until the next `get()`.
2734 * This can be useful for temporary values, like error messages.
2735 */
2736 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
2737 /**
2738 * Removes a value from the session.
2739 */
2740 unset(name: keyof Data & string): void;
2741}
2742type FlashSessionData<Data, FlashData> = Partial<Data & { [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key] }>;
2743type FlashDataKey<Key extends string> = `__flash_${Key}__`;
2744type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
2745/**
2746 * Creates a new Session object.
2747 *
2748 * Note: This function is typically not invoked directly by application code.
2749 * Instead, use a `SessionStorage` object's `getSession` method.
2750 *
2751 * @category Utils
2752 * @param initialData The initial data for the session.
2753 * @param id The identifier for the session. Defaults to an empty string for a
2754 * new session.
2755 * @returns A new {@link Session} object.
2756 */
2757declare const createSession: CreateSessionFunction;
2758/**
2759 * A function that determines whether a value is a React Router {@link Session}
2760 * object.
2761 *
2762 * @public
2763 * @category Utils
2764 * @mode framework
2765 * @mode data
2766 * @param object The value to check.
2767 * @returns `true` if the value is a React Router {@link Session} object;
2768 * otherwise, `false`.
2769 */
2770type IsSessionFunction = (object: any) => object is Session;
2771/**
2772 * Returns `true` if a value is a React Router {@link Session} object.
2773 *
2774 * @public
2775 * @category Utils
2776 * @mode framework
2777 * @mode data
2778 * @param object The value to check.
2779 * @returns `true` if the value is a React Router {@link Session} object;
2780 * otherwise, `false`.
2781 */
2782declare const isSession: IsSessionFunction;
2783/**
2784 * SessionStorage stores session data between HTTP requests and knows how to
2785 * parse and create cookies.
2786 *
2787 * A SessionStorage creates Session objects using a `Cookie` header as input.
2788 * Then, later it generates the `Set-Cookie` header to be used in the response.
2789 */
2790interface SessionStorage<Data = SessionData, FlashData = Data> {
2791 /**
2792 * Parses a Cookie header from a HTTP request and returns the associated
2793 * Session. If there is no session associated with the cookie, this will
2794 * return a new Session with no data.
2795 */
2796 getSession: (cookieHeader?: string | null, options?: CookieParseOptions$1) => Promise<Session<Data, FlashData>>;
2797 /**
2798 * Stores all data in the Session and returns the Set-Cookie header to be
2799 * used in the HTTP response.
2800 */
2801 commitSession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2802 /**
2803 * Deletes all data associated with the Session and returns the Set-Cookie
2804 * header to be used in the HTTP response.
2805 */
2806 destroySession: (session: Session<Data, FlashData>, options?: CookieSerializeOptions$1) => Promise<string>;
2807}
2808/**
2809 * SessionIdStorageStrategy is designed to allow anyone to easily build their
2810 * own SessionStorage using `createSessionStorage(strategy)`.
2811 *
2812 * This strategy describes a common scenario where the session id is stored in
2813 * a cookie but the actual session data is stored elsewhere, usually in a
2814 * database or on disk. A set of create, read, update, and delete operations
2815 * are provided for managing the session data.
2816 */
2817interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
2818 /**
2819 * The Cookie used to store the session id, or options used to automatically
2820 * create one.
2821 */
2822 cookie?: Cookie | (CookieOptions & {
2823 name?: string;
2824 });
2825 /**
2826 * Creates a new record with the given data and returns the session id.
2827 */
2828 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
2829 /**
2830 * Returns data for a given session id, or `null` if there isn't any.
2831 */
2832 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
2833 /**
2834 * Updates data for the given session id.
2835 */
2836 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
2837 /**
2838 * Deletes data for a given session id from the data store.
2839 */
2840 deleteData: (id: string) => Promise<void>;
2841}
2842/**
2843 * Creates a SessionStorage object using a SessionIdStorageStrategy.
2844 *
2845 * Note: This is a low-level API that should only be used if none of the
2846 * existing session storage options meet your requirements.
2847 *
2848 * @category Utils
2849 * @param strategy The strategy used to store session identifiers and data.
2850 * @returns A {@link SessionStorage} object that persists session data using the
2851 * provided strategy.
2852 */
2853declare function createSessionStorage<Data = SessionData, FlashData = Data>({
2854 cookie: cookieArg,
2855 createData,
2856 readData,
2857 updateData,
2858 deleteData
2859}: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
2860//#endregion
2861//#region lib/server-runtime/sessions/cookieStorage.d.ts
2862interface CookieSessionStorageOptions {
2863 /**
2864 * The Cookie used to store the session data on the client, or options used
2865 * to automatically create one.
2866 */
2867 cookie?: SessionIdStorageStrategy["cookie"];
2868}
2869/**
2870 * Creates and returns a SessionStorage object that stores all session data
2871 * directly in the session cookie itself.
2872 *
2873 * This has the advantage that no database or other backend services are
2874 * needed, and can help to simplify some load-balanced scenarios. However, it
2875 * also has the limitation that serialized session data may not exceed the
2876 * browser's maximum cookie size. Trade-offs!
2877 *
2878 * @public
2879 * @category Utils
2880 * @mode framework
2881 * @mode data
2882 * @param options Options for creating the cookie-backed session storage.
2883 * @returns A {@link SessionStorage} object that stores all session data in its
2884 * cookie.
2885 */
2886declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({
2887 cookie: cookieArg
2888}?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
2889//#endregion
2890//#region lib/server-runtime/sessions/memoryStorage.d.ts
2891interface MemorySessionStorageOptions {
2892 /**
2893 * The Cookie used to store the session id on the client, or options used
2894 * to automatically create one.
2895 */
2896 cookie?: SessionIdStorageStrategy["cookie"];
2897}
2898/**
2899 * Creates and returns a simple in-memory SessionStorage object.
2900 *
2901 * Intended for local development and testing. It does not scale beyond a single
2902 * process, and all session data is lost when the server process stops/restarts.
2903 *
2904 * @public
2905 * @category Utils
2906 * @mode framework
2907 * @mode data
2908 * @param options Options for creating the in-memory session storage.
2909 * @returns A {@link SessionStorage} object that stores session data in memory.
2910 */
2911declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({
2912 cookie
2913}?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
2914//#endregion
2915export { 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