You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Scripted/website/node_modules/.cache/babel-loader/1afe0c4e90908913cf01f0de744...

1 line
325 KiB

{"ast":null,"code":"/**\n * @remix-run/router v1.0.2\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (Action) {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Action[\"Pop\"] = \"POP\";\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n\n Action[\"Push\"] = \"PUSH\";\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nconst PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\n\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n let {\n initialEntries = [\"/\"],\n initialIndex,\n v5Compat = false\n } = options;\n let entries; // Declare so we can access from createMemoryLocation\n\n entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning$1(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n index = clampIndex(index + delta);\n if (listener) {\n listener({\n action,\n location: getCurrentLocation()\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\n\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\n\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning$1(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\nfunction warning$1(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\n\nfunction getHistoryState(location) {\n return {\n usr: location.state,\n key: location.key\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\n\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\n\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\n\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n function handlePop() {\n action = Action.Pop;\n if (listener) {\n listener({\n action,\n location: history.location\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n let historyState = getHistoryState(location);\n let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/\n\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n let historyState = getHistoryState(location);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: location\n });\n }\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n} //#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nfunction isIndexRoute(route) {\n return route.index === true;\n} // Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\n\nfunction convertRoutesToDataRoutes(routes, parentPath, allIds) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (allIds === void 0) {\n allIds = new Set();\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!allIds.has(id), \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n allIds.add(id);\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, {\n id\n });\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, {\n id,\n children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined\n });\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/match-routes\n */\n\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(branches[i], pathname);\n }\n return matches;\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n routes.forEach((route, index) => {\n let meta = {\n relativePath: route.path || \"\",\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n 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.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n } // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n });\n return branches;\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname) {\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n if (!match) return null;\n Object.assign(matchedParams, match.params);\n let route = meta.route;\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/generate-path\n */\n\nfunction generatePath(path, params) {\n if (params === void 0) {\n params = {};\n }\n return path.replace(/:(\\w+)/g, (_, key) => {\n invariant(params[key] != null, \"Missing \\\":\" + key + \"\\\" param\");\n return params[key];\n }).replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n const star = \"*\";\n if (params[star] == null) {\n // If no splat was provided, trim the trailing slash _unless_ it's\n // the entire path\n return str === \"/*\" ? \"/\" : \"\";\n } // Apply the splat\n\n return \"\" + prefix + params[star];\n });\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/match-path\n */\n\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = paramNames.reduce((memo, paramName, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || \"\", paramName);\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n 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(/\\*$/, \"/*\") + \"\\\".\"));\n let paramNames = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/:(\\w+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return \"([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, paramNames];\n}\nfunction safelyDecodeURIComponent(value, paramName) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(false, \"The value for the URL param \\\"\" + paramName + \"\\\" will not be decoded because\" + (\" the string \\\"\" + value + \"\\\" is a malformed URL segment. This is probably\") + (\" due to a bad percent encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\n\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n } // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n/**\n * @private\n */\n\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging React Router!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/resolve-path\n */\n\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n 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.\";\n}\n/**\n * @private\n */\n\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from; // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\"); // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how <a href> works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n } // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original \"to\" had one\n\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\"); // Or if this was a link to the current path which has a trailing slash\n\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\n\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\n\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\n\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\n\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\n\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\n\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data) {\n this.pendingKeys = new Set();\n this.subscriber = undefined;\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\"); // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref) => {\n let [key, value] = _ref;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.pendingKeys.add(key); // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeys.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n const subscriber = this.subscriber;\n if (error) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n subscriber && subscriber(false);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n subscriber && subscriber(false);\n return data;\n }\n subscribe(fn) {\n this.subscriber = fn;\n }\n cancel() {\n this.controller.abort();\n this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n let subscriber = this.subscriber;\n subscriber && subscriber(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeys.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\nfunction defer(data) {\n return new DeferredData(data);\n}\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\n\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\n\nclass ErrorResponse {\n constructor(status, statusText, data) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.data = data;\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\n\nfunction isRouteErrorResponse(e) {\n return e instanceof ErrorResponse;\n}\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n}; //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\n\nfunction createRouter(init) {\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history\n\n let unlistenHistory = null; // Externally-provided functions to call on all state changes\n\n let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing\n\n let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys\n\n let getScrollRestorationKey = null; // Externally-provided function to get current scroll position\n\n let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n\n let initialScrollRestored = false;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);\n let initialErrors = null;\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let {\n matches,\n route,\n error\n } = getNotFoundMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n restoreScrollPosition: null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map()\n }; // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n\n let pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n\n let pendingPreventScrollReset = false; // AbortController for the active navigation\n\n let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n\n let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidate()\n // - X-Remix-Revalidate (from redirect)\n\n let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n\n let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n\n let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers\n\n let fetchControllers = new Map(); // Track loads based on the order in which they started\n\n let incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n\n let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions\n\n let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions\n\n let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers\n\n let fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n\n let activeDeferreds = new Map(); // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location\n } = _ref;\n return startNavigation(historyAction, location);\n }); // Kick off initial data load if needed. Use Pop to avoid modifying history\n\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location);\n }\n return router;\n } // Clean up a router and it's side effects\n\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n } // Subscribe to state updates for the router\n\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n } // Update our state and notify the calling context of the change\n\n function updateState(newState) {\n state = _extends({}, state, newState);\n subscribers.forEach(subscriber => subscriber(state));\n } // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n\n function completeNavigation(location, newState) {\n var _state$navigation$for;\n\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a submission\n // - We're past the submitting state and into the loading state\n // - The location we've finished loading is different from the submission\n // location, indicating we redirected from the action (avoids false\n // positives for loading/submissionRedirect when actionData returned\n // on a prior submission)\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && state.navigation.state === \"loading\" && ((_state$navigation$for = state.navigation.formAction) == null ? void 0 : _state$navigation$for.split(\"?\")[0]) === location.pathname; // Always preserve any existing loaderData from re-used routes\n\n let newLoaderData = newState.loaderData ? {\n loaderData: mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [])\n } : {};\n updateState(_extends({}, isActionReload ? {} : {\n actionData: null\n }, newState, newLoaderData, {\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n // Don't restore on submission navigations\n restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset: pendingPreventScrollReset\n }));\n if (isUninterruptedRevalidation) ;else if (pendingAction === Action.Pop) ;else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n } // Reset stateful navigation vars\n\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n } // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(to, opts);\n let location = createLocation(state.location, path, opts && opts.state);\n let historyAction = (opts && opts.replace) === true || submission != null ? Action.Replace : Action.Push;\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n return await startNavigation(historyAction, location, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace\n });\n } // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n }); // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n\n if (state.navigation.state === \"submitting\") {\n return;\n } // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n } // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation\n });\n } // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing\n\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error\n } = getNotFoundMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes\n\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n });\n return;\n } // Short circuit if it's only a hash change\n\n if (isHashChangeOnly(state.location, location)) {\n completeNavigation(location, {\n matches\n });\n return;\n } // Create a controller/Request for this navigation\n\n pendingNavigationController = new AbortController();\n let request = createRequest(location, pendingNavigationController.signal, opts && opts.submission);\n let pendingActionData;\n let pendingError;\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError\n };\n } else if (opts && opts.submission) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(request, location, opts.submission, matches, {\n replace: opts.replace\n });\n if (actionOutput.shortCircuited) {\n return;\n }\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n let navigation = _extends({\n state: \"loading\",\n location\n }, opts.submission);\n loadingNavigation = navigation;\n } // Call loaders\n\n let {\n shortCircuited,\n loaderData,\n errors\n } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);\n if (shortCircuited) {\n return;\n } // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n\n pendingNavigationController = null;\n completeNavigation(location, {\n matches,\n loaderData,\n errors\n });\n } // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n\n async function handleAction(request, location, submission, matches, opts) {\n interruptActiveLoads(); // Put us in a submitting state\n\n let navigation = _extends({\n state: \"submitting\",\n location\n }, submission);\n updateState({\n navigation\n }); // Call our action and get the result\n\n let result;\n let actionMatch = getTargetMatch(matches, location);\n if (!actionMatch.route.action) {\n result = getMethodNotAllowedResult(location);\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch);\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n }\n if (isRedirectResult(result)) {\n let redirectNavigation = _extends({\n state: \"loading\",\n location: createLocation(state.location, result.location)\n }, submission);\n await startRedirectNavigation(result, redirectNavigation, opts && opts.replace);\n return {\n shortCircuited: true\n };\n }\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n\n if ((opts && opts.replace) !== true) {\n pendingAction = Action.Push;\n }\n return {\n pendingActionError: {\n [boundaryMatch.route.id]: result.error\n }\n };\n }\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n return {\n pendingActionData: {\n [actionMatch.route.id]: result.data\n }\n };\n } // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n\n async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n if (!loadingNavigation) {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n loadingNavigation = navigation;\n }\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n\n cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run\n\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n completeNavigation(location, {\n matches,\n loaderData: mergeLoaderData(state.loaderData, {}, matches),\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n actionData: pendingActionData || null\n });\n return {\n shortCircuited: true\n };\n } // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach(_ref2 => {\n let [key] = _ref2;\n const fetcher = state.fetchers.get(key);\n let revalidatingFetcher = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(key, revalidatingFetcher);\n });\n updateState(_extends({\n navigation: loadingNavigation,\n actionData: pendingActionData || state.actionData || null\n }, revalidatingFetchers.length > 0 ? {\n fetchers: new Map(state.fetchers)\n } : {}));\n }\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach(_ref3 => {\n let [key] = _ref3;\n return fetchControllers.set(key, pendingNavigationController);\n });\n let {\n results,\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, request);\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n } // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n\n revalidatingFetchers.forEach(_ref4 => {\n let [key] = _ref4;\n return fetchControllers.delete(key);\n }); // If any loaders returned a redirect Response, start a new REPLACE navigation\n\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation, replace);\n return {\n shortCircuited: true\n };\n } // Process and commit output from loaders\n\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle\n\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe(aborted => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n return _extends({\n loaderData,\n errors\n }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {\n fetchers: new Map(state.fetchers)\n } : {});\n }\n function getFetcher(key) {\n return state.fetchers.get(key) || IDLE_FETCHER;\n } // Trigger a fetcher load/submit for the given fetcher key\n\n function fetch(key, routeId, href, opts) {\n if (typeof AbortController === \"undefined\") {\n throw new Error(\"router.fetch() was called during the server render, but it shouldn't be. \" + \"You are likely calling a useFetcher() method in the body of your component. \" + \"Try moving it to a useEffect or a callback.\");\n }\n if (fetchControllers.has(key)) abortFetcher(key);\n let matches = matchRoutes(dataRoutes, href, init.basename);\n if (!matches) {\n setFetcherError(key, routeId, new ErrorResponse(404, \"Not Found\", null));\n return;\n }\n let {\n path,\n submission\n } = normalizeNavigateOptions(href, opts, true);\n let match = getTargetMatch(matches, path);\n if (submission) {\n handleFetcherAction(key, routeId, path, match, submission);\n return;\n } // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n\n fetchLoadMatches.set(key, [path, match]);\n handleFetcherLoader(key, routeId, path, match);\n } // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n\n async function handleFetcherAction(key, routeId, path, match, submission) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n if (!match.route.action) {\n let {\n error\n } = getMethodNotAllowedResult(path);\n setFetcherError(key, routeId, error);\n return;\n } // Put this fetcher into it's submitting state\n\n let existingFetcher = state.fetchers.get(key);\n let fetcher = _extends({\n state: \"submitting\"\n }, submission, {\n data: existingFetcher && existingFetcher.data\n });\n state.fetchers.set(key, fetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }); // Call the action for the fetcher\n\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal, submission);\n fetchControllers.set(key, abortController);\n let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match);\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n let loadingFetcher = _extends({\n state: \"loading\"\n }, submission, {\n data: undefined\n });\n state.fetchers.set(key, loadingFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let redirectNavigation = _extends({\n state: \"loading\",\n location: createLocation(state.location, actionResult.location)\n }, submission);\n await startRedirectNavigation(actionResult, redirectNavigation);\n return;\n } // Process any non-redirect errors thrown\n\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n if (isDeferredResult(actionResult)) {\n invariant(false, \"defer() is not supported in actions\");\n } // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createRequest(nextLocation, abortController.signal);\n let matches = state.navigation.state !== \"idle\" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;\n invariant(matches, \"Didn't find any matches after fetcher action\");\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n let loadFetcher = _extends({\n state: \"loading\",\n data: actionResult.data\n }, submission);\n state.fetchers.set(key, loadFetcher);\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {\n [match.route.id]: actionResult.data\n }, undefined,\n // No need to send through errors since we short circuit above\n fetchLoadMatches); // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n\n revalidatingFetchers.filter(_ref5 => {\n let [staleKey] = _ref5;\n return staleKey !== key;\n }).forEach(_ref6 => {\n let [staleKey] = _ref6;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n fetchControllers.set(staleKey, abortController);\n });\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let {\n results,\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n if (abortController.signal.aborted) {\n return;\n }\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(_ref7 => {\n let [staleKey] = _ref7;\n return fetchControllers.delete(staleKey);\n });\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation);\n return;\n } // Process and commit output from loaders\n\n let {\n loaderData,\n errors\n } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n let doneFetcher = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(key, doneFetcher);\n let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n\n if (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers)\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState(_extends({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches)\n }, didAbortFetchLoads ? {\n fetchers: new Map(state.fetchers)\n } : {}));\n isRevalidationRequired = false;\n }\n } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n\n async function handleFetcherLoader(key, routeId, path, match) {\n let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state\n\n let loadingFetcher = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n data: existingFetcher && existingFetcher.data\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }); // Call the loader for this fetcher route match\n\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal);\n fetchControllers.set(key, abortController);\n let result = await callLoaderOrAction(\"loader\", fetchRequest, match); // Deferred isn't supported or fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n\n if (isDeferredResult(result)) {\n result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n } // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n if (fetchRequest.signal.aborted) {\n return;\n } // If the loader threw a redirect Response, start a new REPLACE navigation\n\n if (isRedirectResult(result)) {\n let redirectNavigation = getLoaderRedirect(state, result);\n await startRedirectNavigation(result, redirectNavigation);\n return;\n } // Process any non-redirect errors thrown\n\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error\n }\n });\n return;\n }\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\"); // Put the fetcher back into an idle state\n\n let doneFetcher = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(key, doneFetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n });\n }\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n\n async function startRedirectNavigation(redirect, navigation, replace) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n invariant(navigation.location, \"Expected a location on the redirect navigation\"); // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n\n pendingNavigationController = null;\n let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;\n await startNavigation(redirectHistoryAction, navigation.location, {\n overrideNavigation: navigation\n });\n }\n async function callLoadersAndMaybeResolveData(currentMatches, matchesToLoad, fetchersToLoad, request) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction(\"loader\", request, m)), ...fetchersToLoad.map(_ref8 => {\n let [, href, match] = _ref8;\n return callLoaderOrAction(\"loader\", createRequest(href, request.signal), match);\n })]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => {\n let [,, match] = _ref9;\n return match;\n }), fetcherResults, request.signal, true)]);\n return {\n results,\n loaderResults,\n fetcherResults\n };\n }\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n\n cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads\n\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n function setFetcherError(key, routeId, error) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error\n },\n fetchers: new Map(state.fetchers)\n });\n }\n function deleteFetcher(key) {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n function abortFetcher(key) {\n let controller = fetchControllers.get(key);\n invariant(controller, \"Expected fetch controller: \" + key);\n controller.abort();\n fetchControllers.delete(key);\n }\n function markFetchersDone(keys) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n function markFetchRedirectsDone() {\n let doneKeys = [];\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n }\n }\n markFetchersDone(doneKeys);\n }\n function abortStaleFetchLoads(landedId) {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n function cancelActiveDeferreds(predicate) {\n let cancelledRouteIds = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n } // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n\n function enableScrollRestoration(positions, getPosition, getKey) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({\n restoreScrollPosition: y\n });\n }\n }\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n function saveScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n function getSavedScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n router = {\n get basename() {\n return init.basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n createHref,\n getFetcher,\n deleteFetcher,\n dispose,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds\n };\n return router;\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nfunction unstable_createStaticHandler(routes) {\n invariant(routes.length > 0, \"You must provide a non-empty routes array to unstable_createStaticHandler\");\n let dataRoutes = convertRoutesToDataRoutes(routes);\n async function query(request) {\n let {\n location,\n result\n } = await queryImpl(request);\n if (result instanceof Response) {\n return result;\n } // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n\n return _extends({\n location\n }, result);\n }\n async function queryRoute(request, routeId) {\n let {\n result\n } = await queryImpl(request, routeId);\n if (result instanceof Response) {\n return result;\n }\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // While we always re-throw Responses returned from loaders/actions\n // directly for route requests and prevent the unwrapping into an\n // ErrorResponse, we still need this for error cases _prior_ the\n // execution of the loader/action, such as a 404/405 error.\n if (isRouteErrorResponse(error)) {\n return new Response(error.data, {\n status: error.status,\n statusText: error.statusText\n });\n } // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n\n throw error;\n } // Pick off the right state value to return\n\n let routeData = [result.actionData, result.loaderData].find(v => v);\n let value = Object.values(routeData || {})[0];\n if (isRouteErrorResponse(value)) {\n return new Response(value.data, {\n status: value.status,\n statusText: value.statusText\n });\n }\n return value;\n }\n async function queryImpl(request, routeId) {\n invariant(request.method !== \"HEAD\", \"query()/queryRoute() do not support HEAD requests\");\n invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n let {\n location,\n matches,\n shortCircuitState\n } = matchRequest(request, routeId);\n try {\n if (shortCircuitState) {\n return {\n location,\n result: shortCircuitState\n };\n }\n if (request.method !== \"GET\") {\n let result = await submit(request, matches, getTargetMatch(matches, location), routeId != null);\n return {\n location,\n result\n };\n }\n let result = await loadRouteData(request, matches, routeId != null);\n return {\n location,\n result: _extends({}, result, {\n actionData: null,\n actionHeaders: {}\n })\n };\n } catch (e) {\n if (e instanceof Response) {\n return {\n location,\n result: e\n };\n }\n throw e;\n }\n }\n async function submit(request, matches, actionMatch, isRouteRequest) {\n let result;\n if (!actionMatch.route.action) {\n let href = createHref(new URL(request.url));\n result = getMethodNotAllowedResult(href);\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch, true, isRouteRequest);\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted\");\n }\n }\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // calLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location\n }\n });\n }\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n if (isRouteRequest) {\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: null,\n errors: {\n [boundaryMatch.route.id]: result.error\n },\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 500,\n loaderHeaders: {},\n actionHeaders: {}\n };\n }\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: {\n [actionMatch.route.id]: result.data\n },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {}\n };\n }\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(request, matches, isRouteRequest, {\n [boundaryMatch.route.id]: result.error\n }); // action status codes take precedence over loader status codes\n\n return _extends({}, context, {\n statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,\n actionData: null,\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n let context = await loadRouteData(request, matches, isRouteRequest);\n return _extends({}, context, result.statusCode ? {\n statusCode: result.statusCode\n } : {}, {\n actionData: {\n [actionMatch.route.id]: result.data\n },\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n async function loadRouteData(request, matches, isRouteRequest, pendingActionError) {\n let matchesToLoad = getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]).filter(m => m.route.loader); // Short circuit if we have no loaders to run\n\n if (matchesToLoad.length === 0) {\n return {\n matches,\n loaderData: {},\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {}\n };\n }\n let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction(\"loader\", request, m, true, isRouteRequest))]);\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted\");\n } // Can't do anything with these without the Remix side of things, so just\n // cancel them for now\n\n results.forEach(result => {\n if (isDeferredResult(result)) {\n result.deferredData.cancel();\n }\n }); // Process and commit output from loaders\n\n let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError);\n return _extends({}, context, {\n matches\n });\n }\n function matchRequest(req, routeId) {\n let url = new URL(req.url);\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location);\n if (matches && routeId) {\n matches = matches.filter(m => m.route.id === routeId);\n } // Short circuit with a 404 if we match nothing\n\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error\n } = getNotFoundMatches(dataRoutes);\n return {\n location,\n matches: notFoundMatches,\n shortCircuitState: {\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: 404,\n loaderHeaders: {},\n actionHeaders: {}\n }\n };\n }\n return {\n location,\n matches\n };\n }\n return {\n dataRoutes,\n query,\n queryRoute\n };\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\n\nfunction getStaticContextFromError(routes, context, error) {\n let newContext = _extends({}, context, {\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error\n }\n });\n return newContext;\n} // Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\n\nfunction normalizeNavigateOptions(to, opts, isFetcher) {\n if (isFetcher === void 0) {\n isFetcher = false;\n }\n let path = typeof to === \"string\" ? to : createPath(to); // Return location verbatim on non-submission navigations\n\n if (!opts || !(\"formMethod\" in opts) && !(\"formData\" in opts)) {\n return {\n path\n };\n } // Create a Submission on non-GET navigations\n\n if (opts.formMethod != null && opts.formMethod !== \"get\") {\n return {\n path,\n submission: {\n formMethod: opts.formMethod,\n formAction: createHref(parsePath(path)),\n formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n formData: opts.formData\n }\n };\n } // No formData to flatten for GET submission\n\n if (!opts.formData) {\n return {\n path\n };\n } // Flatten submission onto URLSearchParams for GET submissions\n\n let parsedPath = parsePath(path);\n try {\n let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to\n // navigation GET submissions which run all loaders), we need to preserve\n // any incoming ?index params\n\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = \"?\" + searchParams;\n } catch (e) {\n return {\n path,\n error: new ErrorResponse(400, \"Bad Request\", \"Cannot submit binary form data using GET\")\n };\n }\n return {\n path: createPath(parsedPath)\n };\n}\nfunction getLoaderRedirect(state, redirect) {\n let {\n formMethod,\n formAction,\n formEncType,\n formData\n } = state.navigation;\n let navigation = {\n state: \"loading\",\n location: createLocation(state.location, redirect.location),\n formMethod: formMethod || undefined,\n formAction: formAction || undefined,\n formEncType: formEncType || undefined,\n formData: formData || undefined\n };\n return navigation;\n} // Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\n\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex(m => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\nfunction getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {\n let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : null; // Pick navigation matches that are net-new or qualify for revalidation\n\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) ||\n // If this route had a pending deferred cancelled it must be revalidated\n cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated\n\n let revalidatingFetchers = [];\n fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => {\n let [href, match] = _ref10;\n\n // This fetcher was cancelled from a prior action submission - force reload\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push([key, href, match]);\n } else if (isRevalidationRequired) {\n let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult);\n if (shouldRevalidate) {\n revalidatingFetchers.push([key, href, match]);\n }\n }\n });\n return [navigationMatches, revalidatingFetchers];\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n\n let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data\n\n return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n currentPath && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n );\n}\nfunction shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) {\n let currentUrl = createURL(currentLocation);\n let currentParams = currentMatch.params;\n let nextUrl = createURL(location);\n let nextParams = match.params; // This is the default implementation as to when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n // Note that fetchers always provide the same current/next locations so the\n // URL-based checks here don't apply to fetcher shouldRevalidate calls\n\n let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.toString() === nextUrl.toString() ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n isRevalidationRequired;\n if (match.route.shouldRevalidate) {\n let routeChoice = match.route.shouldRevalidate(_extends({\n currentUrl,\n currentParams,\n nextUrl,\n nextParams\n }, submission, {\n actionResult,\n defaultShouldRevalidate\n }));\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n return defaultShouldRevalidate;\n}\nasync function callLoaderOrAction(type, request, match, skipRedirects, isRouteRequest) {\n if (skipRedirects === void 0) {\n skipRedirects = false;\n }\n if (isRouteRequest === void 0) {\n isRouteRequest = false;\n }\n let resultType;\n let result; // Setup a promise we can race against so that abort signals short circuit\n\n let reject;\n let abortPromise = new Promise((_, r) => reject = r);\n let onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n try {\n let handler = match.route[type];\n invariant(handler, \"Could not find the \" + type + \" to run on the \\\"\" + match.route.id + \"\\\" route\");\n result = await Promise.race([handler({\n request,\n params: match.params\n }), abortPromise]);\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n if (result instanceof Response) {\n // Process redirects\n let status = result.status;\n let location = result.headers.get(\"Location\"); // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping\n\n if (isRouteRequest) {\n throw result;\n }\n if (status >= 300 && status <= 399 && location != null) {\n // Don't process redirects in the router during SSR document requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect\n if (skipRedirects) {\n throw result;\n }\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null\n };\n }\n let data;\n let contentType = result.headers.get(\"Content-Type\");\n if (contentType && contentType.startsWith(\"application/json\")) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\n headers: result.headers\n };\n }\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers\n };\n }\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: result\n };\n }\n if (result instanceof DeferredData) {\n return {\n type: ResultType.deferred,\n deferredData: result\n };\n }\n return {\n type: ResultType.data,\n data: result\n };\n}\nfunction createRequest(location, signal, submission) {\n let url = createURL(location).toString();\n let init = {\n signal\n };\n if (submission) {\n let {\n formMethod,\n formEncType,\n formData\n } = submission;\n init.method = formMethod.toUpperCase();\n init.body = formEncType === \"application/x-www-form-urlencoded\" ? convertFormDataToSearchParams(formData) : formData;\n } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n\n return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n let searchParams = new URLSearchParams();\n for (let [key, value] of formData.entries()) {\n invariant(typeof value === \"string\", 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' + 'please use \"multipart/form-data\" instead.');\n searchParams.append(key, value);\n }\n return searchParams;\n}\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {\n // Fill in loaderData/errors from our loaders\n let loaderData = {};\n let errors = null;\n let statusCode;\n let foundError = false;\n let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors\n\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error; // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n errors = Object.assign(errors || {}, {\n [boundaryMatch.route.id]: error\n }); // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else if (isDeferredResult(result)) {\n activeDeferreds && activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix\n } else {\n loaderData[id] = result.data; // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n\n if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }); // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here\n\n if (pendingError) {\n errors = pendingError;\n }\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders\n };\n}\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {\n let {\n loaderData,\n errors\n } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers\n\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let [key,, match] = revalidatingFetchers[index];\n invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n let result = fetcherResults[index]; // Process fetcher non-redirect errors\n\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = _extends({}, errors, {\n [boundaryMatch.route.id]: result.error\n });\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n throw new Error(\"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n throw new Error(\"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n return {\n loaderData,\n errors\n };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches) {\n let mergedLoaderData = _extends({}, newLoaderData);\n matches.forEach(match => {\n let id = match.route.id;\n if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {\n mergedLoaderData[id] = loaderData[id];\n }\n });\n return mergedLoaderData;\n} // Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\n\nfunction findNearestBoundary(matches, routeId) {\n let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];\n return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];\n}\nfunction getNotFoundMatches(routes) {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find(r => r.index || r.path === \"\" || r.path === \"/\") || {\n id: \"__shim-404-route__\"\n };\n return {\n matches: [{\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route\n }],\n route,\n error: new ErrorResponse(404, \"Not Found\", null)\n };\n}\nfunction getMethodNotAllowedResult(path) {\n let href = typeof path === \"string\" ? path : createHref(path);\n console.warn(\"You're trying to submit to a route that does not have an action. To \" + \"fix this, please add an `action` function to the route for \" + (\"[\" + href + \"]\"));\n return {\n type: ResultType.error,\n error: new ErrorResponse(405, \"Method Not Allowed\", \"No action found for [\" + href + \"]\")\n };\n} // Find any returned redirect errors, starting from the lowest match\n\nfunction findRedirect(results) {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return result;\n }\n }\n} // Create an href to represent a \"server\" URL without the hash\n\nfunction createHref(location) {\n return (location.pathname || \"\") + (location.search || \"\");\n}\nfunction isHashChangeOnly(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;\n}\nfunction isDeferredResult(result) {\n return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n return (result && result.type) === ResultType.redirect;\n}\nasync function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n let currentMatch = currentMatches.find(m => m.route.id === match.route.id);\n let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, isFetcher).then(result => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\nasync function resolveDeferredData(result, signal, unwrap) {\n if (unwrap === void 0) {\n unwrap = false;\n }\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e\n };\n }\n }\n return {\n type: ResultType.data,\n data: result.deferredData.data\n };\n}\nfunction hasNakedIndexQuery(search) {\n return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n} // Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\n\nfunction createUseMatchesMatch(match, loaderData) {\n let {\n route,\n pathname,\n params\n } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle\n };\n}\nfunction getTargetMatch(matches, location) {\n let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n if (matches[matches.length - 1].route.index && !hasNakedIndexQuery(search || \"\")) {\n return matches.slice(-2)[0];\n }\n return matches.slice(-1)[0];\n}\nfunction createURL(location) {\n let base = typeof window !== \"undefined\" && typeof window.location !== \"undefined\" ? window.location.origin : \"unknown://unknown\";\n let href = typeof location === \"string\" ? location : createHref(location);\n return new URL(href, base);\n} //#endregion\n\nexport { AbortedDeferredError, Action, ErrorResponse, IDLE_FETCHER, IDLE_NAVIGATION, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, unstable_createStaticHandler, warning };","map":{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;;AAEG;IACSA;AAAZ,WAAYA,MAAZ,EAAkB;EAChB;;;;;;AAMG;EACHA;EAEA;;;;AAIG;;EACHA;EAEA;;;AAGG;;EACHA;AACD,CAtBD,EAAYA,MAAM,KAANA,MAAM,GAsBjB,EAtBiB,CAAlB;AAkKA,MAAMC,iBAAiB,GAAG,UAA1B;AA+BA;;;AAGG;;AACa,6BACdC,OADc,EACoB;EAAA,IAAlCA,OAAkC;IAAlCA,OAAkC,GAAF,EAAE;EAAA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AF;IAASpE,QAAT;IAAmBuI;EAAnB,IAA8BH,KAAlC;EACA,OAAO;IACLzD,EAAE,EAAEP,KAAK,CAACO,EADL;IAEL3E,QAFK;IAGLuI,MAHK;IAILsD,IAAI,EAAEkF,UAAU,CAAC3M,KAAK,CAACO,EAAP,CAJX;IAKL6Y,MAAM,EAAEpZ,KAAK,CAACoZ;GALhB;AAOD;AAED,SAAShJ,cAAT,CACE9O,OADF,EAEE5F,QAFF,EAE6B;EAE3B,IAAIuB,MAAM,GACR,OAAOvB,QAAP,KAAoB,QAApB,GAA+B6B,SAAS,CAAC7B,QAAD,CAAT,CAAoBuB,MAAnD,GAA4DvB,QAAQ,CAACuB,MADvE;EAEA,IACEqE,OAAO,CAACA,OAAO,CAACvG,MAAR,GAAiB,CAAlB,CAAP,CAA4BiF,KAA5B,CAAkCtF,KAAlC,IACA,CAAC+b,kBAAkB,CAACxZ,MAAM,IAAI,EAAX,CAFrB,EAGE;IACA,OAAOqE,OAAO,CAACpD,KAAR,CAAc,CAAC,CAAf,EAAkB,CAAlB,CAAP;EACD;EACD,OAAOoD,OAAO,CAACpD,KAAR,CAAc,CAAC,CAAf,EAAkB,CAAlB,CAAP;AACD;AAED,SAASwZ,SAAT,CAAmBhc,QAAnB,EAA8C;EAC5C,IAAIgC,IAAI,GACN,OAAOX,MAAP,KAAkB,WAAlB,IAAiC,OAAOA,MAAM,CAACrB,QAAd,KAA2B,WAA5D,GACIqB,MAAM,CAACrB,QAAP,CAAgB2d,MADpB,GAEI,mBAHN;EAIA,IAAIxb,IAAI,GAAG,OAAOnC,QAAP,KAAoB,QAApB,GAA+BA,QAA/B,GAA0CQ,UAAU,CAACR,QAAD,CAA/D;EACA,OAAO,IAAIia,GAAJ,CAAQ9X,IAAR,EAAcH,IAAd,CAAP;AACD","names":["Action","PopStateEventType","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","history","createHref","createPath","push","Push","nextLocation","splice","replace","Replace","go","delta","listen","fn","createBrowserLocation","window","globalHistory","search","hash","usr","createBrowserHref","getUrlBasedHistory","createHashLocation","parsePath","substr","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","cond","message","console","warn","Error","e","createKey","random","toString","getHistoryState","current","_ref","path","parsedPath","searchIndex","getLocation","validateLocation","defaultView","handlePop","historyState","pushState","error","assign","replaceState","addEventListener","removeEventListener","ResultType","isIndexRoute","route","convertRoutesToDataRoutes","routes","parentPath","allIds","Set","treePath","id","join","invariant","children","has","add","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","parentsMeta","forEach","meta","relativePath","caseSensitive","childrenIndex","startsWith","joinPaths","routesMeta","concat","score","computeScore","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","segments","split","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","match","matchPath","Object","params","pathnameBase","normalizePathname","generatePath","_","prefix","__","str","star","pattern","matcher","paramNames","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","endsWith","regexpSource","RegExp","value","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","includes","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","data","init","responseInit","status","headers","Headers","set","Response","AbortedDeferredError","DeferredData","constructor","subscriber","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","pendingKeys","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","done","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","unwrapTrackedPromise","isTrackedPromise","_tracked","_error","_data","defer","redirect","ErrorResponse","statusText","isRouteErrorResponse","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","IDLE_FETCHER","createRouter","dataRoutes","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","initialMatches","initialErrors","getNotFoundMatches","initialized","m","loader","hydrationData","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","loaderData","actionData","errors","fetchers","Map","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","initialize","startNavigation","dispose","clear","deleteFetcher","updateState","newState","completeNavigation","isActionReload","newLoaderData","mergeLoaderData","getSavedScrollPosition","navigate","opts","submission","normalizeNavigateOptions","pendingError","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","handleLoaders","result","actionMatch","getTargetMatch","getMethodNotAllowedResult","callLoaderOrAction","isRedirectResult","redirectNavigation","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","matchesToLoad","revalidatingFetchers","getMatchesToLoad","routeId","_ref2","fetcher","revalidatingFetcher","_ref3","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","_ref4","findRedirect","getLoaderRedirect","processLoaderData","deferredData","markFetchRedirectsDone","didAbortFetchLoads","abortStaleFetchLoads","getFetcher","fetch","abortFetcher","setFetcherError","handleFetcherAction","handleFetcherLoader","existingFetcher","abortController","fetchRequest","actionResult","loadingFetcher","revalidationRequest","loadId","loadFetcher","_ref5","staleKey","_ref6","_ref7","doneFetcher","resolveDeferredData","redirectHistoryAction","currentMatches","fetchersToLoad","all","_ref8","resolveDeferredResults","_ref9","markFetchersDone","keys","doneKeys","landedId","yeetedKeys","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","userMatches","createUseMatchesMatch","_internalFetchControllers","_internalActiveDeferreds","unstable_createStaticHandler","query","queryImpl","queryRoute","values","routeData","find","method","shortCircuitState","matchRequest","submit","loadRouteData","actionHeaders","isRouteRequest","URL","Location","statusCode","loaderHeaders","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","req","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isFetcher","searchParams","convertFormDataToSearchParams","hasNakedIndexQuery","append","boundaryId","boundaryMatches","findIndex","navigationMatches","isNewLoader","shouldRevalidateLoader","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","isNewRouteInstance","currentPath","currentLocation","currentUrl","createURL","currentParams","nextUrl","nextParams","defaultShouldRevalidate","routeChoice","type","skipRedirects","resultType","onReject","handler","contentType","text","deferred","toUpperCase","body","Request","URLSearchParams","foundError","mergedLoaderData","eligibleMatches","reverse","hasErrorBoundary","isRevalidatingLoader","unwrap","getAll","handle","origin"],"sources":["C:\\Cours\\SAE\\SAE-3.01\\Scripted\\Scripted\\website\\node_modules\\@remix-run\\router\\history.ts","C:\\Cours\\SAE\\SAE-3.01\\Scripted\\Scripted\\website\\node_modules\\@remix-run\\router\\utils.ts","C:\\Cours\\SAE\\SAE-3.01\\Scripted\\Scripted\\website\\node_modules\\@remix-run\\router\\router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: any;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an <a href> attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation });\n }\n },\n go(delta) {\n action = Action.Pop;\n index = clampIndex(index + delta);\n if (listener) {\n listener({ action, location: getCurrentLocation() });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\nfunction warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly<Location> {\n let location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial<Path>) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n let parsedPath: Partial<Path> = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function handlePop() {\n action = Action.Pop;\n if (listener) {\n listener({ action, location: history.location });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n let historyState = getHistoryState(location);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n let historyState = getHistoryState(location);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: location });\n }\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { parsePath } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\nexport type FormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n formMethod: Exclude<FormMethod, \"get\">;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n}\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n (args: LoaderFunctionArgs): Promise<Response> | Response | Promise<any> | any;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs): Promise<Response> | Response | Promise<any> | any;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n formData?: Submission[\"formData\"];\n actionResult?: DataResult;\n defaultShouldRevalidate: boolean;\n }): boolean;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam<L> | _PathParam<R>\n : // find params after `:`\n Path extends `${string}:${infer Param}`\n ? Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\ntype PathParam<Path extends string> =\n // check if path is just a wildcard\n Path extends \"*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam<Rest>\n : // look for params in the absence of wildcards\n _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n // if could not find path params, fallback to `string`\n [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n parentPath: number[] = [],\n allIds: Set<string> = new Set<string>()\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !allIds.has(id),\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n allIds.add(id);\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = { ...route, id };\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n id,\n children: route.children\n ? convertRoutesToDataRoutes(route.children, treePath, allIds)\n : undefined,\n };\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial<Location> | string,\n basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch<string, RouteObjectType>(branches[i], pathname);\n }\n\n return matches;\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch<RouteObjectType>[] = [],\n parentsMeta: RouteMeta<RouteObjectType>[] = [],\n parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n routes.forEach((route, index) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath: route.path || \"\",\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({ path, score: computeScore(path, route.index), routesMeta });\n });\n\n return branches;\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch<RouteObjectType>,\n pathname: string\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params<ParamKey>,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n path: Path,\n params: {\n [key in PathParam<Path>]: string;\n } = {} as any\n): string {\n return path\n .replace(/:(\\w+)/g, (_, key: PathParam<Path>) => {\n invariant(params[key] != null, `Missing \":${key}\" param`);\n return params[key]!;\n })\n .replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n const star = \"*\" as PathParam<Path>;\n\n if (params[star] == null) {\n // If no splat was provided, trim the trailing slash _unless_ it's\n // the entire path\n return str === \"/*\" ? \"/\" : \"\";\n }\n\n // Apply the splat\n return `${prefix}${params[star]}`;\n });\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params<ParamKey>;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(\n pattern: PathPattern<Path> | Path,\n pathname: string\n): PathMatch<ParamKey> | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, paramNames] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = paramNames.reduce<Mutable<Params>>(\n (memo, paramName, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n memo[paramName] = safelyDecodeURIComponent(\n captureGroups[index] || \"\",\n paramName\n );\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, string[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let paramNames: string[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/:(\\w+)/g, (_: string, paramName: string) => {\n paramNames.push(paramName);\n return \"([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, paramNames];\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\n/**\n * @private\n */\nexport function warning(cond: any, message: string): void {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging React Router!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/docs/en/v6/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial<Path>\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in <Link to=\"...\"> and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial<Path>;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how <a href> works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise<any> {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeys: Set<string | number> = new Set<string | number>();\n private controller: AbortController;\n private abortPromise: Promise<void>;\n private unlistenAbortSignal: () => void;\n private subscriber?: (aborted: boolean) => void = undefined;\n data: Record<string, unknown>;\n\n constructor(data: Record<string, unknown>) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n }\n\n private trackPromise(\n key: string | number,\n value: Promise<unknown> | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.pendingKeys.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, null, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string | number,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeys.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n const subscriber = this.subscriber;\n if (error) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n subscriber && subscriber(false);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n subscriber && subscriber(false);\n return data;\n }\n\n subscribe(fn: (aborted: boolean) => void) {\n this.subscriber = fn;\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n let subscriber = this.subscriber;\n subscriber && subscriber(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeys.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport function defer(data: Record<string, unknown>) {\n return new DeferredData(data);\n}\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n\n constructor(status: number, statusText: string | undefined, data: any) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.data = data;\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\nexport function isRouteErrorResponse(e: any): e is ErrorResponse {\n return e instanceof ErrorResponse;\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n parsePath,\n} from \"./history\";\nimport type {\n DataResult,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DeferredResult,\n ErrorResult,\n FormEncType,\n FormMethod,\n RedirectResult,\n RouteData,\n AgnosticRouteObject,\n Submission,\n SuccessResult,\n AgnosticRouteMatch,\n} from \"./utils\";\nimport {\n DeferredData,\n ErrorResponse,\n ResultType,\n convertRoutesToDataRoutes,\n invariant,\n isRouteErrorResponse,\n matchRoutes,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record<string, number>,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): void;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To, opts?: RouterNavigateOptions): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string,\n opts?: RouterNavigateOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher<TData = any>(key?: string): Fetcher<TData>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key?: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map<string, AbortController>;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map<string, Fetcher>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n basename?: string;\n routes: AgnosticRouteObject[];\n history: History;\n hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n actionHeaders: Record<string, Headers>;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(request: Request): Promise<StaticHandlerContext | Response>;\n queryRoute(request: Request, routeId?: string): Promise<any>;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: unknown;\n handle: unknown;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n};\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = {\n replace?: boolean;\n state?: any;\n formMethod?: FormMethod;\n formEncType?: FormEncType;\n formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n | Omit<LinkNavigateOptions, \"replace\">\n | Omit<SubmissionNavigateOptions, \"replace\">;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Tuple of [key, href, DataRouterMatch] for a revalidating fetcher.load()\n */\ntype RevalidatingFetcher = [string, string, AgnosticDataRouteMatch];\n\n/**\n * Tuple of [href, DataRouteMatch] for an active fetcher.load()\n */\ntype FetchLoadMatch = [string, AgnosticDataRouteMatch];\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n};\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(init.routes);\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set<RouterSubscriber>();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record<string, number> | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n let initialScrollRestored = false;\n\n let initialMatches = matchRoutes(\n dataRoutes,\n init.history.location,\n init.basename\n );\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let { matches, route, error } = getNotFoundMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n !initialMatches.some((m) => m.route.loader) || init.hydrationData != null;\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n restoreScrollPosition: null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidate()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n // Fetchers that triggered redirect navigations from their actions\n let fetchRedirectIds = new Set<string>();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map<string, DeferredData>();\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location }) =>\n startNavigation(historyAction, location)\n );\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(newState: Partial<RouterState>): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) => subscriber(state));\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a submission\n // - We're past the submitting state and into the loading state\n // - The location we've finished loading is different from the submission\n // location, indicating we redirected from the action (avoids false\n // positives for loading/submissionRedirect when actionData returned\n // on a prior submission)\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n state.navigation.state === \"loading\" &&\n state.navigation.formAction?.split(\"?\")[0] === location.pathname;\n\n // Always preserve any existing loaderData from re-used routes\n let newLoaderData = newState.loaderData\n ? {\n loaderData: mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || []\n ),\n }\n : {};\n\n updateState({\n // Clear existing actionData on any completed navigation beyond the original\n // action, unless we're currently finishing the loading/actionReload state.\n // Do this prior to spreading in newState in case we got back to back actions\n ...(isActionReload ? {} : { actionData: null }),\n ...newState,\n ...newLoaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n // Don't restore on submission navigations\n restoreScrollPosition: state.navigation.formData\n ? false\n : getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset: pendingPreventScrollReset,\n });\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To,\n opts?: RouterNavigateOptions\n ): Promise<void> {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(to, opts);\n\n let location = createLocation(state.location, path, opts && opts.state);\n let historyAction =\n (opts && opts.replace) === true || submission != null\n ? HistoryAction.Replace\n : HistoryAction.Push;\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n return await startNavigation(historyAction, location, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n submission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponse;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n }\n ): Promise<void> {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(dataRoutes, location, init.basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n });\n return;\n }\n\n // Short circuit if it's only a hash change\n if (isHashChangeOnly(state.location, location)) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createRequest(\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (opts && opts.submission) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n ...opts.submission,\n };\n loadingNavigation = navigation;\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.replace,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts?: { replace?: boolean }\n ): Promise<HandleActionResult> {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n ...submission,\n };\n updateState({ navigation });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action) {\n result = getMethodNotAllowedResult(location);\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch);\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, result.location),\n ...submission,\n };\n await startRedirectNavigation(\n result,\n redirectNavigation,\n opts && opts.replace\n );\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n replace?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise<HandleLoadersResult> {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n if (!loadingNavigation) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n loadingNavigation = navigation;\n }\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n pendingActionData,\n pendingError,\n fetchLoadMatches\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n completeNavigation(location, {\n matches,\n loaderData: mergeLoaderData(state.loaderData, {}, matches),\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n actionData: pendingActionData || null,\n });\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach(([key]) => {\n const fetcher = state.fetchers.get(key);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, revalidatingFetcher);\n });\n updateState({\n navigation: loadingNavigation,\n actionData: pendingActionData || state.actionData || null,\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach(([key]) =>\n fetchControllers.set(key, pendingNavigationController!)\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation, replace);\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n\n return {\n loaderData,\n errors,\n ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n };\n }\n\n function getFetcher<TData = any>(key: string): Fetcher<TData> {\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string,\n opts?: RouterFetchOptions\n ) {\n if (typeof AbortController === \"undefined\") {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n\n let matches = matchRoutes(dataRoutes, href, init.basename);\n if (!matches) {\n setFetcherError(key, routeId, new ErrorResponse(404, \"Not Found\", null));\n return;\n }\n\n let { path, submission } = normalizeNavigateOptions(href, opts, true);\n let match = getTargetMatch(matches, path);\n\n if (submission) {\n handleFetcherAction(key, routeId, path, match, submission);\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, [path, match]);\n handleFetcherLoader(key, routeId, path, match);\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action) {\n let { error } = getMethodNotAllowedResult(path);\n setFetcherError(key, routeId, error);\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n ...submission,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, fetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal, submission);\n fetchControllers.set(key, abortController);\n\n let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match);\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n ...submission,\n data: undefined,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, actionResult.location),\n ...submission,\n };\n await startRedirectNavigation(actionResult, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n invariant(false, \"defer() is not supported in actions\");\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createRequest(\n nextLocation,\n abortController.signal\n );\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(dataRoutes, state.navigation.location, init.basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: actionResult.data,\n ...submission,\n };\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n { [match.route.id]: actionResult.data },\n undefined, // No need to send through errors since we short circuit above\n fetchLoadMatches\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter(([staleKey]) => staleKey !== key)\n .forEach(([staleKey]) => {\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n fetchControllers.set(staleKey, abortController);\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(([staleKey]) =>\n fetchControllers.delete(staleKey)\n );\n\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation);\n return;\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n\n let didAbortFetchLoads = abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches),\n ...(didAbortFetchLoads ? { fetchers: new Map(state.fetchers) } : {}),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch\n ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal);\n fetchControllers.set(key, abortController);\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match\n );\n\n // Deferred isn't supported or fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n let redirectNavigation = getLoaderRedirect(state, result);\n await startRedirectNavigation(result, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key);\n // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n redirect: RedirectResult,\n navigation: Navigation,\n replace?: boolean\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n invariant(\n navigation.location,\n \"Expected a location on the redirect navigation\"\n );\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n await startNavigation(redirectHistoryAction, navigation.location, {\n overrideNavigation: navigation,\n });\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((m) => callLoaderOrAction(\"loader\", request, m)),\n ...fetchersToLoad.map(([, href, match]) =>\n callLoaderOrAction(\"loader\", createRequest(href, request.signal), match)\n ),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n request.signal,\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map(([, , match]) => match),\n fetcherResults,\n request.signal,\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key: string, routeId: string, error: any) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n });\n }\n\n function deleteFetcher(key: string): void {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): void {\n let doneKeys = [];\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n }\n }\n markFetchersDone(doneKeys);\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(\n positions: Record<string, number>,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || ((location) => location.key);\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n router = {\n get basename() {\n return init.basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n createHref,\n getFetcher,\n deleteFetcher,\n dispose,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport function unstable_createStaticHandler(\n routes: AgnosticRouteObject[]\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to unstable_createStaticHandler\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(routes);\n\n async function query(\n request: Request\n ): Promise<StaticHandlerContext | Response> {\n let { location, result } = await queryImpl(request);\n if (result instanceof Response) {\n return result;\n }\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, ...result };\n }\n\n async function queryRoute(request: Request, routeId: string): Promise<any> {\n let { result } = await queryImpl(request, routeId);\n if (result instanceof Response) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // While we always re-throw Responses returned from loaders/actions\n // directly for route requests and prevent the unwrapping into an\n // ErrorResponse, we still need this for error cases _prior_ the\n // execution of the loader/action, such as a 404/405 error.\n if (isRouteErrorResponse(error)) {\n return new Response(error.data, {\n status: error.status,\n statusText: error.statusText,\n });\n }\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n let routeData = [result.actionData, result.loaderData].find((v) => v);\n let value = Object.values(routeData || {})[0];\n\n if (isRouteErrorResponse(value)) {\n return new Response(value.data, {\n status: value.status,\n statusText: value.statusText,\n });\n }\n\n return value;\n }\n\n async function queryImpl(\n request: Request,\n routeId?: string\n ): Promise<{\n location: Location;\n result: Omit<StaticHandlerContext, \"location\"> | Response;\n }> {\n invariant(\n request.method !== \"HEAD\",\n \"query()/queryRoute() do not support HEAD requests\"\n );\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n let { location, matches, shortCircuitState } = matchRequest(\n request,\n routeId\n );\n\n try {\n if (shortCircuitState) {\n return { location, result: shortCircuitState };\n }\n\n if (request.method !== \"GET\") {\n let result = await submit(\n request,\n matches,\n getTargetMatch(matches, location),\n routeId != null\n );\n return { location, result };\n }\n\n let result = await loadRouteData(request, matches, routeId != null);\n return {\n location,\n result: {\n ...result,\n actionData: null,\n actionHeaders: {},\n },\n };\n } catch (e) {\n if (e instanceof Response) {\n return { location, result: e };\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\"> | Response> {\n let result: DataResult;\n if (!actionMatch.route.action) {\n let href = createHref(new URL(request.url));\n result = getMethodNotAllowedResult(href);\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n true,\n isRouteRequest\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // calLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n if (isRouteRequest) {\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: null,\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 500,\n loaderHeaders: {},\n actionHeaders: {},\n };\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(request, matches, isRouteRequest, {\n [boundaryMatch.route.id]: result.error,\n });\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(request, matches, isRouteRequest);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<StaticHandlerContext, \"location\" | \"actionData\" | \"actionHeaders\">\n | Response\n > {\n let matchesToLoad = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n ).filter((m) => m.route.loader);\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0) {\n return {\n matches,\n loaderData: {},\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((m) =>\n callLoaderOrAction(\"loader\", request, m, true, isRouteRequest)\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n\n // Can't do anything with these without the Remix side of things, so just\n // cancel them for now\n results.forEach((result) => {\n if (isDeferredResult(result)) {\n result.deferredData.cancel();\n }\n });\n\n // Process and commit output from loaders\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError\n );\n\n return {\n ...context,\n matches,\n };\n }\n\n function matchRequest(\n req: Request,\n routeId?: string\n ): {\n location: Location;\n matches: AgnosticDataRouteMatch[];\n routeMatch?: AgnosticDataRouteMatch;\n shortCircuitState?: Omit<StaticHandlerContext, \"location\">;\n } {\n let url = new URL(req.url);\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location);\n if (matches && routeId) {\n matches = matches.filter((m) => m.route.id === routeId);\n }\n\n // Short circuit with a 404 if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n return {\n location,\n matches: notFoundMatches,\n shortCircuitState: {\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: 404,\n loaderHeaders: {},\n actionHeaders: {},\n },\n };\n }\n\n return { location, matches };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n to: To,\n opts?: RouterNavigateOptions,\n isFetcher = false\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponse;\n} {\n let path = typeof to === \"string\" ? to : createPath(to);\n\n // Return location verbatim on non-submission navigations\n if (!opts || (!(\"formMethod\" in opts) && !(\"formData\" in opts))) {\n return { path };\n }\n\n // Create a Submission on non-GET navigations\n if (opts.formMethod != null && opts.formMethod !== \"get\") {\n return {\n path,\n submission: {\n formMethod: opts.formMethod,\n formAction: createHref(parsePath(path)),\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData: opts.formData,\n },\n };\n }\n\n // No formData to flatten for GET submission\n if (!opts.formData) {\n return { path };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n try {\n let searchParams = convertFormDataToSearchParams(opts.formData);\n // Since fetcher GET submissions only run a single loader (as opposed to\n // navigation GET submissions which run all loaders), we need to preserve\n // any incoming ?index params\n if (\n isFetcher &&\n parsedPath.search &&\n hasNakedIndexQuery(parsedPath.search)\n ) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n } catch (e) {\n return {\n path,\n error: new ErrorResponse(\n 400,\n \"Bad Request\",\n \"Cannot submit binary form data using GET\"\n ),\n };\n }\n\n return { path: createPath(parsedPath) };\n}\n\nfunction getLoaderRedirect(\n state: RouterState,\n redirect: RedirectResult\n): Navigation {\n let { formMethod, formAction, formEncType, formData } = state.navigation;\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, redirect.location),\n formMethod: formMethod || undefined,\n formAction: formAction || undefined,\n formEncType: formEncType || undefined,\n formData: formData || undefined,\n };\n return navigation;\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n pendingActionData?: RouteData,\n pendingError?: RouteData,\n fetchLoadMatches?: Map<string, FetchLoadMatch>\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : null;\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n let navigationMatches = boundaryMatches.filter(\n (match, index) =>\n match.route.loader != null &&\n (isNewLoader(state.loaderData, state.matches[index], match) ||\n // If this route had a pending deferred cancelled it must be revalidated\n cancelledDeferredRoutes.some((id) => id === match.route.id) ||\n shouldRevalidateLoader(\n state.location,\n state.matches[index],\n submission,\n location,\n match,\n isRevalidationRequired,\n actionResult\n ))\n );\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches &&\n fetchLoadMatches.forEach(([href, match], key) => {\n // This fetcher was cancelled from a prior action submission - force reload\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push([key, href, match]);\n } else if (isRevalidationRequired) {\n let shouldRevalidate = shouldRevalidateLoader(\n href,\n match,\n submission,\n href,\n match,\n isRevalidationRequired,\n actionResult\n );\n if (shouldRevalidate) {\n revalidatingFetchers.push([key, href, match]);\n }\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n currentLocation: string | Location,\n currentMatch: AgnosticDataRouteMatch,\n submission: Submission | undefined,\n location: string | Location,\n match: AgnosticDataRouteMatch,\n isRevalidationRequired: boolean,\n actionResult: DataResult | undefined\n) {\n let currentUrl = createURL(currentLocation);\n let currentParams = currentMatch.params;\n let nextUrl = createURL(location);\n let nextParams = match.params;\n\n // This is the default implementation as to when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n // Note that fetchers always provide the same current/next locations so the\n // URL-based checks here don't apply to fetcher shouldRevalidate calls\n let defaultShouldRevalidate =\n isNewRouteInstance(currentMatch, match) ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.toString() === nextUrl.toString() ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n isRevalidationRequired;\n\n if (match.route.shouldRevalidate) {\n let routeChoice = match.route.shouldRevalidate({\n currentUrl,\n currentParams,\n nextUrl,\n nextParams,\n ...submission,\n actionResult,\n defaultShouldRevalidate,\n });\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return defaultShouldRevalidate;\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n skipRedirects: boolean = false,\n isRouteRequest: boolean = false\n): Promise<DataResult> {\n let resultType;\n let result;\n\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n let onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n try {\n let handler = match.route[type];\n invariant<Function>(\n handler,\n `Could not find the ${type} to run on the \"${match.route.id}\" route`\n );\n\n result = await Promise.race([\n handler({ request, params: match.params }),\n abortPromise,\n ]);\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n\n if (result instanceof Response) {\n // Process redirects\n let status = result.status;\n let location = result.headers.get(\"Location\");\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping\n if (isRouteRequest) {\n throw result;\n }\n\n if (status >= 300 && status <= 399 && location != null) {\n // Don't process redirects in the router during SSR document requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect\n if (skipRedirects) {\n throw result;\n }\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n };\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n if (contentType && contentType.startsWith(\"application/json\")) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (result instanceof DeferredData) {\n return { type: ResultType.deferred, deferredData: result };\n }\n\n return { type: ResultType.data, data: result };\n}\n\nfunction createRequest(\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = createURL(location).toString();\n let init: RequestInit = { signal };\n\n if (submission) {\n let { formMethod, formEncType, formData } = submission;\n init.method = formMethod.toUpperCase();\n init.body =\n formEncType === \"application/x-www-form-urlencoded\"\n ? convertFormDataToSearchParams(formData)\n : formData;\n }\n\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n invariant(\n typeof value === \"string\",\n 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' +\n 'please use \"multipart/form-data\" instead.'\n );\n searchParams.append(key, value);\n }\n\n return searchParams;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds?: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record<string, Headers>;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record<string, Headers> = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n errors = Object.assign(errors || {}, {\n [boundaryMatch.route.id]: error,\n });\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else if (isDeferredResult(result)) {\n activeDeferreds && activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // TODO: Add statusCode/headers once we wire up streaming in Remix\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here\n if (pendingError) {\n errors = pendingError;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map<string, DeferredData>\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let [key, , match] = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n throw new Error(\"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n throw new Error(\"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[]\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n matches.forEach((match) => {\n let id = match.route.id;\n if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {\n mergedLoaderData[id] = loaderData[id];\n }\n });\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getNotFoundMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n error: ErrorResponse;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find(\n (r) => r.index || r.path === \"\" || r.path === \"/\"\n ) || {\n id: \"__shim-404-route__\",\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n error: new ErrorResponse(404, \"Not Found\", null),\n };\n}\n\nfunction getMethodNotAllowedResult(path: Location | string): ErrorResult {\n let href = typeof path === \"string\" ? path : createHref(path);\n console.warn(\n \"You're trying to submit to a route that does not have an action. To \" +\n \"fix this, please add an `action` function to the route for \" +\n `[${href}]`\n );\n return {\n type: ResultType.error,\n error: new ErrorResponse(\n 405,\n \"Method Not Allowed\",\n `No action found for [${href}]`\n ),\n };\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results: DataResult[]): RedirectResult | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return result;\n }\n }\n}\n\n// Create an href to represent a \"server\" URL without the hash\nfunction createHref(location: Partial<Path> | Location | URL) {\n return (location.pathname || \"\") + (location.search || \"\");\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n return (\n a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash\n );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n signal: AbortSignal,\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UseMatchesMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id] as unknown,\n handle: route.handle as unknown,\n };\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n !hasNakedIndexQuery(search || \"\")\n ) {\n return matches.slice(-2)[0];\n }\n return matches.slice(-1)[0];\n}\n\nfunction createURL(location: Location | string): URL {\n let base =\n typeof window !== \"undefined\" && typeof window.location !== \"undefined\"\n ? window.location.origin\n : \"unknown://unknown\";\n let href = typeof location === \"string\" ? location : createHref(location);\n return new URL(href, base);\n}\n//#endregion\n"]},"metadata":{},"sourceType":"module"}