index.d.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. import { n as Router, o as RouteModules, p as DataStrategyFunction, q as MiddlewareEnabled, c as RouterContextProvider, r as AppLoadContext, T as To, s as NavigateOptions, B as BlockerFunction, t as Blocker, v as SerializeFrom, w as RelativeRoutingType, L as Location, x as ParamParseKey, y as Path, z as PathPattern, E as PathMatch, U as UIMatch, I as Navigation, J as Action, P as Params, K as RouteObject, G as GetLoaderData, m as GetActionData, O as InitialEntry, Q as HydrationState, V as IndexRouteObject, W as RouteComponentType, X as HydrateFallbackType, Y as ErrorBoundaryType, d as LoaderFunction, A as ActionFunction, M as MetaFunction, b as LinksFunction, Z as NonIndexRouteObject, _ as Equal, $ as RouterState, a0 as PatchRoutesOnNavigationFunction, a1 as DataRouteObject, a as ClientLoaderFunction } from './instrumentation-BB0wRuqz.js';
  2. export { ac as ActionFunctionArgs, b1 as Await, aQ as AwaitProps, C as ClientActionFunction, bd as ClientActionFunctionArgs, be as ClientLoaderFunctionArgs, aL as DataRouteMatch, ad as DataStrategyFunctionArgs, ae as DataStrategyMatch, D as DataStrategyResult, ag as ErrorResponse, a6 as Fetcher, ah as FormEncType, ai as FormMethod, bj as Future, a3 as GetScrollPositionFunction, a4 as GetScrollRestorationKeyFunction, aj as HTMLFormMethod, bf as HeadersArgs, H as HeadersFunction, bi as HtmlLinkDescriptor, aB as IDLE_BLOCKER, aA as IDLE_FETCHER, az as IDLE_NAVIGATION, aR as IndexRouteProps, aT as LayoutRouteProps, ak as LazyRouteFunction, f as LinkDescriptor, al as LoaderFunctionArgs, b2 as MemoryRouter, aU as MemoryRouterOpts, aV as MemoryRouterProps, bg as MetaArgs, h as MetaDescriptor, am as MiddlewareFunction, b3 as Navigate, aW as NavigateProps, a7 as NavigationStates, aM as Navigator, b4 as Outlet, aX as OutletProps, bh as PageLinkDescriptor, aN as PatchRoutesOnNavigationFunctionArgs, an as PathParam, aY as PathRouteProps, ao as RedirectFunction, ab as RevalidationState, b5 as Route, aO as RouteMatch, aZ as RouteProps, b6 as Router, ap as RouterContext, aa as RouterFetchOptions, e as RouterInit, a9 as RouterNavigateOptions, a_ as RouterProps, b7 as RouterProvider, a$ as RouterProviderProps, a8 as RouterSubscriber, b8 as Routes, b0 as RoutesProps, S as ShouldRevalidateFunction, aq as ShouldRevalidateFunctionArgs, a2 as StaticHandler, a5 as StaticHandlerContext, aP as UNSAFE_AwaitContextProvider, bp as UNSAFE_DataRouterContext, bq as UNSAFE_DataRouterStateContext, af as UNSAFE_DataWithResponseInit, bo as UNSAFE_ErrorResponseImpl, br as UNSAFE_FetchersContext, bs as UNSAFE_LocationContext, bt as UNSAFE_NavigationContext, bu as UNSAFE_RouteContext, bv as UNSAFE_ViewTransitionContext, by as UNSAFE_WithComponentProps, bC as UNSAFE_WithErrorBoundaryProps, bA as UNSAFE_WithHydrateFallbackProps, bl as UNSAFE_createBrowserHistory, bn as UNSAFE_createRouter, bw as UNSAFE_hydrationRouteProperties, bm as UNSAFE_invariant, bx as UNSAFE_mapRouteProperties, bz as UNSAFE_withComponentProps, bD as UNSAFE_withErrorBoundaryProps, bB as UNSAFE_withHydrateFallbackProps, ar as createContext, b9 as createMemoryRouter, as as createPath, ba as createRoutesFromChildren, bb as createRoutesFromElements, aC as data, aD as generatePath, aE as isRouteErrorResponse, aF as matchPath, aG as matchRoutes, at as parsePath, aH as redirect, aI as redirectDocument, bc as renderMatches, aJ as replace, aK as resolvePath, u as unstable_ClientInstrumentation, aS as unstable_ClientOnErrorFunction, av as unstable_InstrumentRequestHandlerFunction, ax as unstable_InstrumentRouteFunction, aw as unstable_InstrumentRouterFunction, ay as unstable_InstrumentationHandlerResult, bk as unstable_SerializesTo, au as unstable_ServerInstrumentation } from './instrumentation-BB0wRuqz.js';
  3. import * as React from 'react';
  4. import React__default, { ReactElement } from 'react';
  5. import { a as RouteModules$1, P as Pages } from './register-ODDAAYlf.js';
  6. export { b as Register } from './register-ODDAAYlf.js';
  7. import { A as AssetsManifest, S as ServerBuild, E as EntryContext, F as FutureConfig } from './index-react-server-client-CCjKYJTH.js';
  8. export { l as BrowserRouter, B as BrowserRouterProps, D as DOMRouterOpts, a1 as DiscoverBehavior, c as FetcherFormProps, h as FetcherSubmitFunction, G as FetcherSubmitOptions, i as FetcherWithComponents, q as Form, d as FormProps, a2 as HandleDataRequestFunction, a3 as HandleDocumentRequestFunction, a4 as HandleErrorFunction, m as HashRouter, H as HashRouterProps, a as HistoryRouterProps, n as Link, L as LinkProps, X as Links, _ as LinksProps, W as Meta, p as NavLink, N as NavLinkProps, b as NavLinkRenderProps, P as ParamKeyValuePair, a0 as PrefetchBehavior, Z as PrefetchPageLinks, Y as Scripts, $ as ScriptsProps, r as ScrollRestoration, e as ScrollRestorationProps, a5 as ServerEntryModule, f as SetURLSearchParams, T as StaticRouter, M as StaticRouterProps, V as StaticRouterProvider, O as StaticRouterProviderProps, g as SubmitFunction, I as SubmitOptions, J as SubmitTarget, a6 as UNSAFE_FrameworkContext, a7 as UNSAFE_createClientRoutes, a8 as UNSAFE_createClientRoutesWithHMRRevalidationOptOut, a9 as UNSAFE_shouldHydrateRouteLoader, aa as UNSAFE_useScrollRestoration, U as URLSearchParamsInit, j as createBrowserRouter, k as createHashRouter, K as createSearchParams, Q as createStaticHandler, R as createStaticRouter, o as unstable_HistoryRouter, z as unstable_usePrompt, y as useBeforeUnload, w as useFetcher, x as useFetchers, v as useFormAction, u as useLinkClickHandler, s as useSearchParams, t as useSubmit, C as useViewTransitionState } from './index-react-server-client-CCjKYJTH.js';
  9. import { ParseOptions, SerializeOptions } from 'cookie';
  10. export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
  11. import { e as RSCPayload, m as matchRSCServerRequest } from './browser-BpxEZgZC.js';
  12. export { B as unstable_BrowserCreateFromReadableStreamFunction, D as unstable_DecodeActionFunction, a as unstable_DecodeFormStateFunction, b as unstable_DecodeReplyFunction, E as unstable_EncodeReplyFunction, L as unstable_LoadServerActionFunction, g as unstable_RSCHydratedRouterProps, d as unstable_RSCManifestPayload, h as unstable_RSCMatch, f as unstable_RSCRenderPayload, l as unstable_RSCRouteConfig, k as unstable_RSCRouteConfigEntry, i as unstable_RSCRouteManifest, j as unstable_RSCRouteMatch } from './browser-BpxEZgZC.js';
  13. declare const SingleFetchRedirectSymbol: unique symbol;
  14. declare function getTurboStreamSingleFetchDataStrategy(getRouter: () => Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, basename: string | undefined): DataStrategyFunction;
  15. declare function decodeViaTurboStream(body: ReadableStream<Uint8Array>, global: Window | typeof globalThis): Promise<{
  16. done: Promise<undefined>;
  17. value: unknown;
  18. }>;
  19. /**
  20. * The mode to use when running the server.
  21. */
  22. declare enum ServerMode {
  23. Development = "development",
  24. Production = "production",
  25. Test = "test"
  26. }
  27. type RequestHandler = (request: Request, loadContext?: MiddlewareEnabled extends true ? RouterContextProvider : AppLoadContext) => Promise<Response>;
  28. type CreateRequestHandlerFunction = (build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>), mode?: string) => RequestHandler;
  29. declare const createRequestHandler: CreateRequestHandlerFunction;
  30. /**
  31. * Resolves a URL against the current {@link Location}.
  32. *
  33. * @example
  34. * import { useHref } from "react-router";
  35. *
  36. * function SomeComponent() {
  37. * let href = useHref("some/where");
  38. * // "/resolved/some/where"
  39. * }
  40. *
  41. * @public
  42. * @category Hooks
  43. * @param to The path to resolve
  44. * @param options Options
  45. * @param options.relative Defaults to `"route"` so routing is relative to the
  46. * route tree.
  47. * Set to `"path"` to make relative routing operate against path segments.
  48. * @returns The resolved href string
  49. */
  50. declare function useHref(to: To, { relative }?: {
  51. relative?: RelativeRoutingType;
  52. }): string;
  53. /**
  54. * Returns `true` if this component is a descendant of a {@link Router}, useful
  55. * to ensure a component is used within a {@link Router}.
  56. *
  57. * @public
  58. * @category Hooks
  59. * @mode framework
  60. * @mode data
  61. * @returns Whether the component is within a {@link Router} context
  62. */
  63. declare function useInRouterContext(): boolean;
  64. /**
  65. * Returns the current {@link Location}. This can be useful if you'd like to
  66. * perform some side effect whenever it changes.
  67. *
  68. * @example
  69. * import * as React from 'react'
  70. * import { useLocation } from 'react-router'
  71. *
  72. * function SomeComponent() {
  73. * let location = useLocation()
  74. *
  75. * React.useEffect(() => {
  76. * // Google Analytics
  77. * ga('send', 'pageview')
  78. * }, [location]);
  79. *
  80. * return (
  81. * // ...
  82. * );
  83. * }
  84. *
  85. * @public
  86. * @category Hooks
  87. * @returns The current {@link Location} object
  88. */
  89. declare function useLocation(): Location;
  90. /**
  91. * Returns the current {@link Navigation} action which describes how the router
  92. * came to the current {@link Location}, either by a pop, push, or replace on
  93. * the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack.
  94. *
  95. * @public
  96. * @category Hooks
  97. * @returns The current {@link NavigationType} (`"POP"`, `"PUSH"`, or `"REPLACE"`)
  98. */
  99. declare function useNavigationType(): Action;
  100. /**
  101. * Returns a {@link PathMatch} object if the given pattern matches the current URL.
  102. * This is useful for components that need to know "active" state, e.g.
  103. * {@link NavLink | `<NavLink>`}.
  104. *
  105. * @public
  106. * @category Hooks
  107. * @param pattern The pattern to match against the current {@link Location}
  108. * @returns The path match object if the pattern matches, `null` otherwise
  109. */
  110. declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;
  111. /**
  112. * The interface for the `navigate` function returned from {@link useNavigate}.
  113. */
  114. interface NavigateFunction {
  115. (to: To, options?: NavigateOptions): void | Promise<void>;
  116. (delta: number): void | Promise<void>;
  117. }
  118. /**
  119. * Returns a function that lets you navigate programmatically in the browser in
  120. * response to user interactions or effects.
  121. *
  122. * It's often better to use {@link redirect} in [`action`](../../start/framework/route-module#action)/[`loader`](../../start/framework/route-module#loader)
  123. * functions than this hook.
  124. *
  125. * The returned function signature is `navigate(to, options?)`/`navigate(delta)` where:
  126. *
  127. * * `to` can be a string path, a {@link To} object, or a number (delta)
  128. * * `options` contains options for modifying the navigation
  129. * * These options work in all modes (Framework, Data, and Declarative):
  130. * * `relative`: `"route"` or `"path"` to control relative routing logic
  131. * * `replace`: Replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History) stack
  132. * * `state`: Optional [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) to include with the new {@link Location}
  133. * * These options only work in Framework and Data modes:
  134. * * `flushSync`: Wrap the DOM updates in [`ReactDom.flushSync`](https://react.dev/reference/react-dom/flushSync)
  135. * * `preventScrollReset`: Do not scroll back to the top of the page after navigation
  136. * * `viewTransition`: Enable [`document.startViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for this navigation
  137. *
  138. * @example
  139. * import { useNavigate } from "react-router";
  140. *
  141. * function SomeComponent() {
  142. * let navigate = useNavigate();
  143. * return (
  144. * <button onClick={() => navigate(-1)}>
  145. * Go Back
  146. * </button>
  147. * );
  148. * }
  149. *
  150. * @additionalExamples
  151. * ### Navigate to another path
  152. *
  153. * ```tsx
  154. * navigate("/some/route");
  155. * navigate("/some/route?search=param");
  156. * ```
  157. *
  158. * ### Navigate with a {@link To} object
  159. *
  160. * All properties are optional.
  161. *
  162. * ```tsx
  163. * navigate({
  164. * pathname: "/some/route",
  165. * search: "?search=param",
  166. * hash: "#hash",
  167. * state: { some: "state" },
  168. * });
  169. * ```
  170. *
  171. * If you use `state`, that will be available on the {@link Location} object on
  172. * the next page. Access it with `useLocation().state` (see {@link useLocation}).
  173. *
  174. * ### Navigate back or forward in the history stack
  175. *
  176. * ```tsx
  177. * // back
  178. * // often used to close modals
  179. * navigate(-1);
  180. *
  181. * // forward
  182. * // often used in a multistep wizard workflows
  183. * navigate(1);
  184. * ```
  185. *
  186. * Be cautious with `navigate(number)`. If your application can load up to a
  187. * route that has a button that tries to navigate forward/back, there may not be
  188. * a `[`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
  189. * entry to go back or forward to, or it can go somewhere you don't expect
  190. * (like a different domain).
  191. *
  192. * Only use this if you're sure they will have an entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
  193. * stack to navigate to.
  194. *
  195. * ### Replace the current entry in the history stack
  196. *
  197. * This will remove the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
  198. * stack, replacing it with a new one, similar to a server side redirect.
  199. *
  200. * ```tsx
  201. * navigate("/some/route", { replace: true });
  202. * ```
  203. *
  204. * ### Prevent Scroll Reset
  205. *
  206. * [MODES: framework, data]
  207. *
  208. * <br/>
  209. * <br/>
  210. *
  211. * To prevent {@link ScrollRestoration | `<ScrollRestoration>`} from resetting
  212. * the scroll position, use the `preventScrollReset` option.
  213. *
  214. * ```tsx
  215. * navigate("?some-tab=1", { preventScrollReset: true });
  216. * ```
  217. *
  218. * For example, if you have a tab interface connected to search params in the
  219. * middle of a page, and you don't want it to scroll to the top when a tab is
  220. * clicked.
  221. *
  222. * ### Return Type Augmentation
  223. *
  224. * Internally, `useNavigate` uses a separate implementation when you are in
  225. * Declarative mode versus Data/Framework mode - the primary difference being
  226. * that the latter is able to return a stable reference that does not change
  227. * identity across navigations. The implementation in Data/Framework mode also
  228. * returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
  229. * that resolves when the navigation is completed. This means the return type of
  230. * `useNavigate` is `void | Promise<void>`. This is accurate, but can lead to
  231. * some red squigglies based on the union in the return value:
  232. *
  233. * - If you're using `typescript-eslint`, you may see errors from
  234. * [`@typescript-eslint/no-floating-promises`](https://typescript-eslint.io/rules/no-floating-promises)
  235. * - In Framework/Data mode, `React.use(navigate())` will show a false-positive
  236. * `Argument of type 'void | Promise<void>' is not assignable to parameter of
  237. * type 'Usable<void>'` error
  238. *
  239. * The easiest way to work around these issues is to augment the type based on the
  240. * router you're using:
  241. *
  242. * ```ts
  243. * // If using <BrowserRouter>
  244. * declare module "react-router" {
  245. * interface NavigateFunction {
  246. * (to: To, options?: NavigateOptions): void;
  247. * (delta: number): void;
  248. * }
  249. * }
  250. *
  251. * // If using <RouterProvider> or Framework mode
  252. * declare module "react-router" {
  253. * interface NavigateFunction {
  254. * (to: To, options?: NavigateOptions): Promise<void>;
  255. * (delta: number): Promise<void>;
  256. * }
  257. * }
  258. * ```
  259. *
  260. * @public
  261. * @category Hooks
  262. * @returns A navigate function for programmatic navigation
  263. */
  264. declare function useNavigate(): NavigateFunction;
  265. /**
  266. * Returns the parent route {@link Outlet | `<Outlet context>`}.
  267. *
  268. * Often parent routes manage state or other values you want shared with child
  269. * routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
  270. * if you like, but this is such a common situation that it's built-into
  271. * {@link Outlet | `<Outlet>`}.
  272. *
  273. * ```tsx
  274. * // Parent route
  275. * function Parent() {
  276. * const [count, setCount] = React.useState(0);
  277. * return <Outlet context={[count, setCount]} />;
  278. * }
  279. * ```
  280. *
  281. * ```tsx
  282. * // Child route
  283. * import { useOutletContext } from "react-router";
  284. *
  285. * function Child() {
  286. * const [count, setCount] = useOutletContext();
  287. * const increment = () => setCount((c) => c + 1);
  288. * return <button onClick={increment}>{count}</button>;
  289. * }
  290. * ```
  291. *
  292. * If you're using TypeScript, we recommend the parent component provide a
  293. * custom hook for accessing the context value. This makes it easier for
  294. * consumers to get nice typings, control consumers, and know who's consuming
  295. * the context value.
  296. *
  297. * Here's a more realistic example:
  298. *
  299. * ```tsx filename=src/routes/dashboard.tsx lines=[14,20]
  300. * import { useState } from "react";
  301. * import { Outlet, useOutletContext } from "react-router";
  302. *
  303. * import type { User } from "./types";
  304. *
  305. * type ContextType = { user: User | null };
  306. *
  307. * export default function Dashboard() {
  308. * const [user, setUser] = useState<User | null>(null);
  309. *
  310. * return (
  311. * <div>
  312. * <h1>Dashboard</h1>
  313. * <Outlet context={{ user } satisfies ContextType} />
  314. * </div>
  315. * );
  316. * }
  317. *
  318. * export function useUser() {
  319. * return useOutletContext<ContextType>();
  320. * }
  321. * ```
  322. *
  323. * ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
  324. * import { useUser } from "../dashboard";
  325. *
  326. * export default function DashboardMessages() {
  327. * const { user } = useUser();
  328. * return (
  329. * <div>
  330. * <h2>Messages</h2>
  331. * <p>Hello, {user.name}!</p>
  332. * </div>
  333. * );
  334. * }
  335. * ```
  336. *
  337. * @public
  338. * @category Hooks
  339. * @returns The context value passed to the parent {@link Outlet} component
  340. */
  341. declare function useOutletContext<Context = unknown>(): Context;
  342. /**
  343. * Returns the element for the child route at this level of the route
  344. * hierarchy. Used internally by {@link Outlet | `<Outlet>`} to render child
  345. * routes.
  346. *
  347. * @public
  348. * @category Hooks
  349. * @param context The context to pass to the outlet
  350. * @returns The child route element or `null` if no child routes match
  351. */
  352. declare function useOutlet(context?: unknown): React.ReactElement | null;
  353. /**
  354. * Returns an object of key/value-pairs of the dynamic params from the current
  355. * URL that were matched by the routes. Child routes inherit all params from
  356. * their parent routes.
  357. *
  358. * Assuming a route pattern like `/posts/:postId` is matched by `/posts/123`
  359. * then `params.postId` will be `"123"`.
  360. *
  361. * @example
  362. * import { useParams } from "react-router";
  363. *
  364. * function SomeComponent() {
  365. * let params = useParams();
  366. * params.postId;
  367. * }
  368. *
  369. * @additionalExamples
  370. * ### Basic Usage
  371. *
  372. * ```tsx
  373. * import { useParams } from "react-router";
  374. *
  375. * // given a route like:
  376. * <Route path="/posts/:postId" element={<Post />} />;
  377. *
  378. * // or a data route like:
  379. * createBrowserRouter([
  380. * {
  381. * path: "/posts/:postId",
  382. * component: Post,
  383. * },
  384. * ]);
  385. *
  386. * // or in routes.ts
  387. * route("/posts/:postId", "routes/post.tsx");
  388. * ```
  389. *
  390. * Access the params in a component:
  391. *
  392. * ```tsx
  393. * import { useParams } from "react-router";
  394. *
  395. * export default function Post() {
  396. * let params = useParams();
  397. * return <h1>Post: {params.postId}</h1>;
  398. * }
  399. * ```
  400. *
  401. * ### Multiple Params
  402. *
  403. * Patterns can have multiple params:
  404. *
  405. * ```tsx
  406. * "/posts/:postId/comments/:commentId";
  407. * ```
  408. *
  409. * All will be available in the params object:
  410. *
  411. * ```tsx
  412. * import { useParams } from "react-router";
  413. *
  414. * export default function Post() {
  415. * let params = useParams();
  416. * return (
  417. * <h1>
  418. * Post: {params.postId}, Comment: {params.commentId}
  419. * </h1>
  420. * );
  421. * }
  422. * ```
  423. *
  424. * ### Catchall Params
  425. *
  426. * Catchall params are defined with `*`:
  427. *
  428. * ```tsx
  429. * "/files/*";
  430. * ```
  431. *
  432. * The matched value will be available in the params object as follows:
  433. *
  434. * ```tsx
  435. * import { useParams } from "react-router";
  436. *
  437. * export default function File() {
  438. * let params = useParams();
  439. * let catchall = params["*"];
  440. * // ...
  441. * }
  442. * ```
  443. *
  444. * You can destructure the catchall param:
  445. *
  446. * ```tsx
  447. * export default function File() {
  448. * let { "*": catchall } = useParams();
  449. * console.log(catchall);
  450. * }
  451. * ```
  452. *
  453. * @public
  454. * @category Hooks
  455. * @returns An object containing the dynamic route parameters
  456. */
  457. declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
  458. ParamsOrKey
  459. ] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
  460. /**
  461. * Resolves the pathname of the given `to` value against the current
  462. * {@link Location}. Similar to {@link useHref}, but returns a
  463. * {@link Path} instead of a string.
  464. *
  465. * @example
  466. * import { useResolvedPath } from "react-router";
  467. *
  468. * function SomeComponent() {
  469. * // if the user is at /dashboard/profile
  470. * let path = useResolvedPath("../accounts");
  471. * path.pathname; // "/dashboard/accounts"
  472. * path.search; // ""
  473. * path.hash; // ""
  474. * }
  475. *
  476. * @public
  477. * @category Hooks
  478. * @param to The path to resolve
  479. * @param options Options
  480. * @param options.relative Defaults to `"route"` so routing is relative to the route tree.
  481. * Set to `"path"` to make relative routing operate against path segments.
  482. * @returns The resolved {@link Path} object with `pathname`, `search`, and `hash`
  483. */
  484. declare function useResolvedPath(to: To, { relative }?: {
  485. relative?: RelativeRoutingType;
  486. }): Path;
  487. /**
  488. * Hook version of {@link Routes | `<Routes>`} that uses objects instead of
  489. * components. These objects have the same properties as the component props.
  490. * The return value of `useRoutes` is either a valid React element you can use
  491. * to render the route tree, or `null` if nothing matched.
  492. *
  493. * @example
  494. * import { useRoutes } from "react-router";
  495. *
  496. * function App() {
  497. * let element = useRoutes([
  498. * {
  499. * path: "/",
  500. * element: <Dashboard />,
  501. * children: [
  502. * {
  503. * path: "messages",
  504. * element: <DashboardMessages />,
  505. * },
  506. * { path: "tasks", element: <DashboardTasks /> },
  507. * ],
  508. * },
  509. * { path: "team", element: <AboutPage /> },
  510. * ]);
  511. *
  512. * return element;
  513. * }
  514. *
  515. * @public
  516. * @category Hooks
  517. * @param routes An array of {@link RouteObject}s that define the route hierarchy
  518. * @param locationArg An optional {@link Location} object or pathname string to
  519. * use instead of the current {@link Location}
  520. * @returns A React element to render the matched route, or `null` if no routes matched
  521. */
  522. declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
  523. /**
  524. * Returns the current {@link Navigation}, defaulting to an "idle" navigation
  525. * when no navigation is in progress. You can use this to render pending UI
  526. * (like a global spinner) or read [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
  527. * from a form navigation.
  528. *
  529. * @example
  530. * import { useNavigation } from "react-router";
  531. *
  532. * function SomeComponent() {
  533. * let navigation = useNavigation();
  534. * navigation.state;
  535. * navigation.formData;
  536. * // etc.
  537. * }
  538. *
  539. * @public
  540. * @category Hooks
  541. * @mode framework
  542. * @mode data
  543. * @returns The current {@link Navigation} object
  544. */
  545. declare function useNavigation(): Navigation;
  546. /**
  547. * Revalidate the data on the page for reasons outside of normal data mutations
  548. * like [`Window` focus](https://developer.mozilla.org/en-US/docs/Web/API/Window/focus_event)
  549. * or polling on an interval.
  550. *
  551. * Note that page data is already revalidated automatically after actions.
  552. * If you find yourself using this for normal CRUD operations on your data in
  553. * response to user interactions, you're probably not taking advantage of the
  554. * other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do
  555. * this automatically.
  556. *
  557. * @example
  558. * import { useRevalidator } from "react-router";
  559. *
  560. * function WindowFocusRevalidator() {
  561. * const revalidator = useRevalidator();
  562. *
  563. * useFakeWindowFocus(() => {
  564. * revalidator.revalidate();
  565. * });
  566. *
  567. * return (
  568. * <div hidden={revalidator.state === "idle"}>
  569. * Revalidating...
  570. * </div>
  571. * );
  572. * }
  573. *
  574. * @public
  575. * @category Hooks
  576. * @mode framework
  577. * @mode data
  578. * @returns An object with a `revalidate` function and the current revalidation
  579. * `state`
  580. */
  581. declare function useRevalidator(): {
  582. revalidate: () => Promise<void>;
  583. state: Router["state"]["revalidation"];
  584. };
  585. /**
  586. * Returns the active route matches, useful for accessing `loaderData` for
  587. * parent/child routes or the route [`handle`](../../start/framework/route-module#handle)
  588. * property
  589. *
  590. * @public
  591. * @category Hooks
  592. * @mode framework
  593. * @mode data
  594. * @returns An array of {@link UIMatch | UI matches} for the current route hierarchy
  595. */
  596. declare function useMatches(): UIMatch[];
  597. /**
  598. * Returns the data from the closest route
  599. * [`loader`](../../start/framework/route-module#loader) or
  600. * [`clientLoader`](../../start/framework/route-module#clientloader).
  601. *
  602. * @example
  603. * import { useLoaderData } from "react-router";
  604. *
  605. * export async function loader() {
  606. * return await fakeDb.invoices.findAll();
  607. * }
  608. *
  609. * export default function Invoices() {
  610. * let invoices = useLoaderData<typeof loader>();
  611. * // ...
  612. * }
  613. *
  614. * @public
  615. * @category Hooks
  616. * @mode framework
  617. * @mode data
  618. * @returns The data returned from the route's [`loader`](../../start/framework/route-module#loader) or [`clientLoader`](../../start/framework/route-module#clientloader) function
  619. */
  620. declare function useLoaderData<T = any>(): SerializeFrom<T>;
  621. /**
  622. * Returns the [`loader`](../../start/framework/route-module#loader) data for a
  623. * given route by route ID.
  624. *
  625. * Route IDs are created automatically. They are simply the path of the route file
  626. * relative to the app folder without the extension.
  627. *
  628. * | Route Filename | Route ID |
  629. * | ---------------------------- | ---------------------- |
  630. * | `app/root.tsx` | `"root"` |
  631. * | `app/routes/teams.tsx` | `"routes/teams"` |
  632. * | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
  633. *
  634. * @example
  635. * import { useRouteLoaderData } from "react-router";
  636. *
  637. * function SomeComponent() {
  638. * const { user } = useRouteLoaderData("root");
  639. * }
  640. *
  641. * // You can also specify your own route ID's manually in your routes.ts file:
  642. * route("/", "containers/app.tsx", { id: "app" })
  643. * useRouteLoaderData("app");
  644. *
  645. * @public
  646. * @category Hooks
  647. * @mode framework
  648. * @mode data
  649. * @param routeId The ID of the route to return loader data from
  650. * @returns The data returned from the specified route's [`loader`](../../start/framework/route-module#loader)
  651. * function, or `undefined` if not found
  652. */
  653. declare function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined;
  654. /**
  655. * Returns the [`action`](../../start/framework/route-module#action) data from
  656. * the most recent `POST` navigation form submission or `undefined` if there
  657. * hasn't been one.
  658. *
  659. * @example
  660. * import { Form, useActionData } from "react-router";
  661. *
  662. * export async function action({ request }) {
  663. * const body = await request.formData();
  664. * const name = body.get("visitorsName");
  665. * return { message: `Hello, ${name}` };
  666. * }
  667. *
  668. * export default function Invoices() {
  669. * const data = useActionData();
  670. * return (
  671. * <Form method="post">
  672. * <input type="text" name="visitorsName" />
  673. * {data ? data.message : "Waiting..."}
  674. * </Form>
  675. * );
  676. * }
  677. *
  678. * @public
  679. * @category Hooks
  680. * @mode framework
  681. * @mode data
  682. * @returns The data returned from the route's [`action`](../../start/framework/route-module#action)
  683. * function, or `undefined` if no [`action`](../../start/framework/route-module#action)
  684. * has been called
  685. */
  686. declare function useActionData<T = any>(): SerializeFrom<T> | undefined;
  687. /**
  688. * Accesses the error thrown during an
  689. * [`action`](../../start/framework/route-module#action),
  690. * [`loader`](../../start/framework/route-module#loader),
  691. * or component render to be used in a route module
  692. * [`ErrorBoundary`](../../start/framework/route-module#errorboundary).
  693. *
  694. * @example
  695. * export function ErrorBoundary() {
  696. * const error = useRouteError();
  697. * return <div>{error.message}</div>;
  698. * }
  699. *
  700. * @public
  701. * @category Hooks
  702. * @mode framework
  703. * @mode data
  704. * @returns The error that was thrown during route [loading](../../start/framework/route-module#loader),
  705. * [`action`](../../start/framework/route-module#action) execution, or rendering
  706. */
  707. declare function useRouteError(): unknown;
  708. /**
  709. * Returns the resolved promise value from the closest {@link Await | `<Await>`}.
  710. *
  711. * @example
  712. * function SomeDescendant() {
  713. * const value = useAsyncValue();
  714. * // ...
  715. * }
  716. *
  717. * // somewhere in your app
  718. * <Await resolve={somePromise}>
  719. * <SomeDescendant />
  720. * </Await>;
  721. *
  722. * @public
  723. * @category Hooks
  724. * @mode framework
  725. * @mode data
  726. * @returns The resolved value from the nearest {@link Await} component
  727. */
  728. declare function useAsyncValue(): unknown;
  729. /**
  730. * Returns the rejection value from the closest {@link Await | `<Await>`}.
  731. *
  732. * @example
  733. * import { Await, useAsyncError } from "react-router";
  734. *
  735. * function ErrorElement() {
  736. * const error = useAsyncError();
  737. * return (
  738. * <p>Uh Oh, something went wrong! {error.message}</p>
  739. * );
  740. * }
  741. *
  742. * // somewhere in your app
  743. * <Await
  744. * resolve={promiseThatRejects}
  745. * errorElement={<ErrorElement />}
  746. * />;
  747. *
  748. * @public
  749. * @category Hooks
  750. * @mode framework
  751. * @mode data
  752. * @returns The error that was thrown in the nearest {@link Await} component
  753. */
  754. declare function useAsyncError(): unknown;
  755. /**
  756. * Allow the application to block navigations within the SPA and present the
  757. * user a confirmation dialog to confirm the navigation. Mostly used to avoid
  758. * using half-filled form data. This does not handle hard-reloads or
  759. * cross-origin navigations.
  760. *
  761. * The {@link Blocker} object returned by the hook has the following properties:
  762. *
  763. * - **`state`**
  764. * - `unblocked` - the blocker is idle and has not prevented any navigation
  765. * - `blocked` - the blocker has prevented a navigation
  766. * - `proceeding` - the blocker is proceeding through from a blocked navigation
  767. * - **`location`**
  768. * - When in a `blocked` state, this represents the {@link Location} to which
  769. * we blocked a navigation. When in a `proceeding` state, this is the
  770. * location being navigated to after a `blocker.proceed()` call.
  771. * - **`proceed()`**
  772. * - When in a `blocked` state, you may call `blocker.proceed()` to proceed to
  773. * the blocked location.
  774. * - **`reset()`**
  775. * - When in a `blocked` state, you may call `blocker.reset()` to return the
  776. * blocker to an `unblocked` state and leave the user at the current
  777. * location.
  778. *
  779. * @example
  780. * // Boolean version
  781. * let blocker = useBlocker(value !== "");
  782. *
  783. * // Function version
  784. * let blocker = useBlocker(
  785. * ({ currentLocation, nextLocation, historyAction }) =>
  786. * value !== "" &&
  787. * currentLocation.pathname !== nextLocation.pathname
  788. * );
  789. *
  790. * @additionalExamples
  791. * ```tsx
  792. * import { useCallback, useState } from "react";
  793. * import { BlockerFunction, useBlocker } from "react-router";
  794. *
  795. * export function ImportantForm() {
  796. * const [value, setValue] = useState("");
  797. *
  798. * const shouldBlock = useCallback<BlockerFunction>(
  799. * () => value !== "",
  800. * [value]
  801. * );
  802. * const blocker = useBlocker(shouldBlock);
  803. *
  804. * return (
  805. * <form
  806. * onSubmit={(e) => {
  807. * e.preventDefault();
  808. * setValue("");
  809. * if (blocker.state === "blocked") {
  810. * blocker.proceed();
  811. * }
  812. * }}
  813. * >
  814. * <input
  815. * name="data"
  816. * value={value}
  817. * onChange={(e) => setValue(e.target.value)}
  818. * />
  819. *
  820. * <button type="submit">Save</button>
  821. *
  822. * {blocker.state === "blocked" ? (
  823. * <>
  824. * <p style={{ color: "red" }}>
  825. * Blocked the last navigation to
  826. * </p>
  827. * <button
  828. * type="button"
  829. * onClick={() => blocker.proceed()}
  830. * >
  831. * Let me through
  832. * </button>
  833. * <button
  834. * type="button"
  835. * onClick={() => blocker.reset()}
  836. * >
  837. * Keep me here
  838. * </button>
  839. * </>
  840. * ) : blocker.state === "proceeding" ? (
  841. * <p style={{ color: "orange" }}>
  842. * Proceeding through blocked navigation
  843. * </p>
  844. * ) : (
  845. * <p style={{ color: "green" }}>
  846. * Blocker is currently unblocked
  847. * </p>
  848. * )}
  849. * </form>
  850. * );
  851. * }
  852. * ```
  853. *
  854. * @public
  855. * @category Hooks
  856. * @mode framework
  857. * @mode data
  858. * @param shouldBlock Either a boolean or a function returning a boolean which
  859. * indicates whether the navigation should be blocked. The function format
  860. * receives a single object parameter containing the `currentLocation`,
  861. * `nextLocation`, and `historyAction` of the potential navigation.
  862. * @returns A {@link Blocker} object with state and reset functionality
  863. */
  864. declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
  865. type UseRouteArgs = [] | [routeId: keyof RouteModules$1];
  866. type UseRouteResult<Args extends UseRouteArgs> = Args extends [] ? UseRoute<unknown> : Args extends ["root"] ? UseRoute<"root"> : Args extends [infer RouteId extends keyof RouteModules$1] ? UseRoute<RouteId> | undefined : never;
  867. type UseRoute<RouteId extends keyof RouteModules$1 | unknown> = {
  868. handle: RouteId extends keyof RouteModules$1 ? RouteModules$1[RouteId] extends {
  869. handle: infer handle;
  870. } ? handle : unknown : unknown;
  871. loaderData: RouteId extends keyof RouteModules$1 ? GetLoaderData<RouteModules$1[RouteId]> | undefined : unknown;
  872. actionData: RouteId extends keyof RouteModules$1 ? GetActionData<RouteModules$1[RouteId]> | undefined : unknown;
  873. };
  874. declare function useRoute<Args extends UseRouteArgs>(...args: Args): UseRouteResult<Args>;
  875. /**
  876. * @category Types
  877. */
  878. interface ServerRouterProps {
  879. /**
  880. * The entry context containing the manifest, route modules, and other data
  881. * needed for rendering.
  882. */
  883. context: EntryContext;
  884. /**
  885. * The URL of the request being handled.
  886. */
  887. url: string | URL;
  888. /**
  889. * An optional `nonce` for [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)
  890. * compliance, used to allow inline scripts to run safely.
  891. */
  892. nonce?: string;
  893. }
  894. /**
  895. * The server entry point for a React Router app in Framework Mode. This
  896. * component is used to generate the HTML in the response from the server. See
  897. * [`entry.server.tsx`](../framework-conventions/entry.server.tsx).
  898. *
  899. * @public
  900. * @category Framework Routers
  901. * @mode framework
  902. * @param props Props
  903. * @param {ServerRouterProps.context} props.context n/a
  904. * @param {ServerRouterProps.nonce} props.nonce n/a
  905. * @param {ServerRouterProps.url} props.url n/a
  906. * @returns A React element that represents the server-rendered application.
  907. */
  908. declare function ServerRouter({ context, url, nonce, }: ServerRouterProps): ReactElement;
  909. interface StubRouteExtensions {
  910. Component?: RouteComponentType;
  911. HydrateFallback?: HydrateFallbackType;
  912. ErrorBoundary?: ErrorBoundaryType;
  913. loader?: LoaderFunction;
  914. action?: ActionFunction;
  915. children?: StubRouteObject[];
  916. meta?: MetaFunction;
  917. links?: LinksFunction;
  918. }
  919. interface StubIndexRouteObject extends Omit<IndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
  920. }
  921. interface StubNonIndexRouteObject extends Omit<NonIndexRouteObject, "Component" | "HydrateFallback" | "ErrorBoundary" | "loader" | "action" | "element" | "errorElement" | "children">, StubRouteExtensions {
  922. }
  923. type StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;
  924. interface RoutesTestStubProps {
  925. /**
  926. * The initial entries in the history stack. This allows you to start a test with
  927. * multiple locations already in the history stack (for testing a back navigation, etc.)
  928. * The test will default to the last entry in initialEntries if no initialIndex is provided.
  929. * e.g. initialEntries={["/home", "/about", "/contact"]}
  930. */
  931. initialEntries?: InitialEntry[];
  932. /**
  933. * The initial index in the history stack to render. This allows you to start a test at a specific entry.
  934. * It defaults to the last entry in initialEntries.
  935. * e.g.
  936. * initialEntries: ["/", "/events/123"]
  937. * initialIndex: 1 // start at "/events/123"
  938. */
  939. initialIndex?: number;
  940. /**
  941. * Used to set the route's initial loader and action data.
  942. * e.g. hydrationData={{
  943. * loaderData: { "/contact": { locale: "en-US" } },
  944. * actionData: { "/login": { errors: { email: "invalid email" } }}
  945. * }}
  946. */
  947. hydrationData?: HydrationState;
  948. /**
  949. * Future flags mimicking the settings in react-router.config.ts
  950. */
  951. future?: Partial<FutureConfig>;
  952. }
  953. /**
  954. * @category Utils
  955. */
  956. declare function createRoutesStub(routes: StubRouteObject[], _context?: AppLoadContext | RouterContextProvider): ({ initialEntries, initialIndex, hydrationData, future, }: RoutesTestStubProps) => React.JSX.Element;
  957. interface CookieSignatureOptions {
  958. /**
  959. * An array of secrets that may be used to sign/unsign the value of a cookie.
  960. *
  961. * The array makes it easy to rotate secrets. New secrets should be added to
  962. * the beginning of the array. `cookie.serialize()` will always use the first
  963. * value in the array, but `cookie.parse()` may use any of them so that
  964. * cookies that were signed with older secrets still work.
  965. */
  966. secrets?: string[];
  967. }
  968. type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
  969. /**
  970. * A HTTP cookie.
  971. *
  972. * A Cookie is a logical container for metadata about a HTTP cookie; its name
  973. * and options. But it doesn't contain a value. Instead, it has `parse()` and
  974. * `serialize()` methods that allow a single instance to be reused for
  975. * parsing/encoding multiple different values.
  976. *
  977. * @see https://remix.run/utils/cookies#cookie-api
  978. */
  979. interface Cookie {
  980. /**
  981. * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
  982. */
  983. readonly name: string;
  984. /**
  985. * True if this cookie uses one or more secrets for verification.
  986. */
  987. readonly isSigned: boolean;
  988. /**
  989. * The Date this cookie expires.
  990. *
  991. * Note: This is calculated at access time using `maxAge` when no `expires`
  992. * option is provided to `createCookie()`.
  993. */
  994. readonly expires?: Date;
  995. /**
  996. * Parses a raw `Cookie` header and returns the value of this cookie or
  997. * `null` if it's not present.
  998. */
  999. parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
  1000. /**
  1001. * Serializes the given value to a string and returns the `Set-Cookie`
  1002. * header.
  1003. */
  1004. serialize(value: any, options?: SerializeOptions): Promise<string>;
  1005. }
  1006. /**
  1007. * Creates a logical container for managing a browser cookie from the server.
  1008. */
  1009. declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
  1010. type IsCookieFunction = (object: any) => object is Cookie;
  1011. /**
  1012. * Returns true if an object is a Remix cookie container.
  1013. *
  1014. * @see https://remix.run/utils/cookies#iscookie
  1015. */
  1016. declare const isCookie: IsCookieFunction;
  1017. /**
  1018. * An object of name/value pairs to be used in the session.
  1019. */
  1020. interface SessionData {
  1021. [name: string]: any;
  1022. }
  1023. /**
  1024. * Session persists data across HTTP requests.
  1025. *
  1026. * @see https://reactrouter.com/explanation/sessions-and-cookies#sessions
  1027. */
  1028. interface Session<Data = SessionData, FlashData = Data> {
  1029. /**
  1030. * A unique identifier for this session.
  1031. *
  1032. * Note: This will be the empty string for newly created sessions and
  1033. * sessions that are not backed by a database (i.e. cookie-based sessions).
  1034. */
  1035. readonly id: string;
  1036. /**
  1037. * The raw data contained in this session.
  1038. *
  1039. * This is useful mostly for SessionStorage internally to access the raw
  1040. * session data to persist.
  1041. */
  1042. readonly data: FlashSessionData<Data, FlashData>;
  1043. /**
  1044. * Returns `true` if the session has a value for the given `name`, `false`
  1045. * otherwise.
  1046. */
  1047. has(name: (keyof Data | keyof FlashData) & string): boolean;
  1048. /**
  1049. * Returns the value for the given `name` in this session.
  1050. */
  1051. 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;
  1052. /**
  1053. * Sets a value in the session for the given `name`.
  1054. */
  1055. set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
  1056. /**
  1057. * Sets a value in the session that is only valid until the next `get()`.
  1058. * This can be useful for temporary values, like error messages.
  1059. */
  1060. flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
  1061. /**
  1062. * Removes a value from the session.
  1063. */
  1064. unset(name: keyof Data & string): void;
  1065. }
  1066. type FlashSessionData<Data, FlashData> = Partial<Data & {
  1067. [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
  1068. }>;
  1069. type FlashDataKey<Key extends string> = `__flash_${Key}__`;
  1070. type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
  1071. /**
  1072. * Creates a new Session object.
  1073. *
  1074. * Note: This function is typically not invoked directly by application code.
  1075. * Instead, use a `SessionStorage` object's `getSession` method.
  1076. */
  1077. declare const createSession: CreateSessionFunction;
  1078. type IsSessionFunction = (object: any) => object is Session;
  1079. /**
  1080. * Returns true if an object is a React Router session.
  1081. *
  1082. * @see https://reactrouter.com/api/utils/isSession
  1083. */
  1084. declare const isSession: IsSessionFunction;
  1085. /**
  1086. * SessionStorage stores session data between HTTP requests and knows how to
  1087. * parse and create cookies.
  1088. *
  1089. * A SessionStorage creates Session objects using a `Cookie` header as input.
  1090. * Then, later it generates the `Set-Cookie` header to be used in the response.
  1091. */
  1092. interface SessionStorage<Data = SessionData, FlashData = Data> {
  1093. /**
  1094. * Parses a Cookie header from a HTTP request and returns the associated
  1095. * Session. If there is no session associated with the cookie, this will
  1096. * return a new Session with no data.
  1097. */
  1098. getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
  1099. /**
  1100. * Stores all data in the Session and returns the Set-Cookie header to be
  1101. * used in the HTTP response.
  1102. */
  1103. commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
  1104. /**
  1105. * Deletes all data associated with the Session and returns the Set-Cookie
  1106. * header to be used in the HTTP response.
  1107. */
  1108. destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
  1109. }
  1110. /**
  1111. * SessionIdStorageStrategy is designed to allow anyone to easily build their
  1112. * own SessionStorage using `createSessionStorage(strategy)`.
  1113. *
  1114. * This strategy describes a common scenario where the session id is stored in
  1115. * a cookie but the actual session data is stored elsewhere, usually in a
  1116. * database or on disk. A set of create, read, update, and delete operations
  1117. * are provided for managing the session data.
  1118. */
  1119. interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
  1120. /**
  1121. * The Cookie used to store the session id, or options used to automatically
  1122. * create one.
  1123. */
  1124. cookie?: Cookie | (CookieOptions & {
  1125. name?: string;
  1126. });
  1127. /**
  1128. * Creates a new record with the given data and returns the session id.
  1129. */
  1130. createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
  1131. /**
  1132. * Returns data for a given session id, or `null` if there isn't any.
  1133. */
  1134. readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
  1135. /**
  1136. * Updates data for the given session id.
  1137. */
  1138. updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
  1139. /**
  1140. * Deletes data for a given session id from the data store.
  1141. */
  1142. deleteData: (id: string) => Promise<void>;
  1143. }
  1144. /**
  1145. * Creates a SessionStorage object using a SessionIdStorageStrategy.
  1146. *
  1147. * Note: This is a low-level API that should only be used if none of the
  1148. * existing session storage options meet your requirements.
  1149. */
  1150. declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
  1151. interface CookieSessionStorageOptions {
  1152. /**
  1153. * The Cookie used to store the session data on the client, or options used
  1154. * to automatically create one.
  1155. */
  1156. cookie?: SessionIdStorageStrategy["cookie"];
  1157. }
  1158. /**
  1159. * Creates and returns a SessionStorage object that stores all session data
  1160. * directly in the session cookie itself.
  1161. *
  1162. * This has the advantage that no database or other backend services are
  1163. * needed, and can help to simplify some load-balanced scenarios. However, it
  1164. * also has the limitation that serialized session data may not exceed the
  1165. * browser's maximum cookie size. Trade-offs!
  1166. */
  1167. declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
  1168. interface MemorySessionStorageOptions {
  1169. /**
  1170. * The Cookie used to store the session id on the client, or options used
  1171. * to automatically create one.
  1172. */
  1173. cookie?: SessionIdStorageStrategy["cookie"];
  1174. }
  1175. /**
  1176. * Creates and returns a simple in-memory SessionStorage object, mostly useful
  1177. * for testing and as a reference implementation.
  1178. *
  1179. * Note: This storage does not scale beyond a single process, so it is not
  1180. * suitable for most production scenarios.
  1181. */
  1182. declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
  1183. type DevServerHooks = {
  1184. getCriticalCss?: (pathname: string) => Promise<string | undefined>;
  1185. processRequestError?: (error: unknown) => void;
  1186. };
  1187. declare function setDevServerHooks(devServerHooks: DevServerHooks): void;
  1188. type Args = {
  1189. [K in keyof Pages]: ToArgs<Pages[K]["params"]>;
  1190. };
  1191. type ToArgs<Params extends Record<string, string | undefined>> = Equal<Params, {}> extends true ? [] : Partial<Params> extends Params ? [Params] | [] : [
  1192. Params
  1193. ];
  1194. /**
  1195. Returns a resolved URL path for the specified route.
  1196. ```tsx
  1197. const h = href("/:lang?/about", { lang: "en" })
  1198. // -> `/en/about`
  1199. <Link to={href("/products/:id", { id: "abc123" })} />
  1200. ```
  1201. */
  1202. declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
  1203. type DecodedPayload = Promise<RSCPayload> & {
  1204. _deepestRenderedBoundaryId?: string | null;
  1205. formState: Promise<any>;
  1206. };
  1207. type SSRCreateFromReadableStreamFunction = (body: ReadableStream<Uint8Array>) => Promise<unknown>;
  1208. /**
  1209. * Routes the incoming [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
  1210. * to the [RSC](https://react.dev/reference/rsc/server-components) server and
  1211. * appropriately proxies the server response for data / resource requests, or
  1212. * renders to HTML for a document request.
  1213. *
  1214. * @example
  1215. * import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
  1216. * import * as ReactDomServer from "react-dom/server.edge";
  1217. * import {
  1218. * unstable_RSCStaticRouter as RSCStaticRouter,
  1219. * unstable_routeRSCServerRequest as routeRSCServerRequest,
  1220. * } from "react-router";
  1221. *
  1222. * routeRSCServerRequest({
  1223. * request,
  1224. * fetchServer,
  1225. * createFromReadableStream,
  1226. * async renderHTML(getPayload) {
  1227. * const payload = getPayload();
  1228. *
  1229. * return await renderHTMLToReadableStream(
  1230. * <RSCStaticRouter getPayload={getPayload} />,
  1231. * {
  1232. * bootstrapScriptContent,
  1233. * formState: await payload.formState,
  1234. * }
  1235. * );
  1236. * },
  1237. * });
  1238. *
  1239. * @name unstable_routeRSCServerRequest
  1240. * @public
  1241. * @category RSC
  1242. * @mode data
  1243. * @param opts Options
  1244. * @param opts.createFromReadableStream Your `react-server-dom-xyz/client`'s
  1245. * `createFromReadableStream` function, used to decode payloads from the server.
  1246. * @param opts.fetchServer A function that forwards a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
  1247. * to the [RSC](https://react.dev/reference/rsc/server-components) handler
  1248. * and returns a `Promise<Response>` containing a serialized {@link unstable_RSCPayload}.
  1249. * @param opts.hydrate Whether to hydrate the server response with the RSC payload.
  1250. * Defaults to `true`.
  1251. * @param opts.renderHTML A function that renders the {@link unstable_RSCPayload} to
  1252. * HTML, usually using a {@link unstable_RSCStaticRouter | `<RSCStaticRouter>`}.
  1253. * @param opts.request The request to route.
  1254. * @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  1255. * that either contains the [RSC](https://react.dev/reference/rsc/server-components)
  1256. * payload for data requests, or renders the HTML for document requests.
  1257. */
  1258. declare function routeRSCServerRequest({ request, fetchServer, createFromReadableStream, renderHTML, hydrate, }: {
  1259. request: Request;
  1260. fetchServer: (request: Request) => Promise<Response>;
  1261. createFromReadableStream: SSRCreateFromReadableStreamFunction;
  1262. renderHTML: (getPayload: () => DecodedPayload) => ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>;
  1263. hydrate?: boolean;
  1264. }): Promise<Response>;
  1265. /**
  1266. * Props for the {@link unstable_RSCStaticRouter} component.
  1267. *
  1268. * @name unstable_RSCStaticRouterProps
  1269. * @category Types
  1270. */
  1271. interface RSCStaticRouterProps {
  1272. /**
  1273. * A function that starts decoding of the {@link unstable_RSCPayload}. Usually passed
  1274. * through from {@link unstable_routeRSCServerRequest}'s `renderHTML`.
  1275. */
  1276. getPayload: () => DecodedPayload;
  1277. }
  1278. /**
  1279. * Pre-renders an {@link unstable_RSCPayload} to HTML. Usually used in
  1280. * {@link unstable_routeRSCServerRequest}'s `renderHTML` callback.
  1281. *
  1282. * @example
  1283. * import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
  1284. * import * as ReactDomServer from "react-dom/server.edge";
  1285. * import {
  1286. * unstable_RSCStaticRouter as RSCStaticRouter,
  1287. * unstable_routeRSCServerRequest as routeRSCServerRequest,
  1288. * } from "react-router";
  1289. *
  1290. * routeRSCServerRequest({
  1291. * request,
  1292. * fetchServer,
  1293. * createFromReadableStream,
  1294. * async renderHTML(getPayload) {
  1295. * const payload = getPayload();
  1296. *
  1297. * return await renderHTMLToReadableStream(
  1298. * <RSCStaticRouter getPayload={getPayload} />,
  1299. * {
  1300. * bootstrapScriptContent,
  1301. * formState: await payload.formState,
  1302. * }
  1303. * );
  1304. * },
  1305. * });
  1306. *
  1307. * @name unstable_RSCStaticRouter
  1308. * @public
  1309. * @category RSC
  1310. * @mode data
  1311. * @param props Props
  1312. * @param {unstable_RSCStaticRouterProps.getPayload} props.getPayload n/a
  1313. * @returns A React component that renders the {@link unstable_RSCPayload} as HTML.
  1314. */
  1315. declare function RSCStaticRouter({ getPayload }: RSCStaticRouterProps): React.JSX.Element | null;
  1316. declare function RSCDefaultRootErrorBoundary({ hasRootLayout, }: {
  1317. hasRootLayout: boolean;
  1318. }): React__default.JSX.Element;
  1319. declare function deserializeErrors(errors: RouterState["errors"]): RouterState["errors"];
  1320. type RemixErrorBoundaryProps = React.PropsWithChildren<{
  1321. location: Location;
  1322. isOutsideRemixApp?: boolean;
  1323. error?: Error;
  1324. }>;
  1325. type RemixErrorBoundaryState = {
  1326. error: null | Error;
  1327. location: Location;
  1328. };
  1329. declare class RemixErrorBoundary extends React.Component<RemixErrorBoundaryProps, RemixErrorBoundaryState> {
  1330. constructor(props: RemixErrorBoundaryProps);
  1331. static getDerivedStateFromError(error: Error): {
  1332. error: Error;
  1333. };
  1334. static getDerivedStateFromProps(props: RemixErrorBoundaryProps, state: RemixErrorBoundaryState): {
  1335. error: Error | null;
  1336. location: Location<any>;
  1337. };
  1338. render(): string | number | boolean | React.JSX.Element | Iterable<React.ReactNode> | null | undefined;
  1339. }
  1340. declare function getPatchRoutesOnNavigationFunction(manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean, basename: string | undefined): PatchRoutesOnNavigationFunction | undefined;
  1341. declare function useFogOFWarDiscovery(router: Router, manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, routeDiscovery: ServerBuild["routeDiscovery"], isSpaMode: boolean): void;
  1342. declare function getHydrationData({ state, routes, getRouteInfo, location, basename, isSpaMode, }: {
  1343. state: {
  1344. loaderData?: Router["state"]["loaderData"];
  1345. actionData?: Router["state"]["actionData"];
  1346. errors?: Router["state"]["errors"];
  1347. };
  1348. routes: DataRouteObject[];
  1349. getRouteInfo: (routeId: string) => {
  1350. clientLoader: ClientLoaderFunction | undefined;
  1351. hasLoader: boolean;
  1352. hasHydrateFallback: boolean;
  1353. };
  1354. location: Path;
  1355. basename: string | undefined;
  1356. isSpaMode: boolean;
  1357. }): HydrationState;
  1358. /**
  1359. * @module index
  1360. * @mergeModuleWith react-router
  1361. */
  1362. declare const unstable_matchRSCServerRequest: typeof matchRSCServerRequest;
  1363. export { ActionFunction, AppLoadContext, Blocker, BlockerFunction, ClientLoaderFunction, type Cookie, type CookieOptions, type CookieSignatureOptions, type CreateRequestHandlerFunction, DataRouteObject, Router as DataRouter, DataStrategyFunction, EntryContext, type FlashSessionData, HydrationState, IndexRouteObject, InitialEntry, type IsCookieFunction, type IsSessionFunction, LinksFunction, LoaderFunction, Location, MetaFunction, type NavigateFunction, NavigateOptions, Navigation, Action as NavigationType, NonIndexRouteObject, ParamParseKey, Params, PatchRoutesOnNavigationFunction, Path, PathMatch, PathPattern, RelativeRoutingType, type RequestHandler, RouteObject, RouterContextProvider, RouterState, type RoutesTestStubProps, ServerBuild, ServerRouter, type ServerRouterProps, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, To, UIMatch, AssetsManifest as UNSAFE_AssetsManifest, MiddlewareEnabled as UNSAFE_MiddlewareEnabled, RSCDefaultRootErrorBoundary as UNSAFE_RSCDefaultRootErrorBoundary, RemixErrorBoundary as UNSAFE_RemixErrorBoundary, RouteModules as UNSAFE_RouteModules, ServerMode as UNSAFE_ServerMode, SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol, decodeViaTurboStream as UNSAFE_decodeViaTurboStream, deserializeErrors as UNSAFE_deserializeErrors, getHydrationData as UNSAFE_getHydrationData, getPatchRoutesOnNavigationFunction as UNSAFE_getPatchRoutesOnNavigationFunction, getTurboStreamSingleFetchDataStrategy as UNSAFE_getTurboStreamSingleFetchDataStrategy, useFogOFWarDiscovery as UNSAFE_useFogOFWarDiscovery, createCookie, createCookieSessionStorage, createMemorySessionStorage, createRequestHandler, createRoutesStub, createSession, createSessionStorage, href, isCookie, isSession, RSCPayload as unstable_RSCPayload, RSCStaticRouter as unstable_RSCStaticRouter, type RSCStaticRouterProps as unstable_RSCStaticRouterProps, type SSRCreateFromReadableStreamFunction as unstable_SSRCreateFromReadableStreamFunction, unstable_matchRSCServerRequest, routeRSCServerRequest as unstable_routeRSCServerRequest, setDevServerHooks as unstable_setDevServerHooks, useRoute as unstable_useRoute, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };