1 | import type { Location, Path, To } from "./history";
|
---|
2 | import { invariant, parsePath, warning } from "./history";
|
---|
3 |
|
---|
4 | /**
|
---|
5 | * Map of routeId -> data returned from a loader/action/error
|
---|
6 | */
|
---|
7 | export interface RouteData {
|
---|
8 | [routeId: string]: any;
|
---|
9 | }
|
---|
10 |
|
---|
11 | export enum ResultType {
|
---|
12 | data = "data",
|
---|
13 | deferred = "deferred",
|
---|
14 | redirect = "redirect",
|
---|
15 | error = "error",
|
---|
16 | }
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * Successful result from a loader or action
|
---|
20 | */
|
---|
21 | export interface SuccessResult {
|
---|
22 | type: ResultType.data;
|
---|
23 | data: any;
|
---|
24 | statusCode?: number;
|
---|
25 | headers?: Headers;
|
---|
26 | }
|
---|
27 |
|
---|
28 | /**
|
---|
29 | * Successful defer() result from a loader or action
|
---|
30 | */
|
---|
31 | export interface DeferredResult {
|
---|
32 | type: ResultType.deferred;
|
---|
33 | deferredData: DeferredData;
|
---|
34 | statusCode?: number;
|
---|
35 | headers?: Headers;
|
---|
36 | }
|
---|
37 |
|
---|
38 | /**
|
---|
39 | * Redirect result from a loader or action
|
---|
40 | */
|
---|
41 | export interface RedirectResult {
|
---|
42 | type: ResultType.redirect;
|
---|
43 | status: number;
|
---|
44 | location: string;
|
---|
45 | revalidate: boolean;
|
---|
46 | reloadDocument?: boolean;
|
---|
47 | }
|
---|
48 |
|
---|
49 | /**
|
---|
50 | * Unsuccessful result from a loader or action
|
---|
51 | */
|
---|
52 | export interface ErrorResult {
|
---|
53 | type: ResultType.error;
|
---|
54 | error: any;
|
---|
55 | headers?: Headers;
|
---|
56 | }
|
---|
57 |
|
---|
58 | /**
|
---|
59 | * Result from a loader or action - potentially successful or unsuccessful
|
---|
60 | */
|
---|
61 | export type DataResult =
|
---|
62 | | SuccessResult
|
---|
63 | | DeferredResult
|
---|
64 | | RedirectResult
|
---|
65 | | ErrorResult;
|
---|
66 |
|
---|
67 | type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
|
---|
68 | type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
|
---|
69 |
|
---|
70 | /**
|
---|
71 | * Users can specify either lowercase or uppercase form methods on `<Form>`,
|
---|
72 | * useSubmit(), `<fetcher.Form>`, etc.
|
---|
73 | */
|
---|
74 | export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
|
---|
75 |
|
---|
76 | /**
|
---|
77 | * Active navigation/fetcher form methods are exposed in lowercase on the
|
---|
78 | * RouterState
|
---|
79 | */
|
---|
80 | export type FormMethod = LowerCaseFormMethod;
|
---|
81 | export type MutationFormMethod = Exclude<FormMethod, "get">;
|
---|
82 |
|
---|
83 | /**
|
---|
84 | * In v7, active navigation/fetcher form methods are exposed in uppercase on the
|
---|
85 | * RouterState. This is to align with the normalization done via fetch().
|
---|
86 | */
|
---|
87 | export type V7_FormMethod = UpperCaseFormMethod;
|
---|
88 | export type V7_MutationFormMethod = Exclude<V7_FormMethod, "GET">;
|
---|
89 |
|
---|
90 | export type FormEncType =
|
---|
91 | | "application/x-www-form-urlencoded"
|
---|
92 | | "multipart/form-data"
|
---|
93 | | "application/json"
|
---|
94 | | "text/plain";
|
---|
95 |
|
---|
96 | // Thanks https://github.com/sindresorhus/type-fest!
|
---|
97 | type JsonObject = { [Key in string]: JsonValue } & {
|
---|
98 | [Key in string]?: JsonValue | undefined;
|
---|
99 | };
|
---|
100 | type JsonArray = JsonValue[] | readonly JsonValue[];
|
---|
101 | type JsonPrimitive = string | number | boolean | null;
|
---|
102 | type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
---|
103 |
|
---|
104 | /**
|
---|
105 | * @private
|
---|
106 | * Internal interface to pass around for action submissions, not intended for
|
---|
107 | * external consumption
|
---|
108 | */
|
---|
109 | export type Submission =
|
---|
110 | | {
|
---|
111 | formMethod: FormMethod | V7_FormMethod;
|
---|
112 | formAction: string;
|
---|
113 | formEncType: FormEncType;
|
---|
114 | formData: FormData;
|
---|
115 | json: undefined;
|
---|
116 | text: undefined;
|
---|
117 | }
|
---|
118 | | {
|
---|
119 | formMethod: FormMethod | V7_FormMethod;
|
---|
120 | formAction: string;
|
---|
121 | formEncType: FormEncType;
|
---|
122 | formData: undefined;
|
---|
123 | json: JsonValue;
|
---|
124 | text: undefined;
|
---|
125 | }
|
---|
126 | | {
|
---|
127 | formMethod: FormMethod | V7_FormMethod;
|
---|
128 | formAction: string;
|
---|
129 | formEncType: FormEncType;
|
---|
130 | formData: undefined;
|
---|
131 | json: undefined;
|
---|
132 | text: string;
|
---|
133 | };
|
---|
134 |
|
---|
135 | /**
|
---|
136 | * @private
|
---|
137 | * Arguments passed to route loader/action functions. Same for now but we keep
|
---|
138 | * this as a private implementation detail in case they diverge in the future.
|
---|
139 | */
|
---|
140 | interface DataFunctionArgs<Context> {
|
---|
141 | request: Request;
|
---|
142 | params: Params;
|
---|
143 | context?: Context;
|
---|
144 | }
|
---|
145 |
|
---|
146 | // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
|
---|
147 | // ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
|
---|
148 | // Also, make them a type alias instead of an interface
|
---|
149 |
|
---|
150 | /**
|
---|
151 | * Arguments passed to loader functions
|
---|
152 | */
|
---|
153 | export interface LoaderFunctionArgs<Context = any>
|
---|
154 | extends DataFunctionArgs<Context> {}
|
---|
155 |
|
---|
156 | /**
|
---|
157 | * Arguments passed to action functions
|
---|
158 | */
|
---|
159 | export interface ActionFunctionArgs<Context = any>
|
---|
160 | extends DataFunctionArgs<Context> {}
|
---|
161 |
|
---|
162 | /**
|
---|
163 | * Loaders and actions can return anything except `undefined` (`null` is a
|
---|
164 | * valid return value if there is no data to return). Responses are preferred
|
---|
165 | * and will ease any future migration to Remix
|
---|
166 | */
|
---|
167 | type DataFunctionValue = Response | NonNullable<unknown> | null;
|
---|
168 |
|
---|
169 | /**
|
---|
170 | * Route loader function signature
|
---|
171 | */
|
---|
172 | export type LoaderFunction<Context = any> = {
|
---|
173 | (args: LoaderFunctionArgs<Context>):
|
---|
174 | | Promise<DataFunctionValue>
|
---|
175 | | DataFunctionValue;
|
---|
176 | } & { hydrate?: boolean };
|
---|
177 |
|
---|
178 | /**
|
---|
179 | * Route action function signature
|
---|
180 | */
|
---|
181 | export interface ActionFunction<Context = any> {
|
---|
182 | (args: ActionFunctionArgs<Context>):
|
---|
183 | | Promise<DataFunctionValue>
|
---|
184 | | DataFunctionValue;
|
---|
185 | }
|
---|
186 |
|
---|
187 | /**
|
---|
188 | * Arguments passed to shouldRevalidate function
|
---|
189 | */
|
---|
190 | export interface ShouldRevalidateFunctionArgs {
|
---|
191 | currentUrl: URL;
|
---|
192 | currentParams: AgnosticDataRouteMatch["params"];
|
---|
193 | nextUrl: URL;
|
---|
194 | nextParams: AgnosticDataRouteMatch["params"];
|
---|
195 | formMethod?: Submission["formMethod"];
|
---|
196 | formAction?: Submission["formAction"];
|
---|
197 | formEncType?: Submission["formEncType"];
|
---|
198 | text?: Submission["text"];
|
---|
199 | formData?: Submission["formData"];
|
---|
200 | json?: Submission["json"];
|
---|
201 | actionResult?: any;
|
---|
202 | defaultShouldRevalidate: boolean;
|
---|
203 | }
|
---|
204 |
|
---|
205 | /**
|
---|
206 | * Route shouldRevalidate function signature. This runs after any submission
|
---|
207 | * (navigation or fetcher), so we flatten the navigation/fetcher submission
|
---|
208 | * onto the arguments. It shouldn't matter whether it came from a navigation
|
---|
209 | * or a fetcher, what really matters is the URLs and the formData since loaders
|
---|
210 | * have to re-run based on the data models that were potentially mutated.
|
---|
211 | */
|
---|
212 | export interface ShouldRevalidateFunction {
|
---|
213 | (args: ShouldRevalidateFunctionArgs): boolean;
|
---|
214 | }
|
---|
215 |
|
---|
216 | /**
|
---|
217 | * Function provided by the framework-aware layers to set `hasErrorBoundary`
|
---|
218 | * from the framework-aware `errorElement` prop
|
---|
219 | *
|
---|
220 | * @deprecated Use `mapRouteProperties` instead
|
---|
221 | */
|
---|
222 | export interface DetectErrorBoundaryFunction {
|
---|
223 | (route: AgnosticRouteObject): boolean;
|
---|
224 | }
|
---|
225 |
|
---|
226 | /**
|
---|
227 | * Function provided by the framework-aware layers to set any framework-specific
|
---|
228 | * properties from framework-agnostic properties
|
---|
229 | */
|
---|
230 | export interface MapRoutePropertiesFunction {
|
---|
231 | (route: AgnosticRouteObject): {
|
---|
232 | hasErrorBoundary: boolean;
|
---|
233 | } & Record<string, any>;
|
---|
234 | }
|
---|
235 |
|
---|
236 | /**
|
---|
237 | * Keys we cannot change from within a lazy() function. We spread all other keys
|
---|
238 | * onto the route. Either they're meaningful to the router, or they'll get
|
---|
239 | * ignored.
|
---|
240 | */
|
---|
241 | export type ImmutableRouteKey =
|
---|
242 | | "lazy"
|
---|
243 | | "caseSensitive"
|
---|
244 | | "path"
|
---|
245 | | "id"
|
---|
246 | | "index"
|
---|
247 | | "children";
|
---|
248 |
|
---|
249 | export const immutableRouteKeys = new Set<ImmutableRouteKey>([
|
---|
250 | "lazy",
|
---|
251 | "caseSensitive",
|
---|
252 | "path",
|
---|
253 | "id",
|
---|
254 | "index",
|
---|
255 | "children",
|
---|
256 | ]);
|
---|
257 |
|
---|
258 | type RequireOne<T, Key = keyof T> = Exclude<
|
---|
259 | {
|
---|
260 | [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;
|
---|
261 | }[keyof T],
|
---|
262 | undefined
|
---|
263 | >;
|
---|
264 |
|
---|
265 | /**
|
---|
266 | * lazy() function to load a route definition, which can add non-matching
|
---|
267 | * related properties to a route
|
---|
268 | */
|
---|
269 | export interface LazyRouteFunction<R extends AgnosticRouteObject> {
|
---|
270 | (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;
|
---|
271 | }
|
---|
272 |
|
---|
273 | /**
|
---|
274 | * Base RouteObject with common props shared by all types of routes
|
---|
275 | */
|
---|
276 | type AgnosticBaseRouteObject = {
|
---|
277 | caseSensitive?: boolean;
|
---|
278 | path?: string;
|
---|
279 | id?: string;
|
---|
280 | loader?: LoaderFunction;
|
---|
281 | action?: ActionFunction;
|
---|
282 | hasErrorBoundary?: boolean;
|
---|
283 | shouldRevalidate?: ShouldRevalidateFunction;
|
---|
284 | handle?: any;
|
---|
285 | lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;
|
---|
286 | };
|
---|
287 |
|
---|
288 | /**
|
---|
289 | * Index routes must not have children
|
---|
290 | */
|
---|
291 | export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
|
---|
292 | children?: undefined;
|
---|
293 | index: true;
|
---|
294 | };
|
---|
295 |
|
---|
296 | /**
|
---|
297 | * Non-index routes may have children, but cannot have index
|
---|
298 | */
|
---|
299 | export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
|
---|
300 | children?: AgnosticRouteObject[];
|
---|
301 | index?: false;
|
---|
302 | };
|
---|
303 |
|
---|
304 | /**
|
---|
305 | * A route object represents a logical route, with (optionally) its child
|
---|
306 | * routes organized in a tree-like structure.
|
---|
307 | */
|
---|
308 | export type AgnosticRouteObject =
|
---|
309 | | AgnosticIndexRouteObject
|
---|
310 | | AgnosticNonIndexRouteObject;
|
---|
311 |
|
---|
312 | export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
|
---|
313 | id: string;
|
---|
314 | };
|
---|
315 |
|
---|
316 | export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
|
---|
317 | children?: AgnosticDataRouteObject[];
|
---|
318 | id: string;
|
---|
319 | };
|
---|
320 |
|
---|
321 | /**
|
---|
322 | * A data route object, which is just a RouteObject with a required unique ID
|
---|
323 | */
|
---|
324 | export type AgnosticDataRouteObject =
|
---|
325 | | AgnosticDataIndexRouteObject
|
---|
326 | | AgnosticDataNonIndexRouteObject;
|
---|
327 |
|
---|
328 | export type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;
|
---|
329 |
|
---|
330 | // Recursive helper for finding path parameters in the absence of wildcards
|
---|
331 | type _PathParam<Path extends string> =
|
---|
332 | // split path into individual path segments
|
---|
333 | Path extends `${infer L}/${infer R}`
|
---|
334 | ? _PathParam<L> | _PathParam<R>
|
---|
335 | : // find params after `:`
|
---|
336 | Path extends `:${infer Param}`
|
---|
337 | ? Param extends `${infer Optional}?`
|
---|
338 | ? Optional
|
---|
339 | : Param
|
---|
340 | : // otherwise, there aren't any params present
|
---|
341 | never;
|
---|
342 |
|
---|
343 | /**
|
---|
344 | * Examples:
|
---|
345 | * "/a/b/*" -> "*"
|
---|
346 | * ":a" -> "a"
|
---|
347 | * "/a/:b" -> "b"
|
---|
348 | * "/a/blahblahblah:b" -> "b"
|
---|
349 | * "/:a/:b" -> "a" | "b"
|
---|
350 | * "/:a/b/:c/*" -> "a" | "c" | "*"
|
---|
351 | */
|
---|
352 | export type PathParam<Path extends string> =
|
---|
353 | // check if path is just a wildcard
|
---|
354 | Path extends "*" | "/*"
|
---|
355 | ? "*"
|
---|
356 | : // look for wildcard at the end of the path
|
---|
357 | Path extends `${infer Rest}/*`
|
---|
358 | ? "*" | _PathParam<Rest>
|
---|
359 | : // look for params in the absence of wildcards
|
---|
360 | _PathParam<Path>;
|
---|
361 |
|
---|
362 | // Attempt to parse the given string segment. If it fails, then just return the
|
---|
363 | // plain string type as a default fallback. Otherwise, return the union of the
|
---|
364 | // parsed string literals that were referenced as dynamic segments in the route.
|
---|
365 | export type ParamParseKey<Segment extends string> =
|
---|
366 | // if you could not find path params, fallback to `string`
|
---|
367 | [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
|
---|
368 |
|
---|
369 | /**
|
---|
370 | * The parameters that were parsed from the URL path.
|
---|
371 | */
|
---|
372 | export type Params<Key extends string = string> = {
|
---|
373 | readonly [key in Key]: string | undefined;
|
---|
374 | };
|
---|
375 |
|
---|
376 | /**
|
---|
377 | * A RouteMatch contains info about how a route matched a URL.
|
---|
378 | */
|
---|
379 | export interface AgnosticRouteMatch<
|
---|
380 | ParamKey extends string = string,
|
---|
381 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
382 | > {
|
---|
383 | /**
|
---|
384 | * The names and values of dynamic parameters in the URL.
|
---|
385 | */
|
---|
386 | params: Params<ParamKey>;
|
---|
387 | /**
|
---|
388 | * The portion of the URL pathname that was matched.
|
---|
389 | */
|
---|
390 | pathname: string;
|
---|
391 | /**
|
---|
392 | * The portion of the URL pathname that was matched before child routes.
|
---|
393 | */
|
---|
394 | pathnameBase: string;
|
---|
395 | /**
|
---|
396 | * The route object that was used to match.
|
---|
397 | */
|
---|
398 | route: RouteObjectType;
|
---|
399 | }
|
---|
400 |
|
---|
401 | export interface AgnosticDataRouteMatch
|
---|
402 | extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}
|
---|
403 |
|
---|
404 | function isIndexRoute(
|
---|
405 | route: AgnosticRouteObject
|
---|
406 | ): route is AgnosticIndexRouteObject {
|
---|
407 | return route.index === true;
|
---|
408 | }
|
---|
409 |
|
---|
410 | // Walk the route tree generating unique IDs where necessary, so we are working
|
---|
411 | // solely with AgnosticDataRouteObject's within the Router
|
---|
412 | export function convertRoutesToDataRoutes(
|
---|
413 | routes: AgnosticRouteObject[],
|
---|
414 | mapRouteProperties: MapRoutePropertiesFunction,
|
---|
415 | parentPath: number[] = [],
|
---|
416 | manifest: RouteManifest = {}
|
---|
417 | ): AgnosticDataRouteObject[] {
|
---|
418 | return routes.map((route, index) => {
|
---|
419 | let treePath = [...parentPath, index];
|
---|
420 | let id = typeof route.id === "string" ? route.id : treePath.join("-");
|
---|
421 | invariant(
|
---|
422 | route.index !== true || !route.children,
|
---|
423 | `Cannot specify children on an index route`
|
---|
424 | );
|
---|
425 | invariant(
|
---|
426 | !manifest[id],
|
---|
427 | `Found a route id collision on id "${id}". Route ` +
|
---|
428 | "id's must be globally unique within Data Router usages"
|
---|
429 | );
|
---|
430 |
|
---|
431 | if (isIndexRoute(route)) {
|
---|
432 | let indexRoute: AgnosticDataIndexRouteObject = {
|
---|
433 | ...route,
|
---|
434 | ...mapRouteProperties(route),
|
---|
435 | id,
|
---|
436 | };
|
---|
437 | manifest[id] = indexRoute;
|
---|
438 | return indexRoute;
|
---|
439 | } else {
|
---|
440 | let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {
|
---|
441 | ...route,
|
---|
442 | ...mapRouteProperties(route),
|
---|
443 | id,
|
---|
444 | children: undefined,
|
---|
445 | };
|
---|
446 | manifest[id] = pathOrLayoutRoute;
|
---|
447 |
|
---|
448 | if (route.children) {
|
---|
449 | pathOrLayoutRoute.children = convertRoutesToDataRoutes(
|
---|
450 | route.children,
|
---|
451 | mapRouteProperties,
|
---|
452 | treePath,
|
---|
453 | manifest
|
---|
454 | );
|
---|
455 | }
|
---|
456 |
|
---|
457 | return pathOrLayoutRoute;
|
---|
458 | }
|
---|
459 | });
|
---|
460 | }
|
---|
461 |
|
---|
462 | /**
|
---|
463 | * Matches the given routes to a location and returns the match data.
|
---|
464 | *
|
---|
465 | * @see https://reactrouter.com/utils/match-routes
|
---|
466 | */
|
---|
467 | export function matchRoutes<
|
---|
468 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
469 | >(
|
---|
470 | routes: RouteObjectType[],
|
---|
471 | locationArg: Partial<Location> | string,
|
---|
472 | basename = "/"
|
---|
473 | ): AgnosticRouteMatch<string, RouteObjectType>[] | null {
|
---|
474 | let location =
|
---|
475 | typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
|
---|
476 |
|
---|
477 | let pathname = stripBasename(location.pathname || "/", basename);
|
---|
478 |
|
---|
479 | if (pathname == null) {
|
---|
480 | return null;
|
---|
481 | }
|
---|
482 |
|
---|
483 | let branches = flattenRoutes(routes);
|
---|
484 | rankRouteBranches(branches);
|
---|
485 |
|
---|
486 | let matches = null;
|
---|
487 | for (let i = 0; matches == null && i < branches.length; ++i) {
|
---|
488 | // Incoming pathnames are generally encoded from either window.location
|
---|
489 | // or from router.navigate, but we want to match against the unencoded
|
---|
490 | // paths in the route definitions. Memory router locations won't be
|
---|
491 | // encoded here but there also shouldn't be anything to decode so this
|
---|
492 | // should be a safe operation. This avoids needing matchRoutes to be
|
---|
493 | // history-aware.
|
---|
494 | let decoded = decodePath(pathname);
|
---|
495 | matches = matchRouteBranch<string, RouteObjectType>(branches[i], decoded);
|
---|
496 | }
|
---|
497 |
|
---|
498 | return matches;
|
---|
499 | }
|
---|
500 |
|
---|
501 | export interface UIMatch<Data = unknown, Handle = unknown> {
|
---|
502 | id: string;
|
---|
503 | pathname: string;
|
---|
504 | params: AgnosticRouteMatch["params"];
|
---|
505 | data: Data;
|
---|
506 | handle: Handle;
|
---|
507 | }
|
---|
508 |
|
---|
509 | export function convertRouteMatchToUiMatch(
|
---|
510 | match: AgnosticDataRouteMatch,
|
---|
511 | loaderData: RouteData
|
---|
512 | ): UIMatch {
|
---|
513 | let { route, pathname, params } = match;
|
---|
514 | return {
|
---|
515 | id: route.id,
|
---|
516 | pathname,
|
---|
517 | params,
|
---|
518 | data: loaderData[route.id],
|
---|
519 | handle: route.handle,
|
---|
520 | };
|
---|
521 | }
|
---|
522 |
|
---|
523 | interface RouteMeta<
|
---|
524 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
525 | > {
|
---|
526 | relativePath: string;
|
---|
527 | caseSensitive: boolean;
|
---|
528 | childrenIndex: number;
|
---|
529 | route: RouteObjectType;
|
---|
530 | }
|
---|
531 |
|
---|
532 | interface RouteBranch<
|
---|
533 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
534 | > {
|
---|
535 | path: string;
|
---|
536 | score: number;
|
---|
537 | routesMeta: RouteMeta<RouteObjectType>[];
|
---|
538 | }
|
---|
539 |
|
---|
540 | function flattenRoutes<
|
---|
541 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
542 | >(
|
---|
543 | routes: RouteObjectType[],
|
---|
544 | branches: RouteBranch<RouteObjectType>[] = [],
|
---|
545 | parentsMeta: RouteMeta<RouteObjectType>[] = [],
|
---|
546 | parentPath = ""
|
---|
547 | ): RouteBranch<RouteObjectType>[] {
|
---|
548 | let flattenRoute = (
|
---|
549 | route: RouteObjectType,
|
---|
550 | index: number,
|
---|
551 | relativePath?: string
|
---|
552 | ) => {
|
---|
553 | let meta: RouteMeta<RouteObjectType> = {
|
---|
554 | relativePath:
|
---|
555 | relativePath === undefined ? route.path || "" : relativePath,
|
---|
556 | caseSensitive: route.caseSensitive === true,
|
---|
557 | childrenIndex: index,
|
---|
558 | route,
|
---|
559 | };
|
---|
560 |
|
---|
561 | if (meta.relativePath.startsWith("/")) {
|
---|
562 | invariant(
|
---|
563 | meta.relativePath.startsWith(parentPath),
|
---|
564 | `Absolute route path "${meta.relativePath}" nested under path ` +
|
---|
565 | `"${parentPath}" is not valid. An absolute child route path ` +
|
---|
566 | `must start with the combined path of all its parent routes.`
|
---|
567 | );
|
---|
568 |
|
---|
569 | meta.relativePath = meta.relativePath.slice(parentPath.length);
|
---|
570 | }
|
---|
571 |
|
---|
572 | let path = joinPaths([parentPath, meta.relativePath]);
|
---|
573 | let routesMeta = parentsMeta.concat(meta);
|
---|
574 |
|
---|
575 | // Add the children before adding this route to the array, so we traverse the
|
---|
576 | // route tree depth-first and child routes appear before their parents in
|
---|
577 | // the "flattened" version.
|
---|
578 | if (route.children && route.children.length > 0) {
|
---|
579 | invariant(
|
---|
580 | // Our types know better, but runtime JS may not!
|
---|
581 | // @ts-expect-error
|
---|
582 | route.index !== true,
|
---|
583 | `Index routes must not have child routes. Please remove ` +
|
---|
584 | `all child routes from route path "${path}".`
|
---|
585 | );
|
---|
586 |
|
---|
587 | flattenRoutes(route.children, branches, routesMeta, path);
|
---|
588 | }
|
---|
589 |
|
---|
590 | // Routes without a path shouldn't ever match by themselves unless they are
|
---|
591 | // index routes, so don't add them to the list of possible branches.
|
---|
592 | if (route.path == null && !route.index) {
|
---|
593 | return;
|
---|
594 | }
|
---|
595 |
|
---|
596 | branches.push({
|
---|
597 | path,
|
---|
598 | score: computeScore(path, route.index),
|
---|
599 | routesMeta,
|
---|
600 | });
|
---|
601 | };
|
---|
602 | routes.forEach((route, index) => {
|
---|
603 | // coarse-grain check for optional params
|
---|
604 | if (route.path === "" || !route.path?.includes("?")) {
|
---|
605 | flattenRoute(route, index);
|
---|
606 | } else {
|
---|
607 | for (let exploded of explodeOptionalSegments(route.path)) {
|
---|
608 | flattenRoute(route, index, exploded);
|
---|
609 | }
|
---|
610 | }
|
---|
611 | });
|
---|
612 |
|
---|
613 | return branches;
|
---|
614 | }
|
---|
615 |
|
---|
616 | /**
|
---|
617 | * Computes all combinations of optional path segments for a given path,
|
---|
618 | * excluding combinations that are ambiguous and of lower priority.
|
---|
619 | *
|
---|
620 | * For example, `/one/:two?/three/:four?/:five?` explodes to:
|
---|
621 | * - `/one/three`
|
---|
622 | * - `/one/:two/three`
|
---|
623 | * - `/one/three/:four`
|
---|
624 | * - `/one/three/:five`
|
---|
625 | * - `/one/:two/three/:four`
|
---|
626 | * - `/one/:two/three/:five`
|
---|
627 | * - `/one/three/:four/:five`
|
---|
628 | * - `/one/:two/three/:four/:five`
|
---|
629 | */
|
---|
630 | function explodeOptionalSegments(path: string): string[] {
|
---|
631 | let segments = path.split("/");
|
---|
632 | if (segments.length === 0) return [];
|
---|
633 |
|
---|
634 | let [first, ...rest] = segments;
|
---|
635 |
|
---|
636 | // Optional path segments are denoted by a trailing `?`
|
---|
637 | let isOptional = first.endsWith("?");
|
---|
638 | // Compute the corresponding required segment: `foo?` -> `foo`
|
---|
639 | let required = first.replace(/\?$/, "");
|
---|
640 |
|
---|
641 | if (rest.length === 0) {
|
---|
642 | // Intepret empty string as omitting an optional segment
|
---|
643 | // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
|
---|
644 | return isOptional ? [required, ""] : [required];
|
---|
645 | }
|
---|
646 |
|
---|
647 | let restExploded = explodeOptionalSegments(rest.join("/"));
|
---|
648 |
|
---|
649 | let result: string[] = [];
|
---|
650 |
|
---|
651 | // All child paths with the prefix. Do this for all children before the
|
---|
652 | // optional version for all children, so we get consistent ordering where the
|
---|
653 | // parent optional aspect is preferred as required. Otherwise, we can get
|
---|
654 | // child sections interspersed where deeper optional segments are higher than
|
---|
655 | // parent optional segments, where for example, /:two would explode _earlier_
|
---|
656 | // then /:one. By always including the parent as required _for all children_
|
---|
657 | // first, we avoid this issue
|
---|
658 | result.push(
|
---|
659 | ...restExploded.map((subpath) =>
|
---|
660 | subpath === "" ? required : [required, subpath].join("/")
|
---|
661 | )
|
---|
662 | );
|
---|
663 |
|
---|
664 | // Then, if this is an optional value, add all child versions without
|
---|
665 | if (isOptional) {
|
---|
666 | result.push(...restExploded);
|
---|
667 | }
|
---|
668 |
|
---|
669 | // for absolute paths, ensure `/` instead of empty segment
|
---|
670 | return result.map((exploded) =>
|
---|
671 | path.startsWith("/") && exploded === "" ? "/" : exploded
|
---|
672 | );
|
---|
673 | }
|
---|
674 |
|
---|
675 | function rankRouteBranches(branches: RouteBranch[]): void {
|
---|
676 | branches.sort((a, b) =>
|
---|
677 | a.score !== b.score
|
---|
678 | ? b.score - a.score // Higher score first
|
---|
679 | : compareIndexes(
|
---|
680 | a.routesMeta.map((meta) => meta.childrenIndex),
|
---|
681 | b.routesMeta.map((meta) => meta.childrenIndex)
|
---|
682 | )
|
---|
683 | );
|
---|
684 | }
|
---|
685 |
|
---|
686 | const paramRe = /^:[\w-]+$/;
|
---|
687 | const dynamicSegmentValue = 3;
|
---|
688 | const indexRouteValue = 2;
|
---|
689 | const emptySegmentValue = 1;
|
---|
690 | const staticSegmentValue = 10;
|
---|
691 | const splatPenalty = -2;
|
---|
692 | const isSplat = (s: string) => s === "*";
|
---|
693 |
|
---|
694 | function computeScore(path: string, index: boolean | undefined): number {
|
---|
695 | let segments = path.split("/");
|
---|
696 | let initialScore = segments.length;
|
---|
697 | if (segments.some(isSplat)) {
|
---|
698 | initialScore += splatPenalty;
|
---|
699 | }
|
---|
700 |
|
---|
701 | if (index) {
|
---|
702 | initialScore += indexRouteValue;
|
---|
703 | }
|
---|
704 |
|
---|
705 | return segments
|
---|
706 | .filter((s) => !isSplat(s))
|
---|
707 | .reduce(
|
---|
708 | (score, segment) =>
|
---|
709 | score +
|
---|
710 | (paramRe.test(segment)
|
---|
711 | ? dynamicSegmentValue
|
---|
712 | : segment === ""
|
---|
713 | ? emptySegmentValue
|
---|
714 | : staticSegmentValue),
|
---|
715 | initialScore
|
---|
716 | );
|
---|
717 | }
|
---|
718 |
|
---|
719 | function compareIndexes(a: number[], b: number[]): number {
|
---|
720 | let siblings =
|
---|
721 | a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
|
---|
722 |
|
---|
723 | return siblings
|
---|
724 | ? // If two routes are siblings, we should try to match the earlier sibling
|
---|
725 | // first. This allows people to have fine-grained control over the matching
|
---|
726 | // behavior by simply putting routes with identical paths in the order they
|
---|
727 | // want them tried.
|
---|
728 | a[a.length - 1] - b[b.length - 1]
|
---|
729 | : // Otherwise, it doesn't really make sense to rank non-siblings by index,
|
---|
730 | // so they sort equally.
|
---|
731 | 0;
|
---|
732 | }
|
---|
733 |
|
---|
734 | function matchRouteBranch<
|
---|
735 | ParamKey extends string = string,
|
---|
736 | RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
|
---|
737 | >(
|
---|
738 | branch: RouteBranch<RouteObjectType>,
|
---|
739 | pathname: string
|
---|
740 | ): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {
|
---|
741 | let { routesMeta } = branch;
|
---|
742 |
|
---|
743 | let matchedParams = {};
|
---|
744 | let matchedPathname = "/";
|
---|
745 | let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];
|
---|
746 | for (let i = 0; i < routesMeta.length; ++i) {
|
---|
747 | let meta = routesMeta[i];
|
---|
748 | let end = i === routesMeta.length - 1;
|
---|
749 | let remainingPathname =
|
---|
750 | matchedPathname === "/"
|
---|
751 | ? pathname
|
---|
752 | : pathname.slice(matchedPathname.length) || "/";
|
---|
753 | let match = matchPath(
|
---|
754 | { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
|
---|
755 | remainingPathname
|
---|
756 | );
|
---|
757 |
|
---|
758 | if (!match) return null;
|
---|
759 |
|
---|
760 | Object.assign(matchedParams, match.params);
|
---|
761 |
|
---|
762 | let route = meta.route;
|
---|
763 |
|
---|
764 | matches.push({
|
---|
765 | // TODO: Can this as be avoided?
|
---|
766 | params: matchedParams as Params<ParamKey>,
|
---|
767 | pathname: joinPaths([matchedPathname, match.pathname]),
|
---|
768 | pathnameBase: normalizePathname(
|
---|
769 | joinPaths([matchedPathname, match.pathnameBase])
|
---|
770 | ),
|
---|
771 | route,
|
---|
772 | });
|
---|
773 |
|
---|
774 | if (match.pathnameBase !== "/") {
|
---|
775 | matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
|
---|
776 | }
|
---|
777 | }
|
---|
778 |
|
---|
779 | return matches;
|
---|
780 | }
|
---|
781 |
|
---|
782 | /**
|
---|
783 | * Returns a path with params interpolated.
|
---|
784 | *
|
---|
785 | * @see https://reactrouter.com/utils/generate-path
|
---|
786 | */
|
---|
787 | export function generatePath<Path extends string>(
|
---|
788 | originalPath: Path,
|
---|
789 | params: {
|
---|
790 | [key in PathParam<Path>]: string | null;
|
---|
791 | } = {} as any
|
---|
792 | ): string {
|
---|
793 | let path: string = originalPath;
|
---|
794 | if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
|
---|
795 | warning(
|
---|
796 | false,
|
---|
797 | `Route path "${path}" will be treated as if it were ` +
|
---|
798 | `"${path.replace(/\*$/, "/*")}" because the \`*\` character must ` +
|
---|
799 | `always follow a \`/\` in the pattern. To get rid of this warning, ` +
|
---|
800 | `please change the route path to "${path.replace(/\*$/, "/*")}".`
|
---|
801 | );
|
---|
802 | path = path.replace(/\*$/, "/*") as Path;
|
---|
803 | }
|
---|
804 |
|
---|
805 | // ensure `/` is added at the beginning if the path is absolute
|
---|
806 | const prefix = path.startsWith("/") ? "/" : "";
|
---|
807 |
|
---|
808 | const stringify = (p: any) =>
|
---|
809 | p == null ? "" : typeof p === "string" ? p : String(p);
|
---|
810 |
|
---|
811 | const segments = path
|
---|
812 | .split(/\/+/)
|
---|
813 | .map((segment, index, array) => {
|
---|
814 | const isLastSegment = index === array.length - 1;
|
---|
815 |
|
---|
816 | // only apply the splat if it's the last segment
|
---|
817 | if (isLastSegment && segment === "*") {
|
---|
818 | const star = "*" as PathParam<Path>;
|
---|
819 | // Apply the splat
|
---|
820 | return stringify(params[star]);
|
---|
821 | }
|
---|
822 |
|
---|
823 | const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
|
---|
824 | if (keyMatch) {
|
---|
825 | const [, key, optional] = keyMatch;
|
---|
826 | let param = params[key as PathParam<Path>];
|
---|
827 | invariant(optional === "?" || param != null, `Missing ":${key}" param`);
|
---|
828 | return stringify(param);
|
---|
829 | }
|
---|
830 |
|
---|
831 | // Remove any optional markers from optional static segments
|
---|
832 | return segment.replace(/\?$/g, "");
|
---|
833 | })
|
---|
834 | // Remove empty segments
|
---|
835 | .filter((segment) => !!segment);
|
---|
836 |
|
---|
837 | return prefix + segments.join("/");
|
---|
838 | }
|
---|
839 |
|
---|
840 | /**
|
---|
841 | * A PathPattern is used to match on some portion of a URL pathname.
|
---|
842 | */
|
---|
843 | export interface PathPattern<Path extends string = string> {
|
---|
844 | /**
|
---|
845 | * A string to match against a URL pathname. May contain `:id`-style segments
|
---|
846 | * to indicate placeholders for dynamic parameters. May also end with `/*` to
|
---|
847 | * indicate matching the rest of the URL pathname.
|
---|
848 | */
|
---|
849 | path: Path;
|
---|
850 | /**
|
---|
851 | * Should be `true` if the static portions of the `path` should be matched in
|
---|
852 | * the same case.
|
---|
853 | */
|
---|
854 | caseSensitive?: boolean;
|
---|
855 | /**
|
---|
856 | * Should be `true` if this pattern should match the entire URL pathname.
|
---|
857 | */
|
---|
858 | end?: boolean;
|
---|
859 | }
|
---|
860 |
|
---|
861 | /**
|
---|
862 | * A PathMatch contains info about how a PathPattern matched on a URL pathname.
|
---|
863 | */
|
---|
864 | export interface PathMatch<ParamKey extends string = string> {
|
---|
865 | /**
|
---|
866 | * The names and values of dynamic parameters in the URL.
|
---|
867 | */
|
---|
868 | params: Params<ParamKey>;
|
---|
869 | /**
|
---|
870 | * The portion of the URL pathname that was matched.
|
---|
871 | */
|
---|
872 | pathname: string;
|
---|
873 | /**
|
---|
874 | * The portion of the URL pathname that was matched before child routes.
|
---|
875 | */
|
---|
876 | pathnameBase: string;
|
---|
877 | /**
|
---|
878 | * The pattern that was used to match.
|
---|
879 | */
|
---|
880 | pattern: PathPattern;
|
---|
881 | }
|
---|
882 |
|
---|
883 | type Mutable<T> = {
|
---|
884 | -readonly [P in keyof T]: T[P];
|
---|
885 | };
|
---|
886 |
|
---|
887 | /**
|
---|
888 | * Performs pattern matching on a URL pathname and returns information about
|
---|
889 | * the match.
|
---|
890 | *
|
---|
891 | * @see https://reactrouter.com/utils/match-path
|
---|
892 | */
|
---|
893 | export function matchPath<
|
---|
894 | ParamKey extends ParamParseKey<Path>,
|
---|
895 | Path extends string
|
---|
896 | >(
|
---|
897 | pattern: PathPattern<Path> | Path,
|
---|
898 | pathname: string
|
---|
899 | ): PathMatch<ParamKey> | null {
|
---|
900 | if (typeof pattern === "string") {
|
---|
901 | pattern = { path: pattern, caseSensitive: false, end: true };
|
---|
902 | }
|
---|
903 |
|
---|
904 | let [matcher, compiledParams] = compilePath(
|
---|
905 | pattern.path,
|
---|
906 | pattern.caseSensitive,
|
---|
907 | pattern.end
|
---|
908 | );
|
---|
909 |
|
---|
910 | let match = pathname.match(matcher);
|
---|
911 | if (!match) return null;
|
---|
912 |
|
---|
913 | let matchedPathname = match[0];
|
---|
914 | let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
|
---|
915 | let captureGroups = match.slice(1);
|
---|
916 | let params: Params = compiledParams.reduce<Mutable<Params>>(
|
---|
917 | (memo, { paramName, isOptional }, index) => {
|
---|
918 | // We need to compute the pathnameBase here using the raw splat value
|
---|
919 | // instead of using params["*"] later because it will be decoded then
|
---|
920 | if (paramName === "*") {
|
---|
921 | let splatValue = captureGroups[index] || "";
|
---|
922 | pathnameBase = matchedPathname
|
---|
923 | .slice(0, matchedPathname.length - splatValue.length)
|
---|
924 | .replace(/(.)\/+$/, "$1");
|
---|
925 | }
|
---|
926 |
|
---|
927 | const value = captureGroups[index];
|
---|
928 | if (isOptional && !value) {
|
---|
929 | memo[paramName] = undefined;
|
---|
930 | } else {
|
---|
931 | memo[paramName] = (value || "").replace(/%2F/g, "/");
|
---|
932 | }
|
---|
933 | return memo;
|
---|
934 | },
|
---|
935 | {}
|
---|
936 | );
|
---|
937 |
|
---|
938 | return {
|
---|
939 | params,
|
---|
940 | pathname: matchedPathname,
|
---|
941 | pathnameBase,
|
---|
942 | pattern,
|
---|
943 | };
|
---|
944 | }
|
---|
945 |
|
---|
946 | type CompiledPathParam = { paramName: string; isOptional?: boolean };
|
---|
947 |
|
---|
948 | function compilePath(
|
---|
949 | path: string,
|
---|
950 | caseSensitive = false,
|
---|
951 | end = true
|
---|
952 | ): [RegExp, CompiledPathParam[]] {
|
---|
953 | warning(
|
---|
954 | path === "*" || !path.endsWith("*") || path.endsWith("/*"),
|
---|
955 | `Route path "${path}" will be treated as if it were ` +
|
---|
956 | `"${path.replace(/\*$/, "/*")}" because the \`*\` character must ` +
|
---|
957 | `always follow a \`/\` in the pattern. To get rid of this warning, ` +
|
---|
958 | `please change the route path to "${path.replace(/\*$/, "/*")}".`
|
---|
959 | );
|
---|
960 |
|
---|
961 | let params: CompiledPathParam[] = [];
|
---|
962 | let regexpSource =
|
---|
963 | "^" +
|
---|
964 | path
|
---|
965 | .replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
|
---|
966 | .replace(/^\/*/, "/") // Make sure it has a leading /
|
---|
967 | .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
|
---|
968 | .replace(
|
---|
969 | /\/:([\w-]+)(\?)?/g,
|
---|
970 | (_: string, paramName: string, isOptional) => {
|
---|
971 | params.push({ paramName, isOptional: isOptional != null });
|
---|
972 | return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
|
---|
973 | }
|
---|
974 | );
|
---|
975 |
|
---|
976 | if (path.endsWith("*")) {
|
---|
977 | params.push({ paramName: "*" });
|
---|
978 | regexpSource +=
|
---|
979 | path === "*" || path === "/*"
|
---|
980 | ? "(.*)$" // Already matched the initial /, just match the rest
|
---|
981 | : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
|
---|
982 | } else if (end) {
|
---|
983 | // When matching to the end, ignore trailing slashes
|
---|
984 | regexpSource += "\\/*$";
|
---|
985 | } else if (path !== "" && path !== "/") {
|
---|
986 | // If our path is non-empty and contains anything beyond an initial slash,
|
---|
987 | // then we have _some_ form of path in our regex, so we should expect to
|
---|
988 | // match only if we find the end of this path segment. Look for an optional
|
---|
989 | // non-captured trailing slash (to match a portion of the URL) or the end
|
---|
990 | // of the path (if we've matched to the end). We used to do this with a
|
---|
991 | // word boundary but that gives false positives on routes like
|
---|
992 | // /user-preferences since `-` counts as a word boundary.
|
---|
993 | regexpSource += "(?:(?=\\/|$))";
|
---|
994 | } else {
|
---|
995 | // Nothing to match for "" or "/"
|
---|
996 | }
|
---|
997 |
|
---|
998 | let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
|
---|
999 |
|
---|
1000 | return [matcher, params];
|
---|
1001 | }
|
---|
1002 |
|
---|
1003 | function decodePath(value: string) {
|
---|
1004 | try {
|
---|
1005 | return value
|
---|
1006 | .split("/")
|
---|
1007 | .map((v) => decodeURIComponent(v).replace(/\//g, "%2F"))
|
---|
1008 | .join("/");
|
---|
1009 | } catch (error) {
|
---|
1010 | warning(
|
---|
1011 | false,
|
---|
1012 | `The URL path "${value}" could not be decoded because it is is a ` +
|
---|
1013 | `malformed URL segment. This is probably due to a bad percent ` +
|
---|
1014 | `encoding (${error}).`
|
---|
1015 | );
|
---|
1016 |
|
---|
1017 | return value;
|
---|
1018 | }
|
---|
1019 | }
|
---|
1020 |
|
---|
1021 | /**
|
---|
1022 | * @private
|
---|
1023 | */
|
---|
1024 | export function stripBasename(
|
---|
1025 | pathname: string,
|
---|
1026 | basename: string
|
---|
1027 | ): string | null {
|
---|
1028 | if (basename === "/") return pathname;
|
---|
1029 |
|
---|
1030 | if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
|
---|
1031 | return null;
|
---|
1032 | }
|
---|
1033 |
|
---|
1034 | // We want to leave trailing slash behavior in the user's control, so if they
|
---|
1035 | // specify a basename with a trailing slash, we should support it
|
---|
1036 | let startIndex = basename.endsWith("/")
|
---|
1037 | ? basename.length - 1
|
---|
1038 | : basename.length;
|
---|
1039 | let nextChar = pathname.charAt(startIndex);
|
---|
1040 | if (nextChar && nextChar !== "/") {
|
---|
1041 | // pathname does not start with basename/
|
---|
1042 | return null;
|
---|
1043 | }
|
---|
1044 |
|
---|
1045 | return pathname.slice(startIndex) || "/";
|
---|
1046 | }
|
---|
1047 |
|
---|
1048 | /**
|
---|
1049 | * Returns a resolved path object relative to the given pathname.
|
---|
1050 | *
|
---|
1051 | * @see https://reactrouter.com/utils/resolve-path
|
---|
1052 | */
|
---|
1053 | export function resolvePath(to: To, fromPathname = "/"): Path {
|
---|
1054 | let {
|
---|
1055 | pathname: toPathname,
|
---|
1056 | search = "",
|
---|
1057 | hash = "",
|
---|
1058 | } = typeof to === "string" ? parsePath(to) : to;
|
---|
1059 |
|
---|
1060 | let pathname = toPathname
|
---|
1061 | ? toPathname.startsWith("/")
|
---|
1062 | ? toPathname
|
---|
1063 | : resolvePathname(toPathname, fromPathname)
|
---|
1064 | : fromPathname;
|
---|
1065 |
|
---|
1066 | return {
|
---|
1067 | pathname,
|
---|
1068 | search: normalizeSearch(search),
|
---|
1069 | hash: normalizeHash(hash),
|
---|
1070 | };
|
---|
1071 | }
|
---|
1072 |
|
---|
1073 | function resolvePathname(relativePath: string, fromPathname: string): string {
|
---|
1074 | let segments = fromPathname.replace(/\/+$/, "").split("/");
|
---|
1075 | let relativeSegments = relativePath.split("/");
|
---|
1076 |
|
---|
1077 | relativeSegments.forEach((segment) => {
|
---|
1078 | if (segment === "..") {
|
---|
1079 | // Keep the root "" segment so the pathname starts at /
|
---|
1080 | if (segments.length > 1) segments.pop();
|
---|
1081 | } else if (segment !== ".") {
|
---|
1082 | segments.push(segment);
|
---|
1083 | }
|
---|
1084 | });
|
---|
1085 |
|
---|
1086 | return segments.length > 1 ? segments.join("/") : "/";
|
---|
1087 | }
|
---|
1088 |
|
---|
1089 | function getInvalidPathError(
|
---|
1090 | char: string,
|
---|
1091 | field: string,
|
---|
1092 | dest: string,
|
---|
1093 | path: Partial<Path>
|
---|
1094 | ) {
|
---|
1095 | return (
|
---|
1096 | `Cannot include a '${char}' character in a manually specified ` +
|
---|
1097 | `\`to.${field}\` field [${JSON.stringify(
|
---|
1098 | path
|
---|
1099 | )}]. Please separate it out to the ` +
|
---|
1100 | `\`to.${dest}\` field. Alternatively you may provide the full path as ` +
|
---|
1101 | `a string in <Link to="..."> and the router will parse it for you.`
|
---|
1102 | );
|
---|
1103 | }
|
---|
1104 |
|
---|
1105 | /**
|
---|
1106 | * @private
|
---|
1107 | *
|
---|
1108 | * When processing relative navigation we want to ignore ancestor routes that
|
---|
1109 | * do not contribute to the path, such that index/pathless layout routes don't
|
---|
1110 | * interfere.
|
---|
1111 | *
|
---|
1112 | * For example, when moving a route element into an index route and/or a
|
---|
1113 | * pathless layout route, relative link behavior contained within should stay
|
---|
1114 | * the same. Both of the following examples should link back to the root:
|
---|
1115 | *
|
---|
1116 | * <Route path="/">
|
---|
1117 | * <Route path="accounts" element={<Link to=".."}>
|
---|
1118 | * </Route>
|
---|
1119 | *
|
---|
1120 | * <Route path="/">
|
---|
1121 | * <Route path="accounts">
|
---|
1122 | * <Route element={<AccountsLayout />}> // <-- Does not contribute
|
---|
1123 | * <Route index element={<Link to=".."} /> // <-- Does not contribute
|
---|
1124 | * </Route
|
---|
1125 | * </Route>
|
---|
1126 | * </Route>
|
---|
1127 | */
|
---|
1128 | export function getPathContributingMatches<
|
---|
1129 | T extends AgnosticRouteMatch = AgnosticRouteMatch
|
---|
1130 | >(matches: T[]) {
|
---|
1131 | return matches.filter(
|
---|
1132 | (match, index) =>
|
---|
1133 | index === 0 || (match.route.path && match.route.path.length > 0)
|
---|
1134 | );
|
---|
1135 | }
|
---|
1136 |
|
---|
1137 | // Return the array of pathnames for the current route matches - used to
|
---|
1138 | // generate the routePathnames input for resolveTo()
|
---|
1139 | export function getResolveToMatches<
|
---|
1140 | T extends AgnosticRouteMatch = AgnosticRouteMatch
|
---|
1141 | >(matches: T[], v7_relativeSplatPath: boolean) {
|
---|
1142 | let pathMatches = getPathContributingMatches(matches);
|
---|
1143 |
|
---|
1144 | // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
|
---|
1145 | // match so we include splat values for "." links. See:
|
---|
1146 | // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
|
---|
1147 | if (v7_relativeSplatPath) {
|
---|
1148 | return pathMatches.map((match, idx) =>
|
---|
1149 | idx === matches.length - 1 ? match.pathname : match.pathnameBase
|
---|
1150 | );
|
---|
1151 | }
|
---|
1152 |
|
---|
1153 | return pathMatches.map((match) => match.pathnameBase);
|
---|
1154 | }
|
---|
1155 |
|
---|
1156 | /**
|
---|
1157 | * @private
|
---|
1158 | */
|
---|
1159 | export function resolveTo(
|
---|
1160 | toArg: To,
|
---|
1161 | routePathnames: string[],
|
---|
1162 | locationPathname: string,
|
---|
1163 | isPathRelative = false
|
---|
1164 | ): Path {
|
---|
1165 | let to: Partial<Path>;
|
---|
1166 | if (typeof toArg === "string") {
|
---|
1167 | to = parsePath(toArg);
|
---|
1168 | } else {
|
---|
1169 | to = { ...toArg };
|
---|
1170 |
|
---|
1171 | invariant(
|
---|
1172 | !to.pathname || !to.pathname.includes("?"),
|
---|
1173 | getInvalidPathError("?", "pathname", "search", to)
|
---|
1174 | );
|
---|
1175 | invariant(
|
---|
1176 | !to.pathname || !to.pathname.includes("#"),
|
---|
1177 | getInvalidPathError("#", "pathname", "hash", to)
|
---|
1178 | );
|
---|
1179 | invariant(
|
---|
1180 | !to.search || !to.search.includes("#"),
|
---|
1181 | getInvalidPathError("#", "search", "hash", to)
|
---|
1182 | );
|
---|
1183 | }
|
---|
1184 |
|
---|
1185 | let isEmptyPath = toArg === "" || to.pathname === "";
|
---|
1186 | let toPathname = isEmptyPath ? "/" : to.pathname;
|
---|
1187 |
|
---|
1188 | let from: string;
|
---|
1189 |
|
---|
1190 | // Routing is relative to the current pathname if explicitly requested.
|
---|
1191 | //
|
---|
1192 | // If a pathname is explicitly provided in `to`, it should be relative to the
|
---|
1193 | // route context. This is explained in `Note on `<Link to>` values` in our
|
---|
1194 | // migration guide from v5 as a means of disambiguation between `to` values
|
---|
1195 | // that begin with `/` and those that do not. However, this is problematic for
|
---|
1196 | // `to` values that do not provide a pathname. `to` can simply be a search or
|
---|
1197 | // hash string, in which case we should assume that the navigation is relative
|
---|
1198 | // to the current location's pathname and *not* the route pathname.
|
---|
1199 | if (toPathname == null) {
|
---|
1200 | from = locationPathname;
|
---|
1201 | } else {
|
---|
1202 | let routePathnameIndex = routePathnames.length - 1;
|
---|
1203 |
|
---|
1204 | // With relative="route" (the default), each leading .. segment means
|
---|
1205 | // "go up one route" instead of "go up one URL segment". This is a key
|
---|
1206 | // difference from how <a href> works and a major reason we call this a
|
---|
1207 | // "to" value instead of a "href".
|
---|
1208 | if (!isPathRelative && toPathname.startsWith("..")) {
|
---|
1209 | let toSegments = toPathname.split("/");
|
---|
1210 |
|
---|
1211 | while (toSegments[0] === "..") {
|
---|
1212 | toSegments.shift();
|
---|
1213 | routePathnameIndex -= 1;
|
---|
1214 | }
|
---|
1215 |
|
---|
1216 | to.pathname = toSegments.join("/");
|
---|
1217 | }
|
---|
1218 |
|
---|
1219 | from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
|
---|
1220 | }
|
---|
1221 |
|
---|
1222 | let path = resolvePath(to, from);
|
---|
1223 |
|
---|
1224 | // Ensure the pathname has a trailing slash if the original "to" had one
|
---|
1225 | let hasExplicitTrailingSlash =
|
---|
1226 | toPathname && toPathname !== "/" && toPathname.endsWith("/");
|
---|
1227 | // Or if this was a link to the current path which has a trailing slash
|
---|
1228 | let hasCurrentTrailingSlash =
|
---|
1229 | (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
|
---|
1230 | if (
|
---|
1231 | !path.pathname.endsWith("/") &&
|
---|
1232 | (hasExplicitTrailingSlash || hasCurrentTrailingSlash)
|
---|
1233 | ) {
|
---|
1234 | path.pathname += "/";
|
---|
1235 | }
|
---|
1236 |
|
---|
1237 | return path;
|
---|
1238 | }
|
---|
1239 |
|
---|
1240 | /**
|
---|
1241 | * @private
|
---|
1242 | */
|
---|
1243 | export function getToPathname(to: To): string | undefined {
|
---|
1244 | // Empty strings should be treated the same as / paths
|
---|
1245 | return to === "" || (to as Path).pathname === ""
|
---|
1246 | ? "/"
|
---|
1247 | : typeof to === "string"
|
---|
1248 | ? parsePath(to).pathname
|
---|
1249 | : to.pathname;
|
---|
1250 | }
|
---|
1251 |
|
---|
1252 | /**
|
---|
1253 | * @private
|
---|
1254 | */
|
---|
1255 | export const joinPaths = (paths: string[]): string =>
|
---|
1256 | paths.join("/").replace(/\/\/+/g, "/");
|
---|
1257 |
|
---|
1258 | /**
|
---|
1259 | * @private
|
---|
1260 | */
|
---|
1261 | export const normalizePathname = (pathname: string): string =>
|
---|
1262 | pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
|
---|
1263 |
|
---|
1264 | /**
|
---|
1265 | * @private
|
---|
1266 | */
|
---|
1267 | export const normalizeSearch = (search: string): string =>
|
---|
1268 | !search || search === "?"
|
---|
1269 | ? ""
|
---|
1270 | : search.startsWith("?")
|
---|
1271 | ? search
|
---|
1272 | : "?" + search;
|
---|
1273 |
|
---|
1274 | /**
|
---|
1275 | * @private
|
---|
1276 | */
|
---|
1277 | export const normalizeHash = (hash: string): string =>
|
---|
1278 | !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
|
---|
1279 |
|
---|
1280 | export type JsonFunction = <Data>(
|
---|
1281 | data: Data,
|
---|
1282 | init?: number | ResponseInit
|
---|
1283 | ) => Response;
|
---|
1284 |
|
---|
1285 | /**
|
---|
1286 | * This is a shortcut for creating `application/json` responses. Converts `data`
|
---|
1287 | * to JSON and sets the `Content-Type` header.
|
---|
1288 | */
|
---|
1289 | export const json: JsonFunction = (data, init = {}) => {
|
---|
1290 | let responseInit = typeof init === "number" ? { status: init } : init;
|
---|
1291 |
|
---|
1292 | let headers = new Headers(responseInit.headers);
|
---|
1293 | if (!headers.has("Content-Type")) {
|
---|
1294 | headers.set("Content-Type", "application/json; charset=utf-8");
|
---|
1295 | }
|
---|
1296 |
|
---|
1297 | return new Response(JSON.stringify(data), {
|
---|
1298 | ...responseInit,
|
---|
1299 | headers,
|
---|
1300 | });
|
---|
1301 | };
|
---|
1302 |
|
---|
1303 | export interface TrackedPromise extends Promise<any> {
|
---|
1304 | _tracked?: boolean;
|
---|
1305 | _data?: any;
|
---|
1306 | _error?: any;
|
---|
1307 | }
|
---|
1308 |
|
---|
1309 | export class AbortedDeferredError extends Error {}
|
---|
1310 |
|
---|
1311 | export class DeferredData {
|
---|
1312 | private pendingKeysSet: Set<string> = new Set<string>();
|
---|
1313 | private controller: AbortController;
|
---|
1314 | private abortPromise: Promise<void>;
|
---|
1315 | private unlistenAbortSignal: () => void;
|
---|
1316 | private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =
|
---|
1317 | new Set();
|
---|
1318 | data: Record<string, unknown>;
|
---|
1319 | init?: ResponseInit;
|
---|
1320 | deferredKeys: string[] = [];
|
---|
1321 |
|
---|
1322 | constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {
|
---|
1323 | invariant(
|
---|
1324 | data && typeof data === "object" && !Array.isArray(data),
|
---|
1325 | "defer() only accepts plain objects"
|
---|
1326 | );
|
---|
1327 |
|
---|
1328 | // Set up an AbortController + Promise we can race against to exit early
|
---|
1329 | // cancellation
|
---|
1330 | let reject: (e: AbortedDeferredError) => void;
|
---|
1331 | this.abortPromise = new Promise((_, r) => (reject = r));
|
---|
1332 | this.controller = new AbortController();
|
---|
1333 | let onAbort = () =>
|
---|
1334 | reject(new AbortedDeferredError("Deferred data aborted"));
|
---|
1335 | this.unlistenAbortSignal = () =>
|
---|
1336 | this.controller.signal.removeEventListener("abort", onAbort);
|
---|
1337 | this.controller.signal.addEventListener("abort", onAbort);
|
---|
1338 |
|
---|
1339 | this.data = Object.entries(data).reduce(
|
---|
1340 | (acc, [key, value]) =>
|
---|
1341 | Object.assign(acc, {
|
---|
1342 | [key]: this.trackPromise(key, value),
|
---|
1343 | }),
|
---|
1344 | {}
|
---|
1345 | );
|
---|
1346 |
|
---|
1347 | if (this.done) {
|
---|
1348 | // All incoming values were resolved
|
---|
1349 | this.unlistenAbortSignal();
|
---|
1350 | }
|
---|
1351 |
|
---|
1352 | this.init = responseInit;
|
---|
1353 | }
|
---|
1354 |
|
---|
1355 | private trackPromise(
|
---|
1356 | key: string,
|
---|
1357 | value: Promise<unknown> | unknown
|
---|
1358 | ): TrackedPromise | unknown {
|
---|
1359 | if (!(value instanceof Promise)) {
|
---|
1360 | return value;
|
---|
1361 | }
|
---|
1362 |
|
---|
1363 | this.deferredKeys.push(key);
|
---|
1364 | this.pendingKeysSet.add(key);
|
---|
1365 |
|
---|
1366 | // We store a little wrapper promise that will be extended with
|
---|
1367 | // _data/_error props upon resolve/reject
|
---|
1368 | let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(
|
---|
1369 | (data) => this.onSettle(promise, key, undefined, data as unknown),
|
---|
1370 | (error) => this.onSettle(promise, key, error as unknown)
|
---|
1371 | );
|
---|
1372 |
|
---|
1373 | // Register rejection listeners to avoid uncaught promise rejections on
|
---|
1374 | // errors or aborted deferred values
|
---|
1375 | promise.catch(() => {});
|
---|
1376 |
|
---|
1377 | Object.defineProperty(promise, "_tracked", { get: () => true });
|
---|
1378 | return promise;
|
---|
1379 | }
|
---|
1380 |
|
---|
1381 | private onSettle(
|
---|
1382 | promise: TrackedPromise,
|
---|
1383 | key: string,
|
---|
1384 | error: unknown,
|
---|
1385 | data?: unknown
|
---|
1386 | ): unknown {
|
---|
1387 | if (
|
---|
1388 | this.controller.signal.aborted &&
|
---|
1389 | error instanceof AbortedDeferredError
|
---|
1390 | ) {
|
---|
1391 | this.unlistenAbortSignal();
|
---|
1392 | Object.defineProperty(promise, "_error", { get: () => error });
|
---|
1393 | return Promise.reject(error);
|
---|
1394 | }
|
---|
1395 |
|
---|
1396 | this.pendingKeysSet.delete(key);
|
---|
1397 |
|
---|
1398 | if (this.done) {
|
---|
1399 | // Nothing left to abort!
|
---|
1400 | this.unlistenAbortSignal();
|
---|
1401 | }
|
---|
1402 |
|
---|
1403 | // If the promise was resolved/rejected with undefined, we'll throw an error as you
|
---|
1404 | // should always resolve with a value or null
|
---|
1405 | if (error === undefined && data === undefined) {
|
---|
1406 | let undefinedError = new Error(
|
---|
1407 | `Deferred data for key "${key}" resolved/rejected with \`undefined\`, ` +
|
---|
1408 | `you must resolve/reject with a value or \`null\`.`
|
---|
1409 | );
|
---|
1410 | Object.defineProperty(promise, "_error", { get: () => undefinedError });
|
---|
1411 | this.emit(false, key);
|
---|
1412 | return Promise.reject(undefinedError);
|
---|
1413 | }
|
---|
1414 |
|
---|
1415 | if (data === undefined) {
|
---|
1416 | Object.defineProperty(promise, "_error", { get: () => error });
|
---|
1417 | this.emit(false, key);
|
---|
1418 | return Promise.reject(error);
|
---|
1419 | }
|
---|
1420 |
|
---|
1421 | Object.defineProperty(promise, "_data", { get: () => data });
|
---|
1422 | this.emit(false, key);
|
---|
1423 | return data;
|
---|
1424 | }
|
---|
1425 |
|
---|
1426 | private emit(aborted: boolean, settledKey?: string) {
|
---|
1427 | this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));
|
---|
1428 | }
|
---|
1429 |
|
---|
1430 | subscribe(fn: (aborted: boolean, settledKey?: string) => void) {
|
---|
1431 | this.subscribers.add(fn);
|
---|
1432 | return () => this.subscribers.delete(fn);
|
---|
1433 | }
|
---|
1434 |
|
---|
1435 | cancel() {
|
---|
1436 | this.controller.abort();
|
---|
1437 | this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
|
---|
1438 | this.emit(true);
|
---|
1439 | }
|
---|
1440 |
|
---|
1441 | async resolveData(signal: AbortSignal) {
|
---|
1442 | let aborted = false;
|
---|
1443 | if (!this.done) {
|
---|
1444 | let onAbort = () => this.cancel();
|
---|
1445 | signal.addEventListener("abort", onAbort);
|
---|
1446 | aborted = await new Promise((resolve) => {
|
---|
1447 | this.subscribe((aborted) => {
|
---|
1448 | signal.removeEventListener("abort", onAbort);
|
---|
1449 | if (aborted || this.done) {
|
---|
1450 | resolve(aborted);
|
---|
1451 | }
|
---|
1452 | });
|
---|
1453 | });
|
---|
1454 | }
|
---|
1455 | return aborted;
|
---|
1456 | }
|
---|
1457 |
|
---|
1458 | get done() {
|
---|
1459 | return this.pendingKeysSet.size === 0;
|
---|
1460 | }
|
---|
1461 |
|
---|
1462 | get unwrappedData() {
|
---|
1463 | invariant(
|
---|
1464 | this.data !== null && this.done,
|
---|
1465 | "Can only unwrap data on initialized and settled deferreds"
|
---|
1466 | );
|
---|
1467 |
|
---|
1468 | return Object.entries(this.data).reduce(
|
---|
1469 | (acc, [key, value]) =>
|
---|
1470 | Object.assign(acc, {
|
---|
1471 | [key]: unwrapTrackedPromise(value),
|
---|
1472 | }),
|
---|
1473 | {}
|
---|
1474 | );
|
---|
1475 | }
|
---|
1476 |
|
---|
1477 | get pendingKeys() {
|
---|
1478 | return Array.from(this.pendingKeysSet);
|
---|
1479 | }
|
---|
1480 | }
|
---|
1481 |
|
---|
1482 | function isTrackedPromise(value: any): value is TrackedPromise {
|
---|
1483 | return (
|
---|
1484 | value instanceof Promise && (value as TrackedPromise)._tracked === true
|
---|
1485 | );
|
---|
1486 | }
|
---|
1487 |
|
---|
1488 | function unwrapTrackedPromise(value: any) {
|
---|
1489 | if (!isTrackedPromise(value)) {
|
---|
1490 | return value;
|
---|
1491 | }
|
---|
1492 |
|
---|
1493 | if (value._error) {
|
---|
1494 | throw value._error;
|
---|
1495 | }
|
---|
1496 | return value._data;
|
---|
1497 | }
|
---|
1498 |
|
---|
1499 | export type DeferFunction = (
|
---|
1500 | data: Record<string, unknown>,
|
---|
1501 | init?: number | ResponseInit
|
---|
1502 | ) => DeferredData;
|
---|
1503 |
|
---|
1504 | export const defer: DeferFunction = (data, init = {}) => {
|
---|
1505 | let responseInit = typeof init === "number" ? { status: init } : init;
|
---|
1506 |
|
---|
1507 | return new DeferredData(data, responseInit);
|
---|
1508 | };
|
---|
1509 |
|
---|
1510 | export type RedirectFunction = (
|
---|
1511 | url: string,
|
---|
1512 | init?: number | ResponseInit
|
---|
1513 | ) => Response;
|
---|
1514 |
|
---|
1515 | /**
|
---|
1516 | * A redirect response. Sets the status code and the `Location` header.
|
---|
1517 | * Defaults to "302 Found".
|
---|
1518 | */
|
---|
1519 | export const redirect: RedirectFunction = (url, init = 302) => {
|
---|
1520 | let responseInit = init;
|
---|
1521 | if (typeof responseInit === "number") {
|
---|
1522 | responseInit = { status: responseInit };
|
---|
1523 | } else if (typeof responseInit.status === "undefined") {
|
---|
1524 | responseInit.status = 302;
|
---|
1525 | }
|
---|
1526 |
|
---|
1527 | let headers = new Headers(responseInit.headers);
|
---|
1528 | headers.set("Location", url);
|
---|
1529 |
|
---|
1530 | return new Response(null, {
|
---|
1531 | ...responseInit,
|
---|
1532 | headers,
|
---|
1533 | });
|
---|
1534 | };
|
---|
1535 |
|
---|
1536 | /**
|
---|
1537 | * A redirect response that will force a document reload to the new location.
|
---|
1538 | * Sets the status code and the `Location` header.
|
---|
1539 | * Defaults to "302 Found".
|
---|
1540 | */
|
---|
1541 | export const redirectDocument: RedirectFunction = (url, init) => {
|
---|
1542 | let response = redirect(url, init);
|
---|
1543 | response.headers.set("X-Remix-Reload-Document", "true");
|
---|
1544 | return response;
|
---|
1545 | };
|
---|
1546 |
|
---|
1547 | export type ErrorResponse = {
|
---|
1548 | status: number;
|
---|
1549 | statusText: string;
|
---|
1550 | data: any;
|
---|
1551 | };
|
---|
1552 |
|
---|
1553 | /**
|
---|
1554 | * @private
|
---|
1555 | * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
|
---|
1556 | *
|
---|
1557 | * We don't export the class for public use since it's an implementation
|
---|
1558 | * detail, but we export the interface above so folks can build their own
|
---|
1559 | * abstractions around instances via isRouteErrorResponse()
|
---|
1560 | */
|
---|
1561 | export class ErrorResponseImpl implements ErrorResponse {
|
---|
1562 | status: number;
|
---|
1563 | statusText: string;
|
---|
1564 | data: any;
|
---|
1565 | private error?: Error;
|
---|
1566 | private internal: boolean;
|
---|
1567 |
|
---|
1568 | constructor(
|
---|
1569 | status: number,
|
---|
1570 | statusText: string | undefined,
|
---|
1571 | data: any,
|
---|
1572 | internal = false
|
---|
1573 | ) {
|
---|
1574 | this.status = status;
|
---|
1575 | this.statusText = statusText || "";
|
---|
1576 | this.internal = internal;
|
---|
1577 | if (data instanceof Error) {
|
---|
1578 | this.data = data.toString();
|
---|
1579 | this.error = data;
|
---|
1580 | } else {
|
---|
1581 | this.data = data;
|
---|
1582 | }
|
---|
1583 | }
|
---|
1584 | }
|
---|
1585 |
|
---|
1586 | /**
|
---|
1587 | * Check if the given error is an ErrorResponse generated from a 4xx/5xx
|
---|
1588 | * Response thrown from an action/loader
|
---|
1589 | */
|
---|
1590 | export function isRouteErrorResponse(error: any): error is ErrorResponse {
|
---|
1591 | return (
|
---|
1592 | error != null &&
|
---|
1593 | typeof error.status === "number" &&
|
---|
1594 | typeof error.statusText === "string" &&
|
---|
1595 | typeof error.internal === "boolean" &&
|
---|
1596 | "data" in error
|
---|
1597 | );
|
---|
1598 | }
|
---|