UNPKG

34.6 kBJavaScriptView Raw
1/**
2 * react-router v8.4.0
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { ABSOLUTE_URL_REGEX, PROTOCOL_RELATIVE_URL_REGEX, normalizeProtocolRelativeUrl } from "./url.js";
12import { invariant, parsePath, warning } from "./history.js";
13import * as React$1 from "react";
14//#region lib/router/utils.ts
15/**
16* Creates a type-safe {@link RouterContext} object that can be used to
17* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
18* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
19* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
20* but specifically designed for React Router's request/response lifecycle.
21*
22* If a `defaultValue` is provided, it will be returned from `context.get()`
23* when no value has been set for the context. Otherwise, reading this context
24* when no value has been set will throw an error.
25*
26* ```tsx filename=app/context.ts
27* import { createContext } from "react-router";
28*
29* // Create a context for user data
30* export const userContext =
31* createContext<User | null>(null);
32* ```
33*
34* ```tsx filename=app/middleware/auth.ts
35* import { getUserFromSession } from "~/auth.server";
36* import { userContext } from "~/context";
37*
38* export const authMiddleware = async ({
39* context,
40* request,
41* }) => {
42* const user = await getUserFromSession(request);
43* context.set(userContext, user);
44* };
45* ```
46*
47* ```tsx filename=app/routes/profile.tsx
48* import { userContext } from "~/context";
49*
50* export async function loader({
51* context,
52* }: Route.LoaderArgs) {
53* const user = context.get(userContext);
54*
55* if (!user) {
56* throw new Response("Unauthorized", { status: 401 });
57* }
58*
59* return { user };
60* }
61* ```
62*
63* @public
64* @category Utils
65* @mode framework
66* @mode data
67* @param defaultValue An optional default value for the context. This value
68* will be returned if no value has been set for this context.
69* @returns A {@link RouterContext} object that can be used with
70* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
71* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
72*/
73function createContext(defaultValue) {
74 return { defaultValue };
75}
76/**
77* Provides methods for writing/reading values in application context in a
78* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
79*
80* @example
81* import {
82* createContext,
83* RouterContextProvider
84* } from "react-router";
85*
86* const userContext = createContext<User | null>(null);
87* const contextProvider = new RouterContextProvider();
88* contextProvider.set(userContext, getUser());
89* // ^ Type-safe
90* const user = contextProvider.get(userContext);
91* // ^ User
92*
93* @public
94* @category Utils
95* @mode framework
96* @mode data
97*/
98var RouterContextProvider = class {
99 #map = /* @__PURE__ */ new Map();
100 /**
101 * Create a new `RouterContextProvider` instance
102 * @param init An optional initial context map to populate the provider with
103 */
104 constructor(init) {
105 if (init) for (let [context, value] of init) this.set(context, value);
106 }
107 /**
108 * Access a value from the context. If no value has been set for the context,
109 * it will return the context's `defaultValue` if provided, or throw an error
110 * if no `defaultValue` was set.
111 * @param context The context to get the value for
112 * @returns The value for the context, or the context's `defaultValue` if no
113 * value was set
114 */
115 get(context) {
116 if (this.#map.has(context)) return this.#map.get(context);
117 if (context.defaultValue !== void 0) return context.defaultValue;
118 throw new Error("No value found for context");
119 }
120 /**
121 * Set a value for the context. If the context already has a value set, this
122 * will overwrite it.
123 *
124 * @param context The context to set the value for
125 * @param value The value to set for the context
126 * @returns {void}
127 */
128 set(context, value) {
129 this.#map.set(context, value);
130 }
131};
132const unsupportedLazyRouteObjectKeys = new Set([
133 "lazy",
134 "caseSensitive",
135 "path",
136 "id",
137 "index",
138 "children",
139 "unstable_validateParams"
140]);
141function isUnsupportedLazyRouteObjectKey(key) {
142 return unsupportedLazyRouteObjectKeys.has(key);
143}
144const unsupportedLazyRouteFunctionKeys = new Set([
145 "lazy",
146 "caseSensitive",
147 "path",
148 "id",
149 "index",
150 "middleware",
151 "children",
152 "unstable_validateParams"
153]);
154function isUnsupportedLazyRouteFunctionKey(key) {
155 return unsupportedLazyRouteFunctionKeys.has(key);
156}
157function isIndexRoute(route) {
158 return route.index === true;
159}
160function defaultMapRouteProperties(route) {
161 let updates = {};
162 if (route.Component) {
163 if (route.element) warning(false, "You should not include both `Component` and `element` on your route - `Component` will be used.");
164 Object.assign(updates, {
165 element: React$1.createElement(route.Component),
166 Component: void 0
167 });
168 }
169 if (route.HydrateFallback) {
170 if (route.hydrateFallbackElement) warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used.");
171 Object.assign(updates, {
172 hydrateFallbackElement: React$1.createElement(route.HydrateFallback),
173 HydrateFallback: void 0
174 });
175 }
176 if (route.ErrorBoundary) {
177 if (route.errorElement) warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used.");
178 Object.assign(updates, {
179 errorElement: React$1.createElement(route.ErrorBoundary),
180 ErrorBoundary: void 0
181 });
182 }
183 return updates;
184}
185function convertRoutesToDataRoutes(routes, mapRouteProperties = defaultMapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
186 return routes.map((route, index) => {
187 let treePath = [...parentPath, String(index)];
188 let id = typeof route.id === "string" ? route.id : treePath.join("-");
189 invariant(route.index !== true || !route.children, `Cannot specify children on an index route`);
190 invariant(allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`);
191 if (isIndexRoute(route)) {
192 let indexRoute = {
193 ...route,
194 id
195 };
196 manifest[id] = mergeRouteUpdates(indexRoute, mapRouteProperties(indexRoute));
197 return indexRoute;
198 } else {
199 let pathOrLayoutRoute = {
200 ...route,
201 id,
202 children: void 0
203 };
204 manifest[id] = mergeRouteUpdates(pathOrLayoutRoute, mapRouteProperties(pathOrLayoutRoute));
205 if (route.children) pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest, allowInPlaceMutations);
206 return pathOrLayoutRoute;
207 }
208 });
209}
210function mergeRouteUpdates(route, updates) {
211 return Object.assign(route, {
212 ...updates,
213 ...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: {
214 ...route.lazy,
215 ...updates.lazy
216 } } : {}
217 });
218}
219/**
220* Matches the given routes to a location and returns the match data.
221*
222* @example
223* import { matchRoutes } from "react-router";
224*
225* let routes = [{
226* path: "/",
227* Component: Root,
228* children: [{
229* path: "dashboard",
230* Component: Dashboard,
231* }]
232* }];
233*
234* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
235*
236* @public
237* @category Utils
238* @param routes The array of route objects to match against.
239* @param locationArg The location to match against, either a string path or a
240* partial {@link Location} object
241* @param basename Optional base path to strip from the location before matching.
242* Defaults to `/`.
243* @returns An array of matched routes, or `null` if no matches were found.
244*/
245function matchRoutes(routes, locationArg, basename = "/") {
246 return matchRoutesImpl(routes, locationArg, basename, false);
247}
248function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) {
249 let pathname = stripBasename((typeof locationArg === "string" ? parsePath(locationArg) : locationArg).pathname || "/", basename);
250 if (pathname == null) return null;
251 let branches = precomputedBranches ?? flattenAndRankRoutes(routes);
252 let matches = null;
253 let decoded = decodePath(pathname);
254 for (let i = 0; matches == null && i < branches.length; ++i) matches = matchRouteBranch(branches[i], decoded, allowPartial);
255 return matches;
256}
257function convertRouteMatchToUiMatch(match, loaderData) {
258 let { route, pathname, params } = match;
259 return {
260 id: route.id,
261 pathname,
262 params,
263 loaderData: loaderData[route.id],
264 handle: route.handle
265 };
266}
267function flattenAndRankRoutes(routes) {
268 let branches = flattenRoutes(routes);
269 rankRouteBranches(branches);
270 return branches;
271}
272function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
273 let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
274 let meta = {
275 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
276 caseSensitive: route.caseSensitive === true,
277 childrenIndex: index,
278 route
279 };
280 if (meta.relativePath.startsWith("/")) {
281 if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) return;
282 invariant(meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`);
283 meta.relativePath = meta.relativePath.slice(parentPath.length);
284 }
285 let path = joinPaths([parentPath, meta.relativePath]);
286 let routesMeta = parentsMeta.concat(meta);
287 if (route.children && route.children.length > 0) {
288 invariant(route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
289 flattenRoutes(route.children, branches, routesMeta, path, hasParentOptionalSegments);
290 }
291 if (route.path == null && !route.index) return;
292 branches.push({
293 path,
294 score: computeScore(path, route.index),
295 routesMeta: routesMeta.map((meta, i) => {
296 let [matcher, params] = compilePath(meta.relativePath, meta.caseSensitive, i === routesMeta.length - 1);
297 return {
298 ...meta,
299 matcher,
300 compiledParams: params
301 };
302 })
303 });
304 };
305 routes.forEach((route, index) => {
306 if (route.path === "" || !route.path?.includes("?")) flattenRoute(route, index);
307 else for (let exploded of explodeOptionalSegments(route.path)) flattenRoute(route, index, true, exploded);
308 });
309 return branches;
310}
311function explodeOptionalSegments(path) {
312 let segments = path.split("/");
313 if (segments.length === 0) return [];
314 let [first, ...rest] = segments;
315 let isOptional = first.endsWith("?");
316 let required = first.replace(/\?$/, "");
317 if (rest.length === 0) return isOptional ? [required, ""] : [required];
318 let restExploded = explodeOptionalSegments(rest.join("/"));
319 let result = [];
320 result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
321 if (isOptional) result.push(...restExploded);
322 return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
323}
324function rankRouteBranches(branches) {
325 branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex)));
326}
327const paramRe = /^:[\w-]+$/;
328const partialParamRe = /^:[\w-]+/;
329const partialDynamicSegmentValue = 3.5;
330const dynamicSegmentValue = 3;
331const indexRouteValue = 2;
332const emptySegmentValue = 1;
333const staticSegmentValue = 10;
334const splatPenalty = -2;
335const isSplat = (s) => s === "*";
336function computeScore(path, index) {
337 let segments = path.split("/");
338 let initialScore = segments.length;
339 if (segments.some(isSplat)) initialScore += splatPenalty;
340 if (index) initialScore += indexRouteValue;
341 return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : partialParamRe.test(segment) ? partialDynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
342}
343function compareIndexes(a, b) {
344 return a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]) ? a[a.length - 1] - b[b.length - 1] : 0;
345}
346function matchRouteBranch(branch, pathname, allowPartial = false) {
347 let { routesMeta } = branch;
348 let matchedParams = {};
349 let matchedPathname = "/";
350 let matches = [];
351 for (let i = 0; i < routesMeta.length; ++i) {
352 let meta = routesMeta[i];
353 let end = i === routesMeta.length - 1;
354 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
355 let pattern = {
356 path: meta.relativePath,
357 caseSensitive: meta.caseSensitive,
358 end
359 };
360 let match = meta.matcher && meta.compiledParams ? matchPathImpl(pattern, remainingPathname, meta.matcher, meta.compiledParams) : matchPath(pattern, remainingPathname);
361 let route = meta.route;
362 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) match = matchPath({
363 path: meta.relativePath,
364 caseSensitive: meta.caseSensitive,
365 end: false
366 }, remainingPathname);
367 if (!match) return null;
368 Object.assign(matchedParams, match.params);
369 matches.push({
370 params: matchedParams,
371 pathname: joinPaths([matchedPathname, match.pathname]),
372 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
373 route
374 });
375 if (match.pathnameBase !== "/") matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
376 }
377 return matches;
378}
379/**
380* Characters that `encodeURIComponent` escapes but that are valid literally in
381* a URL path segment. Per RFC 3986 §3.3, a path segment is made of `pchar`:
382*
383* ```
384* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
385* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
386* ```
387*
388* `encodeURIComponent` targets query-string values, where `$ & + , ; = : @`
389* are delimiters and must be escaped — but in a path segment they carry no
390* special meaning, and browsers keep them literal in `location.pathname`.
391* (`! ' ( ) *` and the unreserved set are already left alone by
392* `encodeURIComponent`, so they need no restoring.)
393*/
394const PATH_PARAM_OVERESCAPED = {
395 "%24": "$",
396 "%26": "&",
397 "%2B": "+",
398 "%2C": ",",
399 "%3A": ":",
400 "%3B": ";",
401 "%3D": "=",
402 "%40": "@"
403};
404/**
405* Encodes a param value for interpolation into a single URL path segment.
406*
407* Escapes characters that would break the path (`/ ? # %`, whitespace,
408* non-ASCII, …) while leaving characters that RFC 3986 permits literally in a
409* path segment untouched. Escaping those would needlessly rewrite URLs — e.g.
410* a semver build param `1.0.0+1` would become `1.0.0%2B1` even though browsers
411* display and match the `+` literally in `location.pathname`.
412*
413* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3))
414*
415* @param value The param value to encode.
416* @returns The encoded value, safe for use as a single path segment.
417*/
418function encodePathParam(value) {
419 return encodeURIComponent(value).replace(/%(?:24|26|2B|2C|3A|3B|3D|40)/g, (match) => PATH_PARAM_OVERESCAPED[match]);
420}
421/**
422* Returns a path with params interpolated.
423*
424* Param values are percent-encoded for use in a path segment: characters that
425* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
426* are escaped, while characters that RFC 3986 allows literally in a path
427* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
428* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
429* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
430* preserving `/` separators.
431*
432* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
433*
434* @example
435* import { generatePath } from "react-router";
436*
437* generatePath("/users/:id", { id: "123" }); // "/users/123"
438* generatePath("/files/:name", { name: "a b" }); // "/files/a%20b"
439* generatePath("/releases/:v", { v: "1.0.0+1" }); // "/releases/1.0.0+1"
440*
441* @public
442* @category Utils
443* @param originalPath The original path to generate.
444* @param params The parameters to interpolate into the path.
445* @returns The generated path with parameters interpolated.
446*/
447function generatePath(originalPath, params = {}) {
448 let path = originalPath;
449 if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
450 warning(false, `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
451 path = path.replace(/\*$/, "/*");
452 }
453 const prefix = path.startsWith("/") ? "/" : "";
454 const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
455 return prefix + path.split(/\/+/).map((segment, index, array) => {
456 if (index === array.length - 1 && segment === "*") return stringify(params["*"]);
457 const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/);
458 if (keyMatch) {
459 const [, key, optional, suffix] = keyMatch;
460 let param = params[key];
461 invariant(optional === "?" || param != null, `Missing ":${key}" param`);
462 return encodePathParam(stringify(param)) + suffix;
463 }
464 return segment.replace(/\?$/g, "");
465 }).filter((segment) => !!segment).join("/");
466}
467/**
468* Performs pattern matching on a URL pathname and returns information about
469* the match.
470*
471* @public
472* @category Utils
473* @param pattern The pattern to match against the URL pathname. This can be a
474* string or a {@link PathPattern} object. If a string is provided, it will be
475* treated as a pattern with `caseSensitive` set to `false` and `end` set to
476* `true`.
477* @param pathname The URL pathname to match against the pattern.
478* @returns A path match object if the pattern matches the pathname,
479* or `null` if it does not match.
480*/
481function matchPath(pattern, pathname) {
482 if (typeof pattern === "string") pattern = {
483 path: pattern,
484 caseSensitive: false,
485 end: true
486 };
487 let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
488 return matchPathImpl(pattern, pathname, matcher, compiledParams);
489}
490function matchPathImpl(pattern, pathname, matcher, compiledParams) {
491 let match = pathname.match(matcher);
492 if (!match) return null;
493 let matchedPathname = match[0];
494 let pathnameBase = removeTrailingSlash(matchedPathname, 1);
495 let captureGroups = match.slice(1);
496 return {
497 params: compiledParams.reduce((memo, { paramName, isOptional }, index) => {
498 if (paramName === "*") {
499 let splatValue = captureGroups[index] || "";
500 pathnameBase = removeTrailingSlash(matchedPathname.slice(0, matchedPathname.length - splatValue.length), 1);
501 }
502 const value = captureGroups[index];
503 if (isOptional && !value) memo[paramName] = void 0;
504 else memo[paramName] = (value || "").replace(/%2F/g, "/");
505 return memo;
506 }, {}),
507 pathname: matchedPathname,
508 pathnameBase,
509 pattern
510 };
511}
512function compilePath(path, caseSensitive = false, end = true) {
513 warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`);
514 let params = [];
515 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => {
516 params.push({
517 paramName,
518 isOptional: isOptional != null
519 });
520 if (isOptional) {
521 let nextChar = str.charAt(index + match.length);
522 if (nextChar && nextChar !== "/") return "/([^\\/]*)";
523 return "(?:/([^\\/]*))?";
524 }
525 return "/([^\\/]+)";
526 }).replace(/\/([\w-]+)\?(?=\/|$|\()/g, "(?:/$1)?");
527 if (path.endsWith("*")) {
528 params.push({ paramName: "*" });
529 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
530 } else if (end) regexpSource += "\\/*$";
531 else if (path !== "" && path !== "/") regexpSource += "(?:(?=\\/|$))";
532 return [new RegExp(regexpSource, caseSensitive ? void 0 : "i"), params];
533}
534function decodePath(value) {
535 try {
536 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
537 } catch (error) {
538 warning(false, `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`);
539 return value;
540 }
541}
542function stripBasename(pathname, basename) {
543 if (basename === "/") return pathname;
544 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return null;
545 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
546 let nextChar = pathname.charAt(startIndex);
547 if (nextChar && nextChar !== "/") return null;
548 return pathname.slice(startIndex) || "/";
549}
550function prependBasename({ basename, pathname }) {
551 return pathname === "/" ? basename : joinPaths([basename, pathname]);
552}
553const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
554/**
555* Returns a resolved {@link Path} object relative to the given pathname.
556*
557* @public
558* @category Utils
559* @param to The path to resolve, either a string or a partial {@link Path}
560* object.
561* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
562* @returns A {@link Path} object with the resolved pathname, search, and hash.
563*/
564function resolvePath(to, fromPathname = "/") {
565 let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to;
566 let pathname;
567 if (toPathname) {
568 toPathname = removeDoubleSlashes(toPathname);
569 if (toPathname.startsWith("/") || toPathname.startsWith("\\")) pathname = resolvePathname(toPathname.substring(1), "/");
570 else pathname = resolvePathname(toPathname, fromPathname);
571 } else pathname = fromPathname;
572 return {
573 pathname,
574 search: normalizeSearch(search),
575 hash: normalizeHash(hash)
576 };
577}
578function resolvePathname(relativePath, fromPathname) {
579 let segments = removeTrailingSlash(fromPathname).split("/");
580 relativePath.split("/").forEach((segment) => {
581 if (segment === "..") {
582 if (segments.length > 1) segments.pop();
583 } else if (segment !== ".") segments.push(segment);
584 });
585 return segments.length > 1 ? segments.join("/") : "/";
586}
587function getInvalidPathError(char, field, dest, path) {
588 return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(path)}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
589}
590function getPathContributingMatches(matches) {
591 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
592}
593function getResolveToMatches(matches) {
594 let pathMatches = getPathContributingMatches(matches);
595 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
596}
597function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
598 let to;
599 if (typeof toArg === "string") to = parsePath(toArg);
600 else {
601 to = { ...toArg };
602 invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
603 invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
604 invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
605 }
606 let isEmptyPath = toArg === "" || to.pathname === "";
607 let toPathname = isEmptyPath ? "/" : to.pathname;
608 let from;
609 if (toPathname == null) from = locationPathname;
610 else {
611 let routePathnameIndex = routePathnames.length - 1;
612 if (!isPathRelative && toPathname.startsWith("..")) {
613 let toSegments = toPathname.split("/");
614 while (toSegments[0] === "..") {
615 toSegments.shift();
616 routePathnameIndex -= 1;
617 }
618 to.pathname = toSegments.join("/");
619 }
620 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
621 }
622 let path = resolvePath(to, from);
623 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
624 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
625 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) path.pathname += "/";
626 return path;
627}
628const removeDoubleSlashes = (path) => path.replace(/[\\/]{2,}/g, "/");
629const joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
630function removeTrailingSlash(path, minLength = 0) {
631 let end = path.length;
632 while (end > minLength && path.charCodeAt(end - 1) === 47) end--;
633 return end === path.length ? path : path.slice(0, end);
634}
635const normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
636const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
637const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
638var DataWithResponseInit = class {
639 type = "DataWithResponseInit";
640 data;
641 init;
642 constructor(data, init) {
643 this.data = data;
644 this.init = init || null;
645 }
646};
647/**
648* Create "responses" that contain `headers`/`status` without forcing
649* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
650*
651* @example
652* import { data } from "react-router";
653*
654* export async function action({ request }: Route.ActionArgs) {
655* let formData = await request.formData();
656* let item = await createItem(formData);
657* return data(item, {
658* headers: { "X-Custom-Header": "value" }
659* status: 201,
660* });
661* }
662*
663* @public
664* @category Utils
665* @mode framework
666* @mode data
667* @param data The data to be included in the response.
668* @param init The status code or a `ResponseInit` object to be included in the
669* response.
670* @returns A {@link DataWithResponseInit} instance containing the data and
671* response init.
672*/
673function data(data, init) {
674 return new DataWithResponseInit(data, typeof init === "number" ? { status: init } : init);
675}
676/**
677* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
678* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
679* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
680*
681* This utility accepts absolute URLs and can navigate to external domains, so
682* the application should validate any user-supplied inputs to redirects.
683*
684* @example
685* import { redirect } from "react-router";
686*
687* export async function loader({ request }: Route.LoaderArgs) {
688* if (!isLoggedIn(request))
689* throw redirect("/login");
690* }
691*
692* // ...
693* }
694*
695* @public
696* @category Utils
697* @mode framework
698* @mode data
699* @param url The URL to redirect to.
700* @param init The status code or a `ResponseInit` object to be included in the
701* response.
702* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
703* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
704* header.
705*/
706const redirect = (url, init = 302) => {
707 let responseInit = init;
708 if (typeof responseInit === "number") responseInit = { status: responseInit };
709 else if (typeof responseInit.status === "undefined") responseInit.status = 302;
710 let headers = new Headers(responseInit.headers);
711 headers.set("Location", url);
712 return new Response(null, {
713 ...responseInit,
714 headers
715 });
716};
717/**
718* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
719* that will force a document reload to the new location. Sets the status code
720* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
721* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
722*
723* This utility accepts absolute URLs and can navigate to external domains, so
724* the application should validate any user-supplied inputs to redirects.
725*
726* ```tsx filename=routes/logout.tsx
727* import { redirectDocument } from "react-router";
728*
729* import { destroySession } from "../sessions.server";
730*
731* export async function action({ request }: Route.ActionArgs) {
732* let session = await getSession(request.headers.get("Cookie"));
733* return redirectDocument("/", {
734* headers: { "Set-Cookie": await destroySession(session) }
735* });
736* }
737* ```
738*
739* @public
740* @category Utils
741* @mode framework
742* @mode data
743* @param url The URL to redirect to.
744* @param init The status code or a `ResponseInit` object to be included in the
745* response.
746* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
747* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
748* header.
749*/
750const redirectDocument = (url, init) => {
751 let response = redirect(url, init);
752 response.headers.set("X-Remix-Reload-Document", "true");
753 return response;
754};
755/**
756* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
757* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
758* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
759* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
760* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
761*
762* @example
763* import { replace } from "react-router";
764*
765* export async function loader() {
766* return replace("/new-location");
767* }
768*
769* @public
770* @category Utils
771* @mode framework
772* @mode data
773* @param url The URL to redirect to.
774* @param init The status code or a `ResponseInit` object to be included in the
775* response.
776* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
777* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
778* header.
779*/
780const replace = (url, init) => {
781 let response = redirect(url, init);
782 response.headers.set("X-Remix-Replace", "true");
783 return response;
784};
785const SUPPORTED_ERROR_TYPES = [
786 "EvalError",
787 "RangeError",
788 "ReferenceError",
789 "SyntaxError",
790 "TypeError",
791 "URIError"
792];
793var ErrorResponseImpl = class {
794 status;
795 statusText;
796 data;
797 error;
798 internal;
799 constructor(status, statusText, data, internal = false) {
800 this.status = status;
801 this.statusText = statusText || "";
802 this.internal = internal;
803 if (data instanceof Error) {
804 this.data = data.toString();
805 this.error = data;
806 } else this.data = data;
807 }
808};
809/**
810* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
811* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
812* thrown from an [`action`](../../start/framework/route-module#action) or
813* [`loader`](../../start/framework/route-module#loader) function.
814*
815* @example
816* import { isRouteErrorResponse } from "react-router";
817*
818* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
819* if (isRouteErrorResponse(error)) {
820* return (
821* <>
822* <p>Error: `${error.status}: ${error.statusText}`</p>
823* <p>{error.data}</p>
824* </>
825* );
826* }
827*
828* return (
829* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
830* );
831* }
832*
833* @public
834* @category Utils
835* @mode framework
836* @mode data
837* @param error The error to check.
838* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
839*/
840function isRouteErrorResponse(error) {
841 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
842}
843function getRoutePattern(matches) {
844 return joinPaths(matches.map((m) => m.route.path).filter(Boolean)) || "/";
845}
846function createDataFunctionUrl(request, path) {
847 let url = new URL(typeof request === "string" || request instanceof URL ? request : request.url);
848 let parsed = typeof path === "string" ? parsePath(path) : path;
849 url.pathname = parsed.pathname || "/";
850 if (parsed.search) {
851 let searchParams = new URLSearchParams(parsed.search);
852 let indexValues = searchParams.getAll("index");
853 searchParams.delete("index");
854 for (let value of indexValues.filter(Boolean)) searchParams.append("index", value);
855 let search = searchParams.toString();
856 url.search = search ? `?${search}` : "";
857 } else url.search = "";
858 url.hash = parsed.hash || "";
859 return url;
860}
861const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
862function parseToInfo(_to, basename) {
863 let to = _to;
864 if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) return {
865 absoluteURL: void 0,
866 isExternal: false,
867 to
868 };
869 let absoluteURL = to;
870 let isExternal = false;
871 if (isBrowser) try {
872 let currentUrl = new URL(window.location.href);
873 let targetUrl = PROTOCOL_RELATIVE_URL_REGEX.test(to) ? new URL(normalizeProtocolRelativeUrl(to, currentUrl.protocol)) : new URL(to);
874 let path = stripBasename(targetUrl.pathname, basename);
875 if (targetUrl.origin === currentUrl.origin && path != null) to = path + targetUrl.search + targetUrl.hash;
876 else isExternal = true;
877 } catch {
878 warning(false, `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`);
879 }
880 return {
881 absoluteURL,
882 isExternal,
883 to
884 };
885}
886//#endregion
887export { ErrorResponseImpl, RouterContextProvider, SUPPORTED_ERROR_TYPES, compilePath, convertRouteMatchToUiMatch, convertRoutesToDataRoutes, createContext, createDataFunctionUrl, data, decodePath, defaultMapRouteProperties, encodePathParam, explodeOptionalSegments, flattenAndRankRoutes, generatePath, getPathContributingMatches, getResolveToMatches, getRoutePattern, isAbsoluteUrl, isBrowser, isRouteErrorResponse, isUnsupportedLazyRouteFunctionKey, isUnsupportedLazyRouteObjectKey, joinPaths, matchPath, matchRoutes, matchRoutesImpl, normalizePathname, parseToInfo, prependBasename, redirect, redirectDocument, removeDoubleSlashes, removeTrailingSlash, replace, resolvePath, resolveTo, stripBasename };