react-router
Version:
Declarative routing for React
1,566 lines (1,559 loc) • 102 kB
JavaScript
'use strict';
var node_async_hooks = require('node:async_hooks');
var React2 = require('react');
var setCookieParser = require('set-cookie-parser');
var reactServerClient = require('react-router/internal/react-server-client');
var cookie = require('cookie');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
/**
* react-router v7.7.0
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
var __typeError = (msg) => {
throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
// lib/router/history.ts
function invariant(value, message) {
if (value === false || value === null || typeof value === "undefined") {
throw new Error(message);
}
}
function warning(cond, message) {
if (!cond) {
if (typeof console !== "undefined") console.warn(message);
try {
throw new Error(message);
} catch (e) {
}
}
}
function createKey() {
return Math.random().toString(36).substring(2, 10);
}
function createLocation(current, to, state = null, key) {
let location = {
pathname: typeof current === "string" ? current : current.pathname,
search: "",
hash: "",
...typeof to === "string" ? parsePath(to) : to,
state,
// TODO: This could be cleaned up. push/replace should probably just take
// full Locations now and avoid the need to run through this flow at all
// But that's a pretty big refactor to the current test suite so going to
// keep as is for the time being and just let any incoming keys take precedence
key: to && to.key || key || createKey()
};
return location;
}
function createPath({
pathname = "/",
search = "",
hash = ""
}) {
if (search && search !== "?")
pathname += search.charAt(0) === "?" ? search : "?" + search;
if (hash && hash !== "#")
pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
return pathname;
}
function parsePath(path) {
let parsedPath = {};
if (path) {
let hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
parsedPath.hash = path.substring(hashIndex);
path = path.substring(0, hashIndex);
}
let searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
parsedPath.search = path.substring(searchIndex);
path = path.substring(0, searchIndex);
}
if (path) {
parsedPath.pathname = path;
}
}
return parsedPath;
}
// lib/router/utils.ts
function unstable_createContext(defaultValue) {
return { defaultValue };
}
var _map;
var unstable_RouterContextProvider = class {
constructor(init) {
__privateAdd(this, _map, /* @__PURE__ */ new Map());
if (init) {
for (let [context, value] of init) {
this.set(context, value);
}
}
}
get(context) {
if (__privateGet(this, _map).has(context)) {
return __privateGet(this, _map).get(context);
}
if (context.defaultValue !== void 0) {
return context.defaultValue;
}
throw new Error("No value found for context");
}
set(context, value) {
__privateGet(this, _map).set(context, value);
}
};
_map = new WeakMap();
var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
"lazy",
"caseSensitive",
"path",
"id",
"index",
"children"
]);
function isUnsupportedLazyRouteObjectKey(key) {
return unsupportedLazyRouteObjectKeys.has(
key
);
}
var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
"lazy",
"caseSensitive",
"path",
"id",
"index",
"unstable_middleware",
"children"
]);
function isUnsupportedLazyRouteFunctionKey(key) {
return unsupportedLazyRouteFunctionKeys.has(
key
);
}
function isIndexRoute(route) {
return route.index === true;
}
function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
return routes.map((route, index) => {
let treePath = [...parentPath, String(index)];
let id = typeof route.id === "string" ? route.id : treePath.join("-");
invariant(
route.index !== true || !route.children,
`Cannot specify children on an index route`
);
invariant(
allowInPlaceMutations || !manifest[id],
`Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
);
if (isIndexRoute(route)) {
let indexRoute = {
...route,
...mapRouteProperties(route),
id
};
manifest[id] = indexRoute;
return indexRoute;
} else {
let pathOrLayoutRoute = {
...route,
...mapRouteProperties(route),
id,
children: void 0
};
manifest[id] = pathOrLayoutRoute;
if (route.children) {
pathOrLayoutRoute.children = convertRoutesToDataRoutes(
route.children,
mapRouteProperties,
treePath,
manifest,
allowInPlaceMutations
);
}
return pathOrLayoutRoute;
}
});
}
function matchRoutes(routes, locationArg, basename = "/") {
return matchRoutesImpl(routes, locationArg, basename, false);
}
function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
let pathname = stripBasename(location.pathname || "/", basename);
if (pathname == null) {
return null;
}
let branches = flattenRoutes(routes);
rankRouteBranches(branches);
let matches = null;
for (let i = 0; matches == null && i < branches.length; ++i) {
let decoded = decodePath(pathname);
matches = matchRouteBranch(
branches[i],
decoded,
allowPartial
);
}
return matches;
}
function convertRouteMatchToUiMatch(match, loaderData) {
let { route, pathname, params } = match;
return {
id: route.id,
pathname,
params,
data: loaderData[route.id],
handle: route.handle
};
}
function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
let flattenRoute = (route, index, relativePath) => {
let meta = {
relativePath: relativePath === void 0 ? route.path || "" : relativePath,
caseSensitive: route.caseSensitive === true,
childrenIndex: index,
route
};
if (meta.relativePath.startsWith("/")) {
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.`
);
meta.relativePath = meta.relativePath.slice(parentPath.length);
}
let path = joinPaths([parentPath, meta.relativePath]);
let routesMeta = parentsMeta.concat(meta);
if (route.children && route.children.length > 0) {
invariant(
// Our types know better, but runtime JS may not!
// @ts-expect-error
route.index !== true,
`Index routes must not have child routes. Please remove all child routes from route path "${path}".`
);
flattenRoutes(route.children, branches, routesMeta, path);
}
if (route.path == null && !route.index) {
return;
}
branches.push({
path,
score: computeScore(path, route.index),
routesMeta
});
};
routes.forEach((route, index) => {
if (route.path === "" || !route.path?.includes("?")) {
flattenRoute(route, index);
} else {
for (let exploded of explodeOptionalSegments(route.path)) {
flattenRoute(route, index, exploded);
}
}
});
return branches;
}
function explodeOptionalSegments(path) {
let segments = path.split("/");
if (segments.length === 0) return [];
let [first, ...rest] = segments;
let isOptional = first.endsWith("?");
let required = first.replace(/\?$/, "");
if (rest.length === 0) {
return isOptional ? [required, ""] : [required];
}
let restExploded = explodeOptionalSegments(rest.join("/"));
let result = [];
result.push(
...restExploded.map(
(subpath) => subpath === "" ? required : [required, subpath].join("/")
)
);
if (isOptional) {
result.push(...restExploded);
}
return result.map(
(exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
);
}
function rankRouteBranches(branches) {
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)
)
);
}
var paramRe = /^:[\w-]+$/;
var dynamicSegmentValue = 3;
var indexRouteValue = 2;
var emptySegmentValue = 1;
var staticSegmentValue = 10;
var splatPenalty = -2;
var isSplat = (s) => s === "*";
function computeScore(path, index) {
let segments = path.split("/");
let initialScore = segments.length;
if (segments.some(isSplat)) {
initialScore += splatPenalty;
}
if (index) {
initialScore += indexRouteValue;
}
return segments.filter((s) => !isSplat(s)).reduce(
(score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
initialScore
);
}
function compareIndexes(a, b) {
let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
return siblings ? (
// If two routes are siblings, we should try to match the earlier sibling
// first. This allows people to have fine-grained control over the matching
// behavior by simply putting routes with identical paths in the order they
// want them tried.
a[a.length - 1] - b[b.length - 1]
) : (
// Otherwise, it doesn't really make sense to rank non-siblings by index,
// so they sort equally.
0
);
}
function matchRouteBranch(branch, pathname, allowPartial = false) {
let { routesMeta } = branch;
let matchedParams = {};
let matchedPathname = "/";
let matches = [];
for (let i = 0; i < routesMeta.length; ++i) {
let meta = routesMeta[i];
let end = i === routesMeta.length - 1;
let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
let match = matchPath(
{ path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
remainingPathname
);
let route = meta.route;
if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
match = matchPath(
{
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end: false
},
remainingPathname
);
}
if (!match) {
return null;
}
Object.assign(matchedParams, match.params);
matches.push({
// TODO: Can this as be avoided?
params: matchedParams,
pathname: joinPaths([matchedPathname, match.pathname]),
pathnameBase: normalizePathname(
joinPaths([matchedPathname, match.pathnameBase])
),
route
});
if (match.pathnameBase !== "/") {
matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
}
}
return matches;
}
function matchPath(pattern, pathname) {
if (typeof pattern === "string") {
pattern = { path: pattern, caseSensitive: false, end: true };
}
let [matcher, compiledParams] = compilePath(
pattern.path,
pattern.caseSensitive,
pattern.end
);
let match = pathname.match(matcher);
if (!match) return null;
let matchedPathname = match[0];
let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
let captureGroups = match.slice(1);
let params = compiledParams.reduce(
(memo, { paramName, isOptional }, index) => {
if (paramName === "*") {
let splatValue = captureGroups[index] || "";
pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
}
const value = captureGroups[index];
if (isOptional && !value) {
memo[paramName] = void 0;
} else {
memo[paramName] = (value || "").replace(/%2F/g, "/");
}
return memo;
},
{}
);
return {
params,
pathname: matchedPathname,
pathnameBase,
pattern
};
}
function compilePath(path, caseSensitive = false, end = true) {
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(/\*$/, "/*")}".`
);
let params = [];
let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
/\/:([\w-]+)(\?)?/g,
(_, paramName, isOptional) => {
params.push({ paramName, isOptional: isOptional != null });
return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
}
);
if (path.endsWith("*")) {
params.push({ paramName: "*" });
regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
} else if (end) {
regexpSource += "\\/*$";
} else if (path !== "" && path !== "/") {
regexpSource += "(?:(?=\\/|$))";
} else ;
let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
return [matcher, params];
}
function decodePath(value) {
try {
return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
} catch (error) {
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}).`
);
return value;
}
}
function stripBasename(pathname, basename) {
if (basename === "/") return pathname;
if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
return null;
}
let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
let nextChar = pathname.charAt(startIndex);
if (nextChar && nextChar !== "/") {
return null;
}
return pathname.slice(startIndex) || "/";
}
function prependBasename({
basename,
pathname
}) {
return pathname === "/" ? basename : joinPaths([basename, pathname]);
}
function resolvePath(to, fromPathname = "/") {
let {
pathname: toPathname,
search = "",
hash = ""
} = typeof to === "string" ? parsePath(to) : to;
let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
return {
pathname,
search: normalizeSearch(search),
hash: normalizeHash(hash)
};
}
function resolvePathname(relativePath, fromPathname) {
let segments = fromPathname.replace(/\/+$/, "").split("/");
let relativeSegments = relativePath.split("/");
relativeSegments.forEach((segment) => {
if (segment === "..") {
if (segments.length > 1) segments.pop();
} else if (segment !== ".") {
segments.push(segment);
}
});
return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
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.`;
}
function getPathContributingMatches(matches) {
return matches.filter(
(match, index) => index === 0 || match.route.path && match.route.path.length > 0
);
}
function getResolveToMatches(matches) {
let pathMatches = getPathContributingMatches(matches);
return pathMatches.map(
(match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
);
}
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
let to;
if (typeof toArg === "string") {
to = parsePath(toArg);
} else {
to = { ...toArg };
invariant(
!to.pathname || !to.pathname.includes("?"),
getInvalidPathError("?", "pathname", "search", to)
);
invariant(
!to.pathname || !to.pathname.includes("#"),
getInvalidPathError("#", "pathname", "hash", to)
);
invariant(
!to.search || !to.search.includes("#"),
getInvalidPathError("#", "search", "hash", to)
);
}
let isEmptyPath = toArg === "" || to.pathname === "";
let toPathname = isEmptyPath ? "/" : to.pathname;
let from;
if (toPathname == null) {
from = locationPathname;
} else {
let routePathnameIndex = routePathnames.length - 1;
if (!isPathRelative && toPathname.startsWith("..")) {
let toSegments = toPathname.split("/");
while (toSegments[0] === "..") {
toSegments.shift();
routePathnameIndex -= 1;
}
to.pathname = toSegments.join("/");
}
from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
}
let path = resolvePath(to, from);
let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
path.pathname += "/";
}
return path;
}
var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
var DataWithResponseInit = class {
constructor(data2, init) {
this.type = "DataWithResponseInit";
this.data = data2;
this.init = init || null;
}
};
function data(data2, init) {
return new DataWithResponseInit(
data2,
typeof init === "number" ? { status: init } : init
);
}
var redirect = (url, init = 302) => {
let responseInit = init;
if (typeof responseInit === "number") {
responseInit = { status: responseInit };
} else if (typeof responseInit.status === "undefined") {
responseInit.status = 302;
}
let headers = new Headers(responseInit.headers);
headers.set("Location", url);
return new Response(null, { ...responseInit, headers });
};
var redirectDocument = (url, init) => {
let response = redirect(url, init);
response.headers.set("X-Remix-Reload-Document", "true");
return response;
};
var replace = (url, init) => {
let response = redirect(url, init);
response.headers.set("X-Remix-Replace", "true");
return response;
};
var ErrorResponseImpl = class {
constructor(status, statusText, data2, internal = false) {
this.status = status;
this.statusText = statusText || "";
this.internal = internal;
if (data2 instanceof Error) {
this.data = data2.toString();
this.error = data2;
} else {
this.data = data2;
}
}
};
function isRouteErrorResponse(error) {
return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
}
// lib/router/router.ts
var validMutationMethodsArr = [
"POST",
"PUT",
"PATCH",
"DELETE"
];
var validMutationMethods = new Set(
validMutationMethodsArr
);
var validRequestMethodsArr = [
"GET",
...validMutationMethodsArr
];
var validRequestMethods = new Set(validRequestMethodsArr);
var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
var defaultMapRouteProperties = (route) => ({
hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
function createStaticHandler(routes, opts) {
invariant(
routes.length > 0,
"You must provide a non-empty routes array to createStaticHandler"
);
let manifest = {};
let basename = (opts ? opts.basename : null) || "/";
let mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
let dataRoutes = convertRoutesToDataRoutes(
routes,
mapRouteProperties,
void 0,
manifest
);
async function query(request, {
requestContext,
filterMatchesToLoad,
skipLoaderErrorBubbling,
skipRevalidation,
dataStrategy,
unstable_stream: stream,
unstable_respond: respond
} = {}) {
let url = new URL(request.url);
let method = request.method;
let location = createLocation("", createPath(url), null, "default");
let matches = matchRoutes(dataRoutes, location, basename);
requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
let respondOrStreamStaticContext = (ctx) => {
return stream ? stream(
requestContext,
() => Promise.resolve(ctx)
) : respond ? respond(ctx) : ctx;
};
if (!isValidMethod(method) && method !== "HEAD") {
let error = getInternalRouterError(405, { method });
let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
let staticContext = {
basename,
location,
matches: methodNotAllowedMatches,
loaderData: {},
actionData: null,
errors: {
[route.id]: error
},
statusCode: error.status,
loaderHeaders: {},
actionHeaders: {}
};
return respondOrStreamStaticContext(staticContext);
} else if (!matches) {
let error = getInternalRouterError(404, { pathname: location.pathname });
let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
let staticContext = {
basename,
location,
matches: notFoundMatches,
loaderData: {},
actionData: null,
errors: {
[route.id]: error
},
statusCode: error.status,
loaderHeaders: {},
actionHeaders: {}
};
return respondOrStreamStaticContext(staticContext);
}
if (stream || respond && matches.some(
(m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
)) {
invariant(
requestContext instanceof unstable_RouterContextProvider,
"When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
);
try {
await loadLazyMiddlewareForMatches(
matches,
manifest,
mapRouteProperties
);
let renderedStaticContext;
let response = await runMiddlewarePipeline(
{
request,
matches,
params: matches[0].params,
// If we're calling middleware then it must be enabled so we can cast
// this to the proper type knowing it's not an `AppLoadContext`
context: requestContext
},
true,
async () => {
if (stream) {
let res2 = await stream(
requestContext,
async (revalidationRequest) => {
let result3 = await queryImpl(
revalidationRequest,
location,
matches,
requestContext,
dataStrategy || null,
skipLoaderErrorBubbling === true,
null,
filterMatchesToLoad || null,
skipRevalidation === true
);
return isResponse(result3) ? result3 : { location, basename, ...result3 };
}
);
return res2;
}
invariant(respond, "Expected respond to be defined");
let result2 = await queryImpl(
request,
location,
matches,
requestContext,
dataStrategy || null,
skipLoaderErrorBubbling === true,
null,
filterMatchesToLoad || null,
skipRevalidation === true
);
if (isResponse(result2)) {
return result2;
}
renderedStaticContext = { location, basename, ...result2 };
let res = await respond(renderedStaticContext);
return res;
},
async (error, routeId) => {
if (isResponse(error)) {
return error;
}
if (renderedStaticContext) {
if (routeId in renderedStaticContext.loaderData) {
renderedStaticContext.loaderData[routeId] = void 0;
}
let staticContext = getStaticContextFromError(
dataRoutes,
renderedStaticContext,
error,
skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
);
return respondOrStreamStaticContext(staticContext);
} else {
let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
matches,
matches.find(
(m) => m.route.id === routeId || m.route.loader
)?.route.id || routeId
).route.id;
let staticContext = {
matches,
location,
basename,
loaderData: {},
actionData: null,
errors: {
[boundaryRouteId]: error
},
statusCode: isRouteErrorResponse(error) ? error.status : 500,
actionHeaders: {},
loaderHeaders: {}
};
return respondOrStreamStaticContext(staticContext);
}
}
);
invariant(isResponse(response), "Expected a response in query()");
return response;
} catch (e) {
if (isResponse(e)) {
return e;
}
throw e;
}
}
let result = await queryImpl(
request,
location,
matches,
requestContext,
dataStrategy || null,
skipLoaderErrorBubbling === true,
null,
filterMatchesToLoad || null,
skipRevalidation === true
);
if (isResponse(result)) {
return result;
}
return { location, basename, ...result };
}
async function queryRoute(request, {
routeId,
requestContext,
dataStrategy,
unstable_respond: respond
} = {}) {
let url = new URL(request.url);
let method = request.method;
let location = createLocation("", createPath(url), null, "default");
let matches = matchRoutes(dataRoutes, location, basename);
requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
throw getInternalRouterError(405, { method });
} else if (!matches) {
throw getInternalRouterError(404, { pathname: location.pathname });
}
let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
if (routeId && !match) {
throw getInternalRouterError(403, {
pathname: location.pathname,
routeId
});
} else if (!match) {
throw getInternalRouterError(404, { pathname: location.pathname });
}
if (respond && matches.some(
(m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
)) {
invariant(
requestContext instanceof unstable_RouterContextProvider,
"When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
);
await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
let response = await runMiddlewarePipeline(
{
request,
matches,
params: matches[0].params,
// If we're calling middleware then it must be enabled so we can cast
// this to the proper type knowing it's not an `AppLoadContext`
context: requestContext
},
true,
async () => {
let result2 = await queryImpl(
request,
location,
matches,
requestContext,
dataStrategy || null,
false,
match,
null,
false
);
if (isResponse(result2)) {
return respond(result2);
}
let error2 = result2.errors ? Object.values(result2.errors)[0] : void 0;
if (error2 !== void 0) {
throw error2;
}
let value = result2.actionData ? Object.values(result2.actionData)[0] : Object.values(result2.loaderData)[0];
return typeof value === "string" ? new Response(value) : Response.json(value);
},
(error2) => {
if (isResponse(error2)) {
return respond(error2);
}
return new Response(String(error2), {
status: 500,
statusText: "Unexpected Server Error"
});
}
);
return response;
}
let result = await queryImpl(
request,
location,
matches,
requestContext,
dataStrategy || null,
false,
match,
null,
false
);
if (isResponse(result)) {
return result;
}
let error = result.errors ? Object.values(result.errors)[0] : void 0;
if (error !== void 0) {
throw error;
}
if (result.actionData) {
return Object.values(result.actionData)[0];
}
if (result.loaderData) {
return Object.values(result.loaderData)[0];
}
return void 0;
}
async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
invariant(
request.signal,
"query()/queryRoute() requests must contain an AbortController signal"
);
try {
if (isMutationMethod(request.method)) {
let result2 = await submit(
request,
matches,
routeMatch || getTargetMatch(matches, location),
requestContext,
dataStrategy,
skipLoaderErrorBubbling,
routeMatch != null,
filterMatchesToLoad,
skipRevalidation
);
return result2;
}
let result = await loadRouteData(
request,
matches,
requestContext,
dataStrategy,
skipLoaderErrorBubbling,
routeMatch,
filterMatchesToLoad
);
return isResponse(result) ? result : {
...result,
actionData: null,
actionHeaders: {}
};
} catch (e) {
if (isDataStrategyResult(e) && isResponse(e.result)) {
if (e.type === "error" /* error */) {
throw e.result;
}
return e.result;
}
if (isRedirectResponse(e)) {
return e;
}
throw e;
}
}
async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
let result;
if (!actionMatch.route.action && !actionMatch.route.lazy) {
let error = getInternalRouterError(405, {
method: request.method,
pathname: new URL(request.url).pathname,
routeId: actionMatch.route.id
});
if (isRouteRequest) {
throw error;
}
result = {
type: "error" /* error */,
error
};
} else {
let dsMatches = getTargetedDataStrategyMatches(
mapRouteProperties,
manifest,
request,
matches,
actionMatch,
[],
requestContext
);
let results = await callDataStrategy(
request,
dsMatches,
isRouteRequest,
requestContext,
dataStrategy
);
result = results[actionMatch.route.id];
if (request.signal.aborted) {
throwStaticHandlerAbortedError(request, isRouteRequest);
}
}
if (isRedirectResult(result)) {
throw new Response(null, {
status: result.response.status,
headers: {
Location: result.response.headers.get("Location")
}
});
}
if (isRouteRequest) {
if (isErrorResult(result)) {
throw result.error;
}
return {
matches: [actionMatch],
loaderData: {},
actionData: { [actionMatch.route.id]: result.data },
errors: null,
// Note: statusCode + headers are unused here since queryRoute will
// return the raw Response or value
statusCode: 200,
loaderHeaders: {},
actionHeaders: {}
};
}
if (skipRevalidation) {
if (isErrorResult(result)) {
let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
return {
statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
actionData: null,
actionHeaders: {
...result.headers ? { [actionMatch.route.id]: result.headers } : {}
},
matches,
loaderData: {},
errors: {
[boundaryMatch.route.id]: result.error
},
loaderHeaders: {}
};
} else {
return {
actionData: {
[actionMatch.route.id]: result.data
},
actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
matches,
loaderData: {},
errors: null,
statusCode: result.statusCode || 200,
loaderHeaders: {}
};
}
}
let loaderRequest = new Request(request.url, {
headers: request.headers,
redirect: request.redirect,
signal: request.signal
});
if (isErrorResult(result)) {
let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
let handlerContext2 = await loadRouteData(
loaderRequest,
matches,
requestContext,
dataStrategy,
skipLoaderErrorBubbling,
null,
filterMatchesToLoad,
[boundaryMatch.route.id, result]
);
return {
...handlerContext2,
statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
actionData: null,
actionHeaders: {
...result.headers ? { [actionMatch.route.id]: result.headers } : {}
}
};
}
let handlerContext = await loadRouteData(
loaderRequest,
matches,
requestContext,
dataStrategy,
skipLoaderErrorBubbling,
null,
filterMatchesToLoad
);
return {
...handlerContext,
actionData: {
[actionMatch.route.id]: result.data
},
// action status codes take precedence over loader status codes
...result.statusCode ? { statusCode: result.statusCode } : {},
actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
};
}
async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
let isRouteRequest = routeMatch != null;
if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
throw getInternalRouterError(400, {
method: request.method,
pathname: new URL(request.url).pathname,
routeId: routeMatch?.route.id
});
}
let dsMatches;
if (routeMatch) {
dsMatches = getTargetedDataStrategyMatches(
mapRouteProperties,
manifest,
request,
matches,
routeMatch,
[],
requestContext
);
} else {
let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
// Up to but not including the boundary
matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
) : void 0;
dsMatches = matches.map((match, index) => {
if (maxIdx != null && index > maxIdx) {
return getDataStrategyMatch(
mapRouteProperties,
manifest,
request,
match,
[],
requestContext,
false
);
}
return getDataStrategyMatch(
mapRouteProperties,
manifest,
request,
match,
[],
requestContext,
(match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
);
});
}
if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
return {
matches,
loaderData: {},
errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
[pendingActionResult[0]]: pendingActionResult[1].error
} : null,
statusCode: 200,
loaderHeaders: {}
};
}
let results = await callDataStrategy(
request,
dsMatches,
isRouteRequest,
requestContext,
dataStrategy
);
if (request.signal.aborted) {
throwStaticHandlerAbortedError(request, isRouteRequest);
}
let handlerContext = processRouteLoaderData(
matches,
results,
pendingActionResult,
true,
skipLoaderErrorBubbling
);
return {
...handlerContext,
matches
};
}
async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
let results = await callDataStrategyImpl(
dataStrategy || defaultDataStrategy,
request,
matches,
null,
requestContext);
let dataResults = {};
await Promise.all(
matches.map(async (match) => {
if (!(match.route.id in results)) {
return;
}
let result = results[match.route.id];
if (isRedirectDataStrategyResult(result)) {
let response = result.result;
throw normalizeRelativeRoutingRedirectResponse(
response,
request,
match.route.id,
matches,
basename
);
}
if (isResponse(result.result) && isRouteRequest) {
throw result;
}
dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
})
);
return dataResults;
}
return {
dataRoutes,
query,
queryRoute
};
}
function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
return {
...handlerContext,
statusCode: isRouteErrorResponse(error) ? error.status : 500,
errors: {
[errorBoundaryId]: error
}
};
}
function throwStaticHandlerAbortedError(request, isRouteRequest) {
if (request.signal.reason !== void 0) {
throw request.signal.reason;
}
let method = isRouteRequest ? "queryRoute" : "query";
throw new Error(
`${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
);
}
function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
let contextualMatches;
let activeRouteMatch;
{
contextualMatches = matches;
activeRouteMatch = matches[matches.length - 1];
}
let path = resolveTo(
to ? to : ".",
getResolveToMatches(contextualMatches),
stripBasename(location.pathname, basename) || location.pathname,
relative === "path"
);
if (to == null) {
path.search = location.search;
path.hash = location.hash;
}
if ((to == null || to === "" || to === ".") && activeRouteMatch) {
let nakedIndex = hasNakedIndexQuery(path.search);
if (activeRouteMatch.route.index && !nakedIndex) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
} else if (!activeRouteMatch.route.index && nakedIndex) {
let params = new URLSearchParams(path.search);
let indexValues = params.getAll("index");
params.delete("index");
indexValues.filter((v) => v).forEach((v) => params.append("index", v));
let qs = params.toString();
path.search = qs ? `?${qs}` : "";
}
}
if (basename !== "/") {
path.pathname = prependBasename({ basename, pathname: path.pathname });
}
return createPath(path);
}
function shouldRevalidateLoader(loaderMatch, arg) {
if (loaderMatch.route.shouldRevalidate) {
let routeChoice = loaderMatch.route.shouldRevalidate(arg);
if (typeof routeChoice === "boolean") {
return routeChoice;
}
}
return arg.defaultShouldRevalidate;
}
var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
var loadLazyRouteProperty = ({
key,
route,
manifest,
mapRouteProperties
}) => {
let routeToUpdate = manifest[route.id];
invariant(routeToUpdate, "No route found in manifest");
if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
return;
}
let lazyFn = routeToUpdate.lazy[key];
if (!lazyFn) {
return;
}
let cache = lazyRoutePropertyCache.get(routeToUpdate);
if (!cache) {
cache = {};
lazyRoutePropertyCache.set(routeToUpdate, cache);
}
let cachedPromise = cache[key];
if (cachedPromise) {
return cachedPromise;
}
let propertyPromise = (async () => {
let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
let staticRouteValue = routeToUpdate[key];
let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
if (isUnsupported) {
warning(
!isUnsupported,
"Route property " + key + " is not a supported lazy route property. This property will be ignored."
);
cache[key] = Promise.resolve();
} else if (isStaticallyDefined) {
warning(
false,
`Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
);
} else {
let value = await lazyFn();
if (value != null) {
Object.assign(routeToUpdate, { [key]: value });
Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
}
}
if (typeof routeToUpdate.lazy === "object") {
routeToUpdate.lazy[key] = void 0;
if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
routeToUpdate.lazy = void 0;
}
}
})();
cache[key] = propertyPromise;
return propertyPromise;
};
var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
let routeToUpdate = manifest[route.id];
invariant(routeToUpdate, "No route found in manifest");
if (!route.lazy) {
return {
lazyRoutePromise: void 0,
lazyHandlerPromise: void 0
};
}
if (typeof route.lazy === "function") {
let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
if (cachedPromise) {
return {
lazyRoutePromise: cachedPromise,
lazyHandlerPromise: cachedPromise
};
}
let lazyRoutePromise2 = (async () => {
invariant(
typeof route.lazy === "function",
"No lazy route function found"
);
let lazyRoute = await route.lazy();
let routeUpdates = {};
for (let lazyRouteProperty in lazyRoute) {
let lazyValue = lazyRoute[lazyRouteProperty];
if (lazyValue === void 0) {
continue;
}
let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
let staticRouteValue = routeToUpdate[lazyRouteProperty];
let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
// on the route updates
lazyRouteProperty !== "hasErrorBoundary";
if (isUnsupported) {
warning(
!isUnsupported,
"Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
);
} else if (isStaticallyDefined) {
warning(
!isStaticallyDefined,
`Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
);
} else {
routeUpdates[lazyRouteProperty] = lazyValue;
}
}
Object.assign(routeToUpdate, routeUpdates);
Object.assign(routeToUpdate, {
// To keep things framework agnostic, we use the provided `mapRouteProperties`
// function to set the framework-aware properties (`element`/`hasErrorBoundary`)
// since the logic will differ between frameworks.
...mapRouteProperties(routeToUpdate),
lazy: void 0
});
})();
lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
lazyRoutePromise2.catch(() => {
});
return {
lazyRoutePromise: lazyRoutePromise2,
lazyHandlerPromise: lazyRoutePromise2
};
}
let lazyKeys = Object.keys(route.lazy);
let lazyPropertyPromises = [];
let lazyHandlerPromise = void 0;
for (let key of lazyKeys) {
if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
continue;
}
let promise = loadLazyRouteProperty({
key,
route,
manifest,
mapRouteProperties
});
if (promise) {
lazyPropertyPromises.push(promise);
if (key === type) {
lazyHandlerPromise = promise;
}
}
}
let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
}) : void 0;
lazyRoutePromise?.catch(() => {
});
lazyHandlerPromise?.catch(() => {
});
return {
lazyRoutePromise,
lazyHandlerPromise
};
}
function isNonNullable(value) {
return value !== void 0;
}
function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
let promises = matches.map(({ route }) => {
if (typeof route.lazy !== "object" || !route.lazy.unstable_middleware) {
return void 0;
}
return loadLazyRouteProperty({
key: "unstable_middleware",
route,
manifest,
mapRouteProperties
});
}).filter(isNonNullable);
return promises.length > 0 ? Promise.all(promises) : void 0;
}
async function defaultDataStrategy(args) {
let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
let keyedResults = {};
let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
results.forEach((result, i) => {
keyedResults[matchesToLoad[i].route.id] = result;
});
return keyedResults;
}
async function runMiddlewarePipeline(args, propagateResult, handler, errorHandler) {
let { matches, request, params, context } = args;
let middlewareState = {
handlerResult: void 0
};
try {
let tuples = matches.flatMap(
(m) => m.route.unstable_middleware ? m.route.unstable_middleware.map((fn) => [m.route.id, fn]) : []
);
let result = await callRouteMiddleware(
{ request, params, context },
tuples,
propagateResult,
middlewareState,
handler
);
return propagateResult ? result : middlewareState.handlerResult;
} catch (e) {
if (!middlewareState.middlewareError) {
throw e;
}
let result = await errorHandler(
middlewareState.middlewareError.error,
middlewareState.middlewareError.routeId
);
{
return result;
}
}
}
async function callRouteMiddleware(args, middlewares, propagateResult, middlewareState, handler, idx = 0) {
let { request } = args;
if (request.signal.aborted) {
if (request.signal.reason) {
throw request.signal.reason;
}
throw new Error(
`Request aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
);
}
let tuple = middlewares[idx];
if (!tuple) {
middlewareState.handlerResult = await handler();
return middlewareState.handlerResult;
}
let [routeId, middleware] = tuple;
let nextCalled = false;
let nextResult = void 0;
let next = async () => {
if (nextCalled) {
throw new Error("You may only call `next()` once per middleware");
}
nextCalled = true;
let result = await callRouteMiddleware(
args,
middlewares,
propagateResult,
middlewareState,
handler,
idx + 1
);
{
nextResult = result;
return nextResult;
}
};
try {
let result = await middleware(
{
request: args.request,
params: args.params,
context: args.context
},
n