source: node_modules/@remix-run/router/dist/utils.d.ts@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 16.5 KB
RevLine 
[d24f17c]1import type { Location, Path, To } from "./history";
2/**
3 * Map of routeId -> data returned from a loader/action/error
4 */
5export interface RouteData {
6 [routeId: string]: any;
7}
8export declare enum ResultType {
9 data = "data",
10 deferred = "deferred",
11 redirect = "redirect",
12 error = "error"
13}
14/**
15 * Successful result from a loader or action
16 */
17export interface SuccessResult {
18 type: ResultType.data;
19 data: any;
20 statusCode?: number;
21 headers?: Headers;
22}
23/**
24 * Successful defer() result from a loader or action
25 */
26export interface DeferredResult {
27 type: ResultType.deferred;
28 deferredData: DeferredData;
29 statusCode?: number;
30 headers?: Headers;
31}
32/**
33 * Redirect result from a loader or action
34 */
35export interface RedirectResult {
36 type: ResultType.redirect;
37 status: number;
38 location: string;
39 revalidate: boolean;
40 reloadDocument?: boolean;
41}
42/**
43 * Unsuccessful result from a loader or action
44 */
45export interface ErrorResult {
46 type: ResultType.error;
47 error: any;
48 headers?: Headers;
49}
50/**
51 * Result from a loader or action - potentially successful or unsuccessful
52 */
53export type DataResult = SuccessResult | DeferredResult | RedirectResult | ErrorResult;
54type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
55type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
56/**
57 * Users can specify either lowercase or uppercase form methods on `<Form>`,
58 * useSubmit(), `<fetcher.Form>`, etc.
59 */
60export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
61/**
62 * Active navigation/fetcher form methods are exposed in lowercase on the
63 * RouterState
64 */
65export type FormMethod = LowerCaseFormMethod;
66export type MutationFormMethod = Exclude<FormMethod, "get">;
67/**
68 * In v7, active navigation/fetcher form methods are exposed in uppercase on the
69 * RouterState. This is to align with the normalization done via fetch().
70 */
71export type V7_FormMethod = UpperCaseFormMethod;
72export type V7_MutationFormMethod = Exclude<V7_FormMethod, "GET">;
73export type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain";
74type JsonObject = {
75 [Key in string]: JsonValue;
76} & {
77 [Key in string]?: JsonValue | undefined;
78};
79type JsonArray = JsonValue[] | readonly JsonValue[];
80type JsonPrimitive = string | number | boolean | null;
81type JsonValue = JsonPrimitive | JsonObject | JsonArray;
82/**
83 * @private
84 * Internal interface to pass around for action submissions, not intended for
85 * external consumption
86 */
87export type Submission = {
88 formMethod: FormMethod | V7_FormMethod;
89 formAction: string;
90 formEncType: FormEncType;
91 formData: FormData;
92 json: undefined;
93 text: undefined;
94} | {
95 formMethod: FormMethod | V7_FormMethod;
96 formAction: string;
97 formEncType: FormEncType;
98 formData: undefined;
99 json: JsonValue;
100 text: undefined;
101} | {
102 formMethod: FormMethod | V7_FormMethod;
103 formAction: string;
104 formEncType: FormEncType;
105 formData: undefined;
106 json: undefined;
107 text: string;
108};
109/**
110 * @private
111 * Arguments passed to route loader/action functions. Same for now but we keep
112 * this as a private implementation detail in case they diverge in the future.
113 */
114interface DataFunctionArgs<Context> {
115 request: Request;
116 params: Params;
117 context?: Context;
118}
119/**
120 * Arguments passed to loader functions
121 */
122export interface LoaderFunctionArgs<Context = any> extends DataFunctionArgs<Context> {
123}
124/**
125 * Arguments passed to action functions
126 */
127export interface ActionFunctionArgs<Context = any> extends DataFunctionArgs<Context> {
128}
129/**
130 * Loaders and actions can return anything except `undefined` (`null` is a
131 * valid return value if there is no data to return). Responses are preferred
132 * and will ease any future migration to Remix
133 */
134type DataFunctionValue = Response | NonNullable<unknown> | null;
135/**
136 * Route loader function signature
137 */
138export type LoaderFunction<Context = any> = {
139 (args: LoaderFunctionArgs<Context>): Promise<DataFunctionValue> | DataFunctionValue;
140} & {
141 hydrate?: boolean;
142};
143/**
144 * Route action function signature
145 */
146export interface ActionFunction<Context = any> {
147 (args: ActionFunctionArgs<Context>): Promise<DataFunctionValue> | DataFunctionValue;
148}
149/**
150 * Arguments passed to shouldRevalidate function
151 */
152export interface ShouldRevalidateFunctionArgs {
153 currentUrl: URL;
154 currentParams: AgnosticDataRouteMatch["params"];
155 nextUrl: URL;
156 nextParams: AgnosticDataRouteMatch["params"];
157 formMethod?: Submission["formMethod"];
158 formAction?: Submission["formAction"];
159 formEncType?: Submission["formEncType"];
160 text?: Submission["text"];
161 formData?: Submission["formData"];
162 json?: Submission["json"];
163 actionResult?: any;
164 defaultShouldRevalidate: boolean;
165}
166/**
167 * Route shouldRevalidate function signature. This runs after any submission
168 * (navigation or fetcher), so we flatten the navigation/fetcher submission
169 * onto the arguments. It shouldn't matter whether it came from a navigation
170 * or a fetcher, what really matters is the URLs and the formData since loaders
171 * have to re-run based on the data models that were potentially mutated.
172 */
173export interface ShouldRevalidateFunction {
174 (args: ShouldRevalidateFunctionArgs): boolean;
175}
176/**
177 * Function provided by the framework-aware layers to set `hasErrorBoundary`
178 * from the framework-aware `errorElement` prop
179 *
180 * @deprecated Use `mapRouteProperties` instead
181 */
182export interface DetectErrorBoundaryFunction {
183 (route: AgnosticRouteObject): boolean;
184}
185/**
186 * Function provided by the framework-aware layers to set any framework-specific
187 * properties from framework-agnostic properties
188 */
189export interface MapRoutePropertiesFunction {
190 (route: AgnosticRouteObject): {
191 hasErrorBoundary: boolean;
192 } & Record<string, any>;
193}
194/**
195 * Keys we cannot change from within a lazy() function. We spread all other keys
196 * onto the route. Either they're meaningful to the router, or they'll get
197 * ignored.
198 */
199export type ImmutableRouteKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
200export declare const immutableRouteKeys: Set<ImmutableRouteKey>;
201type RequireOne<T, Key = keyof T> = Exclude<{
202 [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;
203}[keyof T], undefined>;
204/**
205 * lazy() function to load a route definition, which can add non-matching
206 * related properties to a route
207 */
208export interface LazyRouteFunction<R extends AgnosticRouteObject> {
209 (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;
210}
211/**
212 * Base RouteObject with common props shared by all types of routes
213 */
214type AgnosticBaseRouteObject = {
215 caseSensitive?: boolean;
216 path?: string;
217 id?: string;
218 loader?: LoaderFunction;
219 action?: ActionFunction;
220 hasErrorBoundary?: boolean;
221 shouldRevalidate?: ShouldRevalidateFunction;
222 handle?: any;
223 lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;
224};
225/**
226 * Index routes must not have children
227 */
228export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
229 children?: undefined;
230 index: true;
231};
232/**
233 * Non-index routes may have children, but cannot have index
234 */
235export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
236 children?: AgnosticRouteObject[];
237 index?: false;
238};
239/**
240 * A route object represents a logical route, with (optionally) its child
241 * routes organized in a tree-like structure.
242 */
243export type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
244export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
245 id: string;
246};
247export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
248 children?: AgnosticDataRouteObject[];
249 id: string;
250};
251/**
252 * A data route object, which is just a RouteObject with a required unique ID
253 */
254export type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
255export type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;
256type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param extends `${infer Optional}?` ? Optional : Param : never;
257/**
258 * Examples:
259 * "/a/b/*" -> "*"
260 * ":a" -> "a"
261 * "/a/:b" -> "b"
262 * "/a/blahblahblah:b" -> "b"
263 * "/:a/:b" -> "a" | "b"
264 * "/:a/b/:c/*" -> "a" | "c" | "*"
265 */
266export type PathParam<Path extends string> = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;
267export type ParamParseKey<Segment extends string> = [
268 PathParam<Segment>
269] extends [never] ? string : PathParam<Segment>;
270/**
271 * The parameters that were parsed from the URL path.
272 */
273export type Params<Key extends string = string> = {
274 readonly [key in Key]: string | undefined;
275};
276/**
277 * A RouteMatch contains info about how a route matched a URL.
278 */
279export interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
280 /**
281 * The names and values of dynamic parameters in the URL.
282 */
283 params: Params<ParamKey>;
284 /**
285 * The portion of the URL pathname that was matched.
286 */
287 pathname: string;
288 /**
289 * The portion of the URL pathname that was matched before child routes.
290 */
291 pathnameBase: string;
292 /**
293 * The route object that was used to match.
294 */
295 route: RouteObjectType;
296}
297export interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
298}
299export declare function convertRoutesToDataRoutes(routes: AgnosticRouteObject[], mapRouteProperties: MapRoutePropertiesFunction, parentPath?: number[], manifest?: RouteManifest): AgnosticDataRouteObject[];
300/**
301 * Matches the given routes to a location and returns the match data.
302 *
303 * @see https://reactrouter.com/utils/match-routes
304 */
305export declare function matchRoutes<RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string): AgnosticRouteMatch<string, RouteObjectType>[] | null;
306export interface UIMatch<Data = unknown, Handle = unknown> {
307 id: string;
308 pathname: string;
309 params: AgnosticRouteMatch["params"];
310 data: Data;
311 handle: Handle;
312}
313export declare function convertRouteMatchToUiMatch(match: AgnosticDataRouteMatch, loaderData: RouteData): UIMatch;
314/**
315 * Returns a path with params interpolated.
316 *
317 * @see https://reactrouter.com/utils/generate-path
318 */
319export declare function generatePath<Path extends string>(originalPath: Path, params?: {
320 [key in PathParam<Path>]: string | null;
321}): string;
322/**
323 * A PathPattern is used to match on some portion of a URL pathname.
324 */
325export interface PathPattern<Path extends string = string> {
326 /**
327 * A string to match against a URL pathname. May contain `:id`-style segments
328 * to indicate placeholders for dynamic parameters. May also end with `/*` to
329 * indicate matching the rest of the URL pathname.
330 */
331 path: Path;
332 /**
333 * Should be `true` if the static portions of the `path` should be matched in
334 * the same case.
335 */
336 caseSensitive?: boolean;
337 /**
338 * Should be `true` if this pattern should match the entire URL pathname.
339 */
340 end?: boolean;
341}
342/**
343 * A PathMatch contains info about how a PathPattern matched on a URL pathname.
344 */
345export interface PathMatch<ParamKey extends string = string> {
346 /**
347 * The names and values of dynamic parameters in the URL.
348 */
349 params: Params<ParamKey>;
350 /**
351 * The portion of the URL pathname that was matched.
352 */
353 pathname: string;
354 /**
355 * The portion of the URL pathname that was matched before child routes.
356 */
357 pathnameBase: string;
358 /**
359 * The pattern that was used to match.
360 */
361 pattern: PathPattern;
362}
363/**
364 * Performs pattern matching on a URL pathname and returns information about
365 * the match.
366 *
367 * @see https://reactrouter.com/utils/match-path
368 */
369export declare function matchPath<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamKey> | null;
370/**
371 * @private
372 */
373export declare function stripBasename(pathname: string, basename: string): string | null;
374/**
375 * Returns a resolved path object relative to the given pathname.
376 *
377 * @see https://reactrouter.com/utils/resolve-path
378 */
379export declare function resolvePath(to: To, fromPathname?: string): Path;
380/**
381 * @private
382 *
383 * When processing relative navigation we want to ignore ancestor routes that
384 * do not contribute to the path, such that index/pathless layout routes don't
385 * interfere.
386 *
387 * For example, when moving a route element into an index route and/or a
388 * pathless layout route, relative link behavior contained within should stay
389 * the same. Both of the following examples should link back to the root:
390 *
391 * <Route path="/">
392 * <Route path="accounts" element={<Link to=".."}>
393 * </Route>
394 *
395 * <Route path="/">
396 * <Route path="accounts">
397 * <Route element={<AccountsLayout />}> // <-- Does not contribute
398 * <Route index element={<Link to=".."} /> // <-- Does not contribute
399 * </Route
400 * </Route>
401 * </Route>
402 */
403export declare function getPathContributingMatches<T extends AgnosticRouteMatch = AgnosticRouteMatch>(matches: T[]): T[];
404export declare function getResolveToMatches<T extends AgnosticRouteMatch = AgnosticRouteMatch>(matches: T[], v7_relativeSplatPath: boolean): string[];
405/**
406 * @private
407 */
408export declare function resolveTo(toArg: To, routePathnames: string[], locationPathname: string, isPathRelative?: boolean): Path;
409/**
410 * @private
411 */
412export declare function getToPathname(to: To): string | undefined;
413/**
414 * @private
415 */
416export declare const joinPaths: (paths: string[]) => string;
417/**
418 * @private
419 */
420export declare const normalizePathname: (pathname: string) => string;
421/**
422 * @private
423 */
424export declare const normalizeSearch: (search: string) => string;
425/**
426 * @private
427 */
428export declare const normalizeHash: (hash: string) => string;
429export type JsonFunction = <Data>(data: Data, init?: number | ResponseInit) => Response;
430/**
431 * This is a shortcut for creating `application/json` responses. Converts `data`
432 * to JSON and sets the `Content-Type` header.
433 */
434export declare const json: JsonFunction;
435export interface TrackedPromise extends Promise<any> {
436 _tracked?: boolean;
437 _data?: any;
438 _error?: any;
439}
440export declare class AbortedDeferredError extends Error {
441}
442export declare class DeferredData {
443 private pendingKeysSet;
444 private controller;
445 private abortPromise;
446 private unlistenAbortSignal;
447 private subscribers;
448 data: Record<string, unknown>;
449 init?: ResponseInit;
450 deferredKeys: string[];
451 constructor(data: Record<string, unknown>, responseInit?: ResponseInit);
452 private trackPromise;
453 private onSettle;
454 private emit;
455 subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean;
456 cancel(): void;
457 resolveData(signal: AbortSignal): Promise<boolean>;
458 get done(): boolean;
459 get unwrappedData(): {};
460 get pendingKeys(): string[];
461}
462export type DeferFunction = (data: Record<string, unknown>, init?: number | ResponseInit) => DeferredData;
463export declare const defer: DeferFunction;
464export type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
465/**
466 * A redirect response. Sets the status code and the `Location` header.
467 * Defaults to "302 Found".
468 */
469export declare const redirect: RedirectFunction;
470/**
471 * A redirect response that will force a document reload to the new location.
472 * Sets the status code and the `Location` header.
473 * Defaults to "302 Found".
474 */
475export declare const redirectDocument: RedirectFunction;
476export type ErrorResponse = {
477 status: number;
478 statusText: string;
479 data: any;
480};
481/**
482 * @private
483 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
484 *
485 * We don't export the class for public use since it's an implementation
486 * detail, but we export the interface above so folks can build their own
487 * abstractions around instances via isRouteErrorResponse()
488 */
489export declare class ErrorResponseImpl implements ErrorResponse {
490 status: number;
491 statusText: string;
492 data: any;
493 private error?;
494 private internal;
495 constructor(status: number, statusText: string | undefined, data: any, internal?: boolean);
496}
497/**
498 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
499 * Response thrown from an action/loader
500 */
501export declare function isRouteErrorResponse(error: any): error is ErrorResponse;
502export {};
Note: See TracBrowser for help on using the repository browser.