UNPKG

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