UNPKG

34.5 kBTypeScriptView Raw
1import { a as RouteModules, b as Router, D as DataStrategyFunction, c as RouteManifest, S as ServerRouteModule, u as unstable_RouterContextProvider, L as LoaderFunctionArgs, A as ActionFunctionArgs, T as To, d as RelativeRoutingType, e as Location, f as Action, P as ParamParseKey, g as Path, h as PathPattern, i as PathMatch, N as NavigateOptions, j as Params$1, k as RouteObject, l as Navigation, m as RevalidationState, U as UIMatch, n as SerializeFrom, B as BlockerFunction, o as Blocker, p as StaticHandlerContext, q as StaticHandler, F as FutureConfig$1, C as CreateStaticHandlerOptions$1, I as InitialEntry, H as HydrationState, r as unstable_InitialContext, s as IndexRouteObject, t as LoaderFunction, v as ActionFunction, M as MetaFunction, w as LinksFunction, x as NonIndexRouteObject, E as Equal, y as RouterState } from './route-data-CGHGzi13.js';
2export { au as ClientActionFunction, av as ClientActionFunctionArgs, aw as ClientLoaderFunction, ax as ClientLoaderFunctionArgs, ao as DataRouteMatch, ap as DataRouteObject, W as DataStrategyFunctionArgs, X as DataStrategyMatch, Y as DataStrategyResult, _ as ErrorResponse, J as Fetcher, $ as FormEncType, a0 as FormMethod, G as GetScrollPositionFunction, z as GetScrollRestorationKeyFunction, a1 as HTMLFormMethod, ay as HeadersArgs, az as HeadersFunction, aD as HtmlLinkDescriptor, ae as IDLE_BLOCKER, ad as IDLE_FETCHER, ac as IDLE_NAVIGATION, a2 as LazyRouteFunction, aE as LinkDescriptor, aA as MetaArgs, aB as MetaDescriptor, K as NavigationStates, aq as Navigator, aC as PageLinkDescriptor, ar as PatchRoutesOnNavigationFunction, as as PatchRoutesOnNavigationFunctionArgs, a4 as PathParam, a5 as RedirectFunction, at as RouteMatch, V as RouterFetchOptions, R as RouterInit, Q as RouterNavigateOptions, O as RouterSubscriber, a7 as ShouldRevalidateFunction, a8 as ShouldRevalidateFunctionArgs, aK as UNSAFE_DataRouterContext, aL as UNSAFE_DataRouterStateContext, Z as UNSAFE_DataWithResponseInit, aJ as UNSAFE_ErrorResponseImpl, aM as UNSAFE_FetchersContext, aN as UNSAFE_LocationContext, aO as UNSAFE_NavigationContext, aP as UNSAFE_RouteContext, aQ as UNSAFE_ViewTransitionContext, aG as UNSAFE_createBrowserHistory, aI as UNSAFE_createRouter, aH as UNSAFE_invariant, aa as createPath, af as data, ag as generatePath, ah as isRouteErrorResponse, ai as matchPath, aj as matchRoutes, ab as parsePath, ak as redirect, al as redirectDocument, am as replace, an as resolvePath, a3 as unstable_MiddlewareFunction, a6 as unstable_RouterContext, aF as unstable_SerializesTo, a9 as unstable_createContext } from './route-data-CGHGzi13.js';
3import { A as AssetsManifest, a as Route, F as FutureConfig, E as EntryContext, C as CriticalCss } from './fog-of-war-CGNKxM4z.js';
4export { g as Await, b as AwaitProps, T as BrowserRouter, B as BrowserRouterProps, D as DOMRouterOpts, w as FetcherFormProps, G as FetcherSubmitFunction, a7 as FetcherSubmitOptions, J as FetcherWithComponents, Y as Form, x as FormProps, U as HashRouter, H as HashRouterProps, s as HistoryRouterProps, I as IndexRouteProps, L as LayoutRouteProps, V as Link, t as LinkProps, ae as Links, h as MemoryRouter, M as MemoryRouterOpts, c as MemoryRouterProps, ad as Meta, X as NavLink, u as NavLinkProps, v as NavLinkRenderProps, i as Navigate, N as NavigateProps, j as Outlet, O as OutletProps, a8 as ParamKeyValuePair, P as PathRouteProps, ag as PrefetchPageLinks, k as Route, d as RouteProps, l as Router, e as RouterProps, m as RouterProvider, R as RouterProviderProps, n as Routes, f as RoutesProps, af as Scripts, ah as ScriptsProps, Z as ScrollRestoration, S as ScrollRestorationProps, y as SetURLSearchParams, z as SubmitFunction, a9 as SubmitOptions, ab as SubmitTarget, aj as UNSAFE_FrameworkContext, am as UNSAFE_createClientRoutes, an as UNSAFE_createClientRoutesWithHMRRevalidationOptOut, ak as UNSAFE_getPatchRoutesOnNavigationFunction, ai as UNSAFE_mapRouteProperties, ao as UNSAFE_shouldHydrateRouteLoader, al as UNSAFE_useFogOFWarDiscovery, ap as UNSAFE_useScrollRestoration, aa as URLSearchParamsInit, K as createBrowserRouter, Q as createHashRouter, o as createMemoryRouter, p as createRoutesFromChildren, q as createRoutesFromElements, ac as createSearchParams, r as renderMatches, W as unstable_HistoryRouter, a5 as unstable_usePrompt, a4 as useBeforeUnload, a2 as useFetcher, a3 as useFetchers, a1 as useFormAction, _ as useLinkClickHandler, $ as useSearchParams, a0 as useSubmit, a6 as useViewTransitionState } from './fog-of-war-CGNKxM4z.js';
5import * as React from 'react';
6import { ReactElement } from 'react';
7import { ParseOptions, SerializeOptions } from 'cookie';
8export { ParseOptions as CookieParseOptions, SerializeOptions as CookieSerializeOptions } from 'cookie';
9import { M as MiddlewareEnabled, A as AppLoadContext } from './future-ldDp5FKH.js';
10export { F as Future } from './future-ldDp5FKH.js';
11
12declare const SingleFetchRedirectSymbol: unique symbol;
13declare function getSingleFetchDataStrategy(manifest: AssetsManifest, routeModules: RouteModules, ssr: boolean, basename: string | undefined, getRouter: () => Router): DataStrategyFunction;
14declare function decodeViaTurboStream(body: ReadableStream<Uint8Array>, global: Window | typeof globalThis): Promise<{
15 done: Promise<undefined>;
16 value: unknown;
17}>;
18
19/**
20 * The mode to use when running the server.
21 */
22declare enum ServerMode {
23 Development = "development",
24 Production = "production",
25 Test = "test"
26}
27
28type ServerRouteManifest = RouteManifest<Omit<ServerRoute, "children">>;
29interface ServerRoute extends Route {
30 children: ServerRoute[];
31 module: ServerRouteModule;
32}
33
34type OptionalCriticalCss = CriticalCss | undefined;
35/**
36 * The output of the compiler for the server build.
37 */
38interface ServerBuild {
39 entry: {
40 module: ServerEntryModule;
41 };
42 routes: ServerRouteManifest;
43 assets: AssetsManifest;
44 basename?: string;
45 publicPath: string;
46 assetsBuildDirectory: string;
47 future: FutureConfig;
48 ssr: boolean;
49 unstable_getCriticalCss?: (args: {
50 pathname: string;
51 }) => OptionalCriticalCss | Promise<OptionalCriticalCss>;
52 /**
53 * @deprecated This is now done via a custom header during prerendering
54 */
55 isSpaMode: boolean;
56 prerender: string[];
57}
58interface HandleDocumentRequestFunction {
59 (request: Request, responseStatusCode: number, responseHeaders: Headers, context: EntryContext, loadContext: MiddlewareEnabled extends true ? unstable_RouterContextProvider : AppLoadContext): Promise<Response> | Response;
60}
61interface HandleDataRequestFunction {
62 (response: Response, args: LoaderFunctionArgs | ActionFunctionArgs): Promise<Response> | Response;
63}
64interface HandleErrorFunction {
65 (error: unknown, args: LoaderFunctionArgs | ActionFunctionArgs): void;
66}
67/**
68 * A module that serves as the entry point for a Remix app during server
69 * rendering.
70 */
71interface ServerEntryModule {
72 default: HandleDocumentRequestFunction;
73 handleDataRequest?: HandleDataRequestFunction;
74 handleError?: HandleErrorFunction;
75 streamTimeout?: number;
76}
77
78/**
79 Resolves a URL against the current location.
80
81 ```tsx
82 import { useHref } from "react-router"
83
84 function SomeComponent() {
85 let href = useHref("some/where");
86 // "/resolved/some/where"
87 }
88 ```
89
90 @category Hooks
91 */
92declare function useHref(to: To, { relative }?: {
93 relative?: RelativeRoutingType;
94}): string;
95/**
96 * Returns true if this component is a descendant of a Router, useful to ensure
97 * a component is used within a Router.
98 *
99 * @category Hooks
100 */
101declare function useInRouterContext(): boolean;
102/**
103 Returns the current {@link Location}. This can be useful if you'd like to perform some side effect whenever it changes.
104
105 ```tsx
106 import * as React from 'react'
107 import { useLocation } from 'react-router'
108
109 function SomeComponent() {
110 let location = useLocation()
111
112 React.useEffect(() => {
113 // Google Analytics
114 ga('send', 'pageview')
115 }, [location]);
116
117 return (
118 // ...
119 );
120 }
121 ```
122
123 @category Hooks
124 */
125declare function useLocation(): Location;
126/**
127 * Returns the current navigation action which describes how the router came to
128 * the current location, either by a pop, push, or replace on the history stack.
129 *
130 * @category Hooks
131 */
132declare function useNavigationType(): Action;
133/**
134 * Returns a PathMatch object if the given pattern matches the current URL.
135 * This is useful for components that need to know "active" state, e.g.
136 * `<NavLink>`.
137 *
138 * @category Hooks
139 */
140declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;
141/**
142 * The interface for the navigate() function returned from useNavigate().
143 */
144interface NavigateFunction {
145 (to: To, options?: NavigateOptions): void | Promise<void>;
146 (delta: number): void | Promise<void>;
147}
148/**
149 Returns a function that lets you navigate programmatically in the browser in response to user interactions or effects.
150
151 ```tsx
152 import { useNavigate } from "react-router";
153
154 function SomeComponent() {
155 let navigate = useNavigate();
156 return (
157 <button
158 onClick={() => {
159 navigate(-1);
160 }}
161 />
162 );
163 }
164 ```
165
166 It's often better to use {@link redirect} in {@link ActionFunction | actions} and {@link LoaderFunction | loaders} than this hook.
167
168 @category Hooks
169 */
170declare function useNavigate(): NavigateFunction;
171/**
172 * Returns the parent route {@link OutletProps.context | `<Outlet context>`}.
173 *
174 * @category Hooks
175 */
176declare function useOutletContext<Context = unknown>(): Context;
177/**
178 * Returns the element for the child route at this level of the route
179 * hierarchy. Used internally by `<Outlet>` to render child routes.
180 *
181 * @category Hooks
182 */
183declare function useOutlet(context?: unknown): React.ReactElement | null;
184/**
185 Returns an object of key/value pairs of the dynamic params from the current URL that were matched by the routes. Child routes inherit all params from their parent routes.
186
187 ```tsx
188 import { useParams } from "react-router"
189
190 function SomeComponent() {
191 let params = useParams()
192 params.postId
193 }
194 ```
195
196 Assuming a route pattern like `/posts/:postId` is matched by `/posts/123` then `params.postId` will be `"123"`.
197
198 @category Hooks
199 */
200declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
201 ParamsOrKey
202] extends [string] ? Params$1<ParamsOrKey> : Partial<ParamsOrKey>>;
203/**
204 Resolves the pathname of the given `to` value against the current location. Similar to {@link useHref}, but returns a {@link Path} instead of a string.
205
206 ```tsx
207 import { useResolvedPath } from "react-router"
208
209 function SomeComponent() {
210 // if the user is at /dashboard/profile
211 let path = useResolvedPath("../accounts")
212 path.pathname // "/dashboard/accounts"
213 path.search // ""
214 path.hash // ""
215 }
216 ```
217
218 @category Hooks
219 */
220declare function useResolvedPath(to: To, { relative }?: {
221 relative?: RelativeRoutingType;
222}): Path;
223/**
224 Hook version of {@link Routes | `<Routes>`} that uses objects instead of components. These objects have the same properties as the component props.
225
226 The return value of `useRoutes` is either a valid React element you can use to render the route tree, or `null` if nothing matched.
227
228 ```tsx
229 import * as React from "react";
230 import { useRoutes } from "react-router";
231
232 function App() {
233 let element = useRoutes([
234 {
235 path: "/",
236 element: <Dashboard />,
237 children: [
238 {
239 path: "messages",
240 element: <DashboardMessages />,
241 },
242 { path: "tasks", element: <DashboardTasks /> },
243 ],
244 },
245 { path: "team", element: <AboutPage /> },
246 ]);
247
248 return element;
249 }
250 ```
251
252 @category Hooks
253 */
254declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
255/**
256 Returns the current navigation, defaulting to an "idle" navigation when no navigation is in progress. You can use this to render pending UI (like a global spinner) or read FormData from a form navigation.
257
258 ```tsx
259 import { useNavigation } from "react-router"
260
261 function SomeComponent() {
262 let navigation = useNavigation();
263 navigation.state
264 navigation.formData
265 // etc.
266 }
267 ```
268
269 @category Hooks
270 */
271declare function useNavigation(): Navigation;
272/**
273 Revalidate the data on the page for reasons outside of normal data mutations like window focus or polling on an interval.
274
275 ```tsx
276 import { useRevalidator } from "react-router";
277
278 function WindowFocusRevalidator() {
279 const revalidator = useRevalidator();
280
281 useFakeWindowFocus(() => {
282 revalidator.revalidate();
283 });
284
285 return (
286 <div hidden={revalidator.state === "idle"}>
287 Revalidating...
288 </div>
289 );
290 }
291 ```
292
293 Note that page data is already revalidated automatically after actions. If you find yourself using this for normal CRUD operations on your data in response to user interactions, you're probably not taking advantage of the other APIs like {@link useFetcher}, {@link Form}, {@link useSubmit} that do this automatically.
294
295 @category Hooks
296 */
297declare function useRevalidator(): {
298 revalidate(): Promise<void>;
299 state: RevalidationState;
300};
301/**
302 * Returns the active route matches, useful for accessing loaderData for
303 * parent/child routes or the route "handle" property
304 *
305 * @category Hooks
306 */
307declare function useMatches(): UIMatch[];
308/**
309 Returns the data from the closest route {@link LoaderFunction | loader} or {@link ClientLoaderFunction | client loader}.
310
311 ```tsx
312 import { useLoaderData } from "react-router"
313
314 export async function loader() {
315 return await fakeDb.invoices.findAll();
316 }
317
318 export default function Invoices() {
319 let invoices = useLoaderData<typeof loader>();
320 // ...
321 }
322 ```
323
324 @category Hooks
325 */
326declare function useLoaderData<T = any>(): SerializeFrom<T>;
327/**
328 Returns the loader data for a given route by route ID.
329
330 ```tsx
331 import { useRouteLoaderData } from "react-router";
332
333 function SomeComponent() {
334 const { user } = useRouteLoaderData("root");
335 }
336 ```
337
338 Route IDs are created automatically. They are simply the path of the route file relative to the app folder without the extension.
339
340 | Route Filename | Route ID |
341 | -------------------------- | -------------------- |
342 | `app/root.tsx` | `"root"` |
343 | `app/routes/teams.tsx` | `"routes/teams"` |
344 | `app/whatever/teams.$id.tsx` | `"whatever/teams.$id"` |
345
346 If you created an ID manually, you can use that instead:
347
348 ```tsx
349 route("/", "containers/app.tsx", { id: "app" }})
350 ```
351
352 @category Hooks
353 */
354declare function useRouteLoaderData<T = any>(routeId: string): SerializeFrom<T> | undefined;
355/**
356 Returns the action data from the most recent POST navigation form submission or `undefined` if there hasn't been one.
357
358 ```tsx
359 import { Form, useActionData } from "react-router"
360
361 export async function action({ request }) {
362 const body = await request.formData()
363 const name = body.get("visitorsName")
364 return { message: `Hello, ${name}` }
365 }
366
367 export default function Invoices() {
368 const data = useActionData()
369 return (
370 <Form method="post">
371 <input type="text" name="visitorsName" />
372 {data ? data.message : "Waiting..."}
373 </Form>
374 )
375 }
376 ```
377
378 @category Hooks
379 */
380declare function useActionData<T = any>(): SerializeFrom<T> | undefined;
381/**
382 Accesses the error thrown during an {@link ActionFunction | action}, {@link LoaderFunction | loader}, or component render to be used in a route module Error Boundary.
383
384 ```tsx
385 export function ErrorBoundary() {
386 const error = useRouteError();
387 return <div>{error.message}</div>;
388 }
389 ```
390
391 @category Hooks
392 */
393declare function useRouteError(): unknown;
394/**
395 Returns the resolved promise value from the closest {@link Await | `<Await>`}.
396
397 ```tsx
398 function SomeDescendant() {
399 const value = useAsyncValue();
400 // ...
401 }
402
403 // somewhere in your app
404 <Await resolve={somePromise}>
405 <SomeDescendant />
406 </Await>
407 ```
408
409 @category Hooks
410 */
411declare function useAsyncValue(): unknown;
412/**
413 Returns the rejection value from the closest {@link Await | `<Await>`}.
414
415 ```tsx
416 import { Await, useAsyncError } from "react-router"
417
418 function ErrorElement() {
419 const error = useAsyncError();
420 return (
421 <p>Uh Oh, something went wrong! {error.message}</p>
422 );
423 }
424
425 // somewhere in your app
426 <Await
427 resolve={promiseThatRejects}
428 errorElement={<ErrorElement />}
429 />
430 ```
431
432 @category Hooks
433 */
434declare function useAsyncError(): unknown;
435/**
436 * Allow the application to block navigations within the SPA and present the
437 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
438 * using half-filled form data. This does not handle hard-reloads or
439 * cross-origin navigations.
440 *
441 * @category Hooks
442 */
443declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
444
445interface StaticRouterProps {
446 basename?: string;
447 children?: React.ReactNode;
448 location: Partial<Location> | string;
449}
450/**
451 * A `<Router>` that may not navigate to any other location. This is useful
452 * on the server where there is no stateful UI.
453 *
454 * @category Component Routers
455 */
456declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): React.JSX.Element;
457interface StaticRouterProviderProps {
458 context: StaticHandlerContext;
459 router: Router;
460 hydrate?: boolean;
461 nonce?: string;
462}
463/**
464 * A Data Router that may not navigate to any other location. This is useful
465 * on the server where there is no stateful UI.
466 *
467 * @category Component Routers
468 */
469declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): React.JSX.Element;
470type CreateStaticHandlerOptions = Omit<CreateStaticHandlerOptions$1, "mapRouteProperties">;
471/**
472 * @category Utils
473 */
474declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
475/**
476 * @category Data Routers
477 */
478declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: {
479 future?: Partial<FutureConfig$1>;
480}): Router;
481
482interface ServerRouterProps {
483 context: EntryContext;
484 url: string | URL;
485 nonce?: string;
486}
487/**
488 * The entry point for a Remix app when it is rendered on the server (in
489 * `app/entry.server.js`). This component is used to generate the HTML in the
490 * response from the server.
491 *
492 * @category Components
493 */
494declare function ServerRouter({ context, url, nonce, }: ServerRouterProps): ReactElement;
495
496interface StubIndexRouteObject extends Omit<IndexRouteObject, "loader" | "action" | "element" | "errorElement" | "children"> {
497 loader?: LoaderFunction;
498 action?: ActionFunction;
499 children?: StubRouteObject[];
500 meta?: MetaFunction;
501 links?: LinksFunction;
502}
503interface StubNonIndexRouteObject extends Omit<NonIndexRouteObject, "loader" | "action" | "element" | "errorElement" | "children"> {
504 loader?: LoaderFunction;
505 action?: ActionFunction;
506 children?: StubRouteObject[];
507 meta?: MetaFunction;
508 links?: LinksFunction;
509}
510type StubRouteObject = StubIndexRouteObject | StubNonIndexRouteObject;
511interface RoutesTestStubProps {
512 /**
513 * The initial entries in the history stack. This allows you to start a test with
514 * multiple locations already in the history stack (for testing a back navigation, etc.)
515 * The test will default to the last entry in initialEntries if no initialIndex is provided.
516 * e.g. initialEntries={["/home", "/about", "/contact"]}
517 */
518 initialEntries?: InitialEntry[];
519 /**
520 * The initial index in the history stack to render. This allows you to start a test at a specific entry.
521 * It defaults to the last entry in initialEntries.
522 * e.g.
523 * initialEntries: ["/", "/events/123"]
524 * initialIndex: 1 // start at "/events/123"
525 */
526 initialIndex?: number;
527 /**
528 * Used to set the route's initial loader and action data.
529 * e.g. hydrationData={{
530 * loaderData: { "/contact": { locale: "en-US" } },
531 * actionData: { "/login": { errors: { email: "invalid email" } }}
532 * }}
533 */
534 hydrationData?: HydrationState;
535 /**
536 * Future flags mimicking the settings in react-router.config.ts
537 */
538 future?: Partial<FutureConfig>;
539}
540/**
541 * @category Utils
542 */
543declare function createRoutesStub(routes: StubRouteObject[], unstable_getContext?: () => unstable_InitialContext): ({ initialEntries, initialIndex, hydrationData, future, }: RoutesTestStubProps) => React.JSX.Element;
544
545interface CookieSignatureOptions {
546 /**
547 * An array of secrets that may be used to sign/unsign the value of a cookie.
548 *
549 * The array makes it easy to rotate secrets. New secrets should be added to
550 * the beginning of the array. `cookie.serialize()` will always use the first
551 * value in the array, but `cookie.parse()` may use any of them so that
552 * cookies that were signed with older secrets still work.
553 */
554 secrets?: string[];
555}
556type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
557/**
558 * A HTTP cookie.
559 *
560 * A Cookie is a logical container for metadata about a HTTP cookie; its name
561 * and options. But it doesn't contain a value. Instead, it has `parse()` and
562 * `serialize()` methods that allow a single instance to be reused for
563 * parsing/encoding multiple different values.
564 *
565 * @see https://remix.run/utils/cookies#cookie-api
566 */
567interface Cookie {
568 /**
569 * The name of the cookie, used in the `Cookie` and `Set-Cookie` headers.
570 */
571 readonly name: string;
572 /**
573 * True if this cookie uses one or more secrets for verification.
574 */
575 readonly isSigned: boolean;
576 /**
577 * The Date this cookie expires.
578 *
579 * Note: This is calculated at access time using `maxAge` when no `expires`
580 * option is provided to `createCookie()`.
581 */
582 readonly expires?: Date;
583 /**
584 * Parses a raw `Cookie` header and returns the value of this cookie or
585 * `null` if it's not present.
586 */
587 parse(cookieHeader: string | null, options?: ParseOptions): Promise<any>;
588 /**
589 * Serializes the given value to a string and returns the `Set-Cookie`
590 * header.
591 */
592 serialize(value: any, options?: SerializeOptions): Promise<string>;
593}
594/**
595 * Creates a logical container for managing a browser cookie from the server.
596 */
597declare const createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
598type IsCookieFunction = (object: any) => object is Cookie;
599/**
600 * Returns true if an object is a Remix cookie container.
601 *
602 * @see https://remix.run/utils/cookies#iscookie
603 */
604declare const isCookie: IsCookieFunction;
605
606type RequestHandler = (request: Request, loadContext?: MiddlewareEnabled extends true ? unstable_InitialContext : AppLoadContext) => Promise<Response>;
607type CreateRequestHandlerFunction = (build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>), mode?: string) => RequestHandler;
608declare const createRequestHandler: CreateRequestHandlerFunction;
609
610/**
611 * An object of name/value pairs to be used in the session.
612 */
613interface SessionData {
614 [name: string]: any;
615}
616/**
617 * Session persists data across HTTP requests.
618 *
619 * @see https://remix.run/utils/sessions#session-api
620 */
621interface Session<Data = SessionData, FlashData = Data> {
622 /**
623 * A unique identifier for this session.
624 *
625 * Note: This will be the empty string for newly created sessions and
626 * sessions that are not backed by a database (i.e. cookie-based sessions).
627 */
628 readonly id: string;
629 /**
630 * The raw data contained in this session.
631 *
632 * This is useful mostly for SessionStorage internally to access the raw
633 * session data to persist.
634 */
635 readonly data: FlashSessionData<Data, FlashData>;
636 /**
637 * Returns `true` if the session has a value for the given `name`, `false`
638 * otherwise.
639 */
640 has(name: (keyof Data | keyof FlashData) & string): boolean;
641 /**
642 * Returns the value for the given `name` in this session.
643 */
644 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;
645 /**
646 * Sets a value in the session for the given `name`.
647 */
648 set<Key extends keyof Data & string>(name: Key, value: Data[Key]): void;
649 /**
650 * Sets a value in the session that is only valid until the next `get()`.
651 * This can be useful for temporary values, like error messages.
652 */
653 flash<Key extends keyof FlashData & string>(name: Key, value: FlashData[Key]): void;
654 /**
655 * Removes a value from the session.
656 */
657 unset(name: keyof Data & string): void;
658}
659type FlashSessionData<Data, FlashData> = Partial<Data & {
660 [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key];
661}>;
662type FlashDataKey<Key extends string> = `__flash_${Key}__`;
663type CreateSessionFunction = <Data = SessionData, FlashData = Data>(initialData?: Data, id?: string) => Session<Data, FlashData>;
664/**
665 * Creates a new Session object.
666 *
667 * Note: This function is typically not invoked directly by application code.
668 * Instead, use a `SessionStorage` object's `getSession` method.
669 *
670 * @see https://remix.run/utils/sessions#createsession
671 */
672declare const createSession: CreateSessionFunction;
673type IsSessionFunction = (object: any) => object is Session;
674/**
675 * Returns true if an object is a Remix session.
676 *
677 * @see https://remix.run/utils/sessions#issession
678 */
679declare const isSession: IsSessionFunction;
680/**
681 * SessionStorage stores session data between HTTP requests and knows how to
682 * parse and create cookies.
683 *
684 * A SessionStorage creates Session objects using a `Cookie` header as input.
685 * Then, later it generates the `Set-Cookie` header to be used in the response.
686 */
687interface SessionStorage<Data = SessionData, FlashData = Data> {
688 /**
689 * Parses a Cookie header from a HTTP request and returns the associated
690 * Session. If there is no session associated with the cookie, this will
691 * return a new Session with no data.
692 */
693 getSession: (cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
694 /**
695 * Stores all data in the Session and returns the Set-Cookie header to be
696 * used in the HTTP response.
697 */
698 commitSession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
699 /**
700 * Deletes all data associated with the Session and returns the Set-Cookie
701 * header to be used in the HTTP response.
702 */
703 destroySession: (session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
704}
705/**
706 * SessionIdStorageStrategy is designed to allow anyone to easily build their
707 * own SessionStorage using `createSessionStorage(strategy)`.
708 *
709 * This strategy describes a common scenario where the session id is stored in
710 * a cookie but the actual session data is stored elsewhere, usually in a
711 * database or on disk. A set of create, read, update, and delete operations
712 * are provided for managing the session data.
713 */
714interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {
715 /**
716 * The Cookie used to store the session id, or options used to automatically
717 * create one.
718 */
719 cookie?: Cookie | (CookieOptions & {
720 name?: string;
721 });
722 /**
723 * Creates a new record with the given data and returns the session id.
724 */
725 createData: (data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
726 /**
727 * Returns data for a given session id, or `null` if there isn't any.
728 */
729 readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
730 /**
731 * Updates data for the given session id.
732 */
733 updateData: (id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
734 /**
735 * Deletes data for a given session id from the data store.
736 */
737 deleteData: (id: string) => Promise<void>;
738}
739/**
740 * Creates a SessionStorage object using a SessionIdStorageStrategy.
741 *
742 * Note: This is a low-level API that should only be used if none of the
743 * existing session storage options meet your requirements.
744 */
745declare function createSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData, }: SessionIdStorageStrategy<Data, FlashData>): SessionStorage<Data, FlashData>;
746
747interface CookieSessionStorageOptions {
748 /**
749 * The Cookie used to store the session data on the client, or options used
750 * to automatically create one.
751 */
752 cookie?: SessionIdStorageStrategy["cookie"];
753}
754/**
755 * Creates and returns a SessionStorage object that stores all session data
756 * directly in the session cookie itself.
757 *
758 * This has the advantage that no database or other backend services are
759 * needed, and can help to simplify some load-balanced scenarios. However, it
760 * also has the limitation that serialized session data may not exceed the
761 * browser's maximum cookie size. Trade-offs!
762 */
763declare function createCookieSessionStorage<Data = SessionData, FlashData = Data>({ cookie: cookieArg }?: CookieSessionStorageOptions): SessionStorage<Data, FlashData>;
764
765interface MemorySessionStorageOptions {
766 /**
767 * The Cookie used to store the session id on the client, or options used
768 * to automatically create one.
769 */
770 cookie?: SessionIdStorageStrategy["cookie"];
771}
772/**
773 * Creates and returns a simple in-memory SessionStorage object, mostly useful
774 * for testing and as a reference implementation.
775 *
776 * Note: This storage does not scale beyond a single process, so it is not
777 * suitable for most production scenarios.
778 */
779declare function createMemorySessionStorage<Data = SessionData, FlashData = Data>({ cookie }?: MemorySessionStorageOptions): SessionStorage<Data, FlashData>;
780
781type DevServerHooks = {
782 getCriticalCss?: (pathname: string) => Promise<string | undefined>;
783 processRequestError?: (error: unknown) => void;
784};
785declare function setDevServerHooks(devServerHooks: DevServerHooks): void;
786
787/**
788 * Apps can use this interface to "register" app-wide types for React Router via interface declaration merging and module augmentation.
789 * React Router should handle this for you via type generation.
790 *
791 * For more on declaration merging and module augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation .
792 */
793interface Register {
794}
795
796type AnyParams = Record<string, Record<string, string | undefined>>;
797type Params = Register extends {
798 params: infer RegisteredParams extends AnyParams;
799} ? RegisteredParams : AnyParams;
800type Args = {
801 [K in keyof Params]: ToArgs<Params[K]>;
802};
803type ToArgs<T> = Equal<T, {}> extends true ? [] : Partial<T> extends T ? [T] | [] : [
804 T
805];
806/**
807 Returns a resolved URL path for the specified route.
808
809 ```tsx
810 const h = href("/:lang?/about", { lang: "en" })
811 // -> `/en/about`
812
813 <Link to={href("/products/:id", { id: "abc123" })} />
814 ```
815 */
816declare function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string;
817
818declare function deserializeErrors(errors: RouterState["errors"]): RouterState["errors"];
819
820type RemixErrorBoundaryProps = React.PropsWithChildren<{
821 location: Location;
822 isOutsideRemixApp?: boolean;
823 error?: Error;
824}>;
825type RemixErrorBoundaryState = {
826 error: null | Error;
827 location: Location;
828};
829declare class RemixErrorBoundary extends React.Component<RemixErrorBoundaryProps, RemixErrorBoundaryState> {
830 constructor(props: RemixErrorBoundaryProps);
831 static getDerivedStateFromError(error: Error): {
832 error: Error;
833 };
834 static getDerivedStateFromProps(props: RemixErrorBoundaryProps, state: RemixErrorBoundaryState): {
835 error: Error | null;
836 location: Location<any>;
837 };
838 render(): string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null | undefined;
839}
840
841export { ActionFunction, ActionFunctionArgs, AppLoadContext, Blocker, BlockerFunction, type Cookie, type CookieOptions, type CookieSignatureOptions, type CreateRequestHandlerFunction, Router as DataRouter, DataStrategyFunction, EntryContext, type FlashSessionData, type HandleDataRequestFunction, type HandleDocumentRequestFunction, type HandleErrorFunction, HydrationState, IndexRouteObject, InitialEntry, type IsCookieFunction, type IsSessionFunction, LinksFunction, LoaderFunction, LoaderFunctionArgs, Location, MetaFunction, type NavigateFunction, NavigateOptions, Navigation, Action as NavigationType, NonIndexRouteObject, ParamParseKey, Params$1 as Params, Path, PathMatch, PathPattern, type Register, RelativeRoutingType, type RequestHandler, RevalidationState, RouteObject, RouterState, type RoutesTestStubProps, type ServerBuild, type ServerEntryModule, ServerRouter, type ServerRouterProps, type Session, type SessionData, type SessionIdStorageStrategy, type SessionStorage, StaticHandler, StaticHandlerContext, StaticRouter, type StaticRouterProps, StaticRouterProvider, type StaticRouterProviderProps, To, UIMatch, AssetsManifest as UNSAFE_AssetsManifest, MiddlewareEnabled as UNSAFE_MiddlewareEnabled, RemixErrorBoundary as UNSAFE_RemixErrorBoundary, RouteModules as UNSAFE_RouteModules, ServerMode as UNSAFE_ServerMode, SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol, decodeViaTurboStream as UNSAFE_decodeViaTurboStream, deserializeErrors as UNSAFE_deserializeErrors, getSingleFetchDataStrategy as UNSAFE_getSingleFetchDataStrategy, createCookie, createCookieSessionStorage, createMemorySessionStorage, createRequestHandler, createRoutesStub, createSession, createSessionStorage, createStaticHandler, createStaticRouter, href, isCookie, isSession, unstable_InitialContext, unstable_RouterContextProvider, setDevServerHooks as unstable_setDevServerHooks, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };