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