UNPKG

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