INDIE UNPKG

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