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,IACA,CAACoK,EAASja,IAEb+iB,EAAAA,WAAgB,KACQ,YAAlB9I,EAAQ7d,OAAwB85B,GAClCjc,EAAQpK,OACT,GACA,CAACoK,EAASic,GACf,CAYA,SAAS7E,GACPr0B,EACA4X,QAAA,IAAAA,IAAAA,EAA2C,CAAC,GAE5C,IAAI+Z,EAAY5L,EAAAA,WAAiBoL,IAGlB,MAAbQ,GADFjL,GAAU,GAMV,IAAI,SAAEzgB,GAAaqhB,GACjBC,GAAe8M,wBAEbvzB,EAAO8lB,GAAgB5mB,EAAI,CAAE4e,SAAUhH,EAAKgH,WAChD,IAAK+S,EAAUP,gBACb,OAAO,EAGT,IAAIjO,EACFjd,EAAcyrB,EAAUpa,gBAAgBnX,SAAU6F,IAClD0rB,EAAUpa,gBAAgBnX,SACxBk5B,EACFpzB,EAAcyrB,EAAUvwB,aAAahB,SAAU6F,IAC/C0rB,EAAUvwB,aAAahB,SAezB,OACwC,MAAtC+J,EAAUrJ,EAAKV,SAAUk5B,IACgB,MAAzCnvB,EAAUrJ,EAAKV,SAAU+iB,EAE7B","sources":["../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","../node_modules/react-router/index.ts","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx"],"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// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\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<State = any> extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\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 * The delta between this location and the former location in the history stack\n */\n delta: number | null;\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`. This may be either a URL or the pieces\n * of a 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 * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\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 idx: number;\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 function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\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,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\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, delta: 1 });\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, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\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\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\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\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\nexport function 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, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\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 let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\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 index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\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 // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\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: history.location, delta: 1 });\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 index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\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 createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\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 { invariant, parsePath, warning } 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 statusCode?: number;\n headers?: Headers;\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 reloadDocument?: 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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\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<Context> {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction<Context = any> {\n (args: LoaderFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n (args: ActionFunctionArgs<Context>):\n | Promise<DataFunctionValue>\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\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 text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\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: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\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 lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\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\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\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 `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\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 you 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 mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\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 !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\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/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>(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\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 let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta<RouteObjectType> = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\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({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\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/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n originalPath: Path,\n params: {\n [key in PathParam<Path>]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\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 path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam<Path>;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam<Path>];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\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/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 safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/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 *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\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 pendingKeysSet: Set<string> = new Set<string>();\n private controller: AbortController;\n private abortPromise: Promise<void>;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record<string, unknown>;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\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 if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise<unknown> | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.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, undefined, 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,\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.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(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.pendingKeysSet.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 get pendingKeys() {\n return Array.from(this.pendingKeysSet);\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 type DeferFunction = (\n data: Record<string, unknown>,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\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 * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\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 * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\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): Promise<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 | null, opts?: RouterNavigateOptions): Promise<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 | null,\n opts?: RouterFetchOptions\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 * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\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 * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): 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 * Map of current blockers\n */\n blockers: Map<string, Blocker>;\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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_normalizeFormMethod: boolean;\n v7_prependBasename: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial<FutureConfig>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\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 activeDeferreds: Record<string, DeferredData> | null;\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(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise<StaticHandlerContext | Response>;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n }\n ): void;\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: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\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 json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\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 text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher<TData = any> =\n FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\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 json: undefined,\n text: 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 json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\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 const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_normalizeFormMethod: false,\n v7_prependBasename: false,\n ...init.future,\n };\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 // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\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 error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some((m) => m.route.lazy) &&\n // And we have to either have no loaders or have been provided hydrationData\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 // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : 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 blockers: 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\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map<string, Set<string>> = new Map<\n string,\n Set<string>\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\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\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\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map<string, AbortController>();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\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\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map<string, number>();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set<string>();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\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 // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map<string, BlockerFunction>();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\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, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\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 if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(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(\n newState: Partial<RouterState>,\n viewTransitionOpts?: ViewTransitionOpts\n ): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) =>\n subscriber(state, { unstable_viewTransitionOpts: viewTransitionOpts })\n );\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 mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\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 let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set<string>([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n viewTransitionOpts\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = 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 | null,\n opts?: RouterNavigateOptions\n ): Promise<void> {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\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 enableViewTransition: opts && opts.unstable_viewTransition,\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 fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: 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 pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\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 and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\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 (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\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 loadingNavigation = getLoadingNavigation(location, opts.submission);\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\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.fetcherSubmission,\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 ...(pendingActionData ? { actionData: pendingActionData } : {}),\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 = getSubmittingNavigation(location, submission);\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 && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\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 // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 fetcherSubmission?: 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 =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\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 pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\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((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState({\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n 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 if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { 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 let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\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 | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\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 routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath })\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error);\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, 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, { routeId, path });\n handleFetcherLoader(key, routeId, path, match, matches, submission);\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 requestMatches: AgnosticDataRouteMatch[],\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\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 = getSubmittingFetcher(submission, existingFetcher);\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 = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename\n );\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 if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n let doneFetcher = getDoneFetcher(undefined);\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n return;\n } else {\n fetchRedirectIds.add(key);\n let loadingFetcher = getLoadingFetcher(submission);\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\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 throw getInternalRouterError(400, { type: \"defer-action\" });\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 = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, 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 = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\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((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\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 // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\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(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\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 matches: AgnosticDataRouteMatch[],\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher = getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\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 = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n // Deferred isn't supported for 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 our 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 if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n let doneFetcher = getDoneFetcher(undefined);\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\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 = getDoneFetcher(result.data);\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 state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\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\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: 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((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\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 loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\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 let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\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 = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\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 updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\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 getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise<StaticHandlerContext | Response> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\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, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise<any> {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\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 if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, 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 let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\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 activeDeferreds: null,\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(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\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 // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\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 requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map<string, DeferredData>();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set<string>(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\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\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId != null && relative !== \"path\") {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route. When using relative:path,\n // fromRouteId is ignored since that is always relative to the current\n // location path\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getPathContributingMatches(contextualMatches).map((m) => m.pathnameBase),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\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 normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\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 history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n fetchLoadMatches: Map<string, FetchLoadMatch>,\n fetchRedirectIds: Set<string>,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\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\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (match.route.loader == null) {\n return false;\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for 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 let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (!matches.some((m) => m.route.id === f.routeId)) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\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 != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record<string, any> = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise<DataResult> {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\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 onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\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 ErrorResponseImpl(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 (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\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 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\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\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\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 {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\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. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\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, controller } = 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 (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else 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 invariant(false, \"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 invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\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 errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\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 getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\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\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\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 // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\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 let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\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\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 the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map<string, Set<string>>\n) {\n if (transitions.size > 0) {\n let json: Record<string, string[]> = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n","import * as React from \"react\";\nimport type {\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n AgnosticRouteMatch,\n History,\n LazyRouteFunction,\n Location,\n Action as NavigationType,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject extends NavigationContextObject {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n","import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n IDLE_BLOCKER,\n Action as NavigationType,\n UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteMatch,\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a <Router> component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a <Router> component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey<Path>,\n Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a <Router> component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath<ParamKey, Path>(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a <Router> component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial<Location> | string,\n dataRouterState?: RemixRouter[\"state\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a <Router> component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname =\n parentPathnameBase === \"/\"\n ? pathname\n : pathname.slice(parentPathnameBase.length) || \"/\";\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n <LocationContext.Provider\n value={{\n location: {\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\",\n ...location,\n },\n navigationType: NavigationType.Pop,\n }}\n >\n {renderedMatches}\n </LocationContext.Provider>\n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n <p>💿 Hey developer 👋</p>\n <p>\n You can provide a way better UX than this when your app throws errors\n by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n <code style={codeStyles}>errorElement</code> prop on your route.\n </p>\n </>\n );\n }\n\n return (\n <>\n <h2>Unexpected Application Error!</h2>\n <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n {stack ? <pre style={preStyles}>{stack}</pre> : null}\n {devInfo}\n </>\n );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error || state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error ? (\n <RouteContext.Provider value={this.props.routeContext}>\n <RouteErrorContext.Provider\n value={this.state.error}\n children={this.props.component}\n />\n </RouteContext.Provider>\n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch<string, RouteObject>;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n <RouteContext.Provider value={routeContext}>\n {children}\n </RouteContext.Provider>\n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors?.[match.route.id] : null;\n // Only data routers handle errors\n let errorElement: React.ReactNode | null = null;\n if (dataRouterState) {\n errorElement = match.route.errorElement || defaultErrorElement;\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = <match.route.Component />;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n <RenderedRoute\n match={match}\n routeContext={{\n outlet,\n matches,\n isDataRoute: dataRouterState != null,\n }}\n children={children}\n />\n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n <RenderErrorBoundary\n location={dataRouterState.location}\n revalidation={dataRouterState.revalidation}\n component={errorElement}\n error={error}\n children={getChildren()}\n routeContext={{ outlet: null, matches, isDataRoute: true }}\n />\n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(\n () => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n }),\n [dataRouterContext.router.revalidate, state.revalidation]\n );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n\n let route = React.useContext(RouteContext);\n invariant(route, `useActionData must be used inside a RouteContext`);\n\n return Object.values(state?.actionData || {})[0];\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback<BlockerFunction>(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n","import type {\n InitialEntry,\n LazyRouteFunction,\n Location,\n MemoryHistory,\n RelativeRoutingType,\n Router as RemixRouter,\n RouterState,\n RouterSubscriber,\n To,\n TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./context\";\nimport {\n AwaitContext,\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./context\";\nimport {\n _renderMatches,\n useAsyncValue,\n useInRouterContext,\n useLocation,\n useNavigate,\n useOutlet,\n useRoutes,\n useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n future?: Partial<FutureConfig>;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n\n let setState = React.useCallback<RouterSubscriber>(\n (newState: RouterState) => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n },\n [setStateImpl, v7_startTransition]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface MemoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n future?: FutureConfig;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nexport function MemoryRouter({\n basename,\n children,\n initialEntries,\n initialIndex,\n future,\n}: MemoryRouterProps): React.ReactElement {\n let historyRef = React.useRef<MemoryHistory>();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true,\n });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface NavigateProps {\n to: To;\n replace?: boolean;\n state?: any;\n relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nexport function Navigate({\n to,\n replace,\n state,\n relative,\n}: NavigateProps): null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n `<Navigate> may be used only in the context of a <Router> component.`\n );\n\n warning(\n !React.useContext(NavigationContext).static,\n `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n `This is a no-op, but you should modify your code so the <Navigate> is ` +\n `only ever rendered in response to some user interaction or state change.`\n );\n\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(\n to,\n getPathContributingMatches(matches).map((match) => match.pathnameBase),\n locationPathname,\n relative === \"path\"\n );\n let jsonPath = JSON.stringify(path);\n\n React.useEffect(\n () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n [navigate, jsonPath, relative, replace, state]\n );\n\n return null;\n}\n\nexport interface OutletProps {\n context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n path?: NonIndexRouteObject[\"path\"];\n id?: NonIndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<NonIndexRouteObject>;\n loader?: NonIndexRouteObject[\"loader\"];\n action?: NonIndexRouteObject[\"action\"];\n hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n handle?: NonIndexRouteObject[\"handle\"];\n index?: false;\n children?: React.ReactNode;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n path?: IndexRouteObject[\"path\"];\n id?: IndexRouteObject[\"id\"];\n lazy?: LazyRouteFunction<IndexRouteObject>;\n loader?: IndexRouteObject[\"loader\"];\n action?: IndexRouteObject[\"action\"];\n hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n handle?: IndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n invariant(\n false,\n `A <Route> is only ever to be used as the child of <Routes> element, ` +\n `never rendered directly. Please wrap your <Route> in a <Routes>.`\n );\n}\n\nexport interface RouterProps {\n basename?: string;\n children?: React.ReactNode;\n location: Partial<Location> | string;\n navigationType?: NavigationType;\n navigator: Navigator;\n static?: boolean;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nexport function Router({\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = NavigationType.Pop,\n navigator,\n static: staticProp = false,\n}: RouterProps): React.ReactElement | null {\n invariant(\n !useInRouterContext(),\n `You cannot render a <Router> inside another <Router>.` +\n ` You should never have more than one in your app.`\n );\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(\n () => ({ basename, navigator, static: staticProp }),\n [basename, navigator, staticProp]\n );\n\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\",\n } = locationProp;\n\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n\n if (trailingPathname == null) {\n return null;\n }\n\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key,\n },\n navigationType,\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n\n warning(\n locationContext != null,\n `<Router basename=\"${basename}\"> is not able to match the URL ` +\n `\"${pathname}${search}${hash}\" because it does not start with the ` +\n `basename, so the <Router> won't render anything.`\n );\n\n if (locationContext == null) {\n return null;\n }\n\n return (\n <NavigationContext.Provider value={navigationContext}>\n <LocationContext.Provider children={children} value={locationContext} />\n </NavigationContext.Provider>\n );\n}\n\nexport interface RoutesProps {\n children?: React.ReactNode;\n location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nexport function Routes({\n children,\n location,\n}: RoutesProps): React.ReactElement | null {\n return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n children: React.ReactNode | AwaitResolveRenderFunction;\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n return (\n <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n <ResolveAwait>{children}</ResolveAwait>\n </AwaitErrorBoundary>\n );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n errorElement?: React.ReactNode;\n resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n error: any;\n};\n\nenum AwaitRenderStatus {\n pending,\n success,\n error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n AwaitErrorBoundaryProps,\n AwaitErrorBoundaryState\n> {\n constructor(props: AwaitErrorBoundaryProps) {\n super(props);\n this.state = { error: null };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"<Await> caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n let { children, errorElement, resolve } = this.props;\n\n let promise: TrackedPromise | null = null;\n let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_data\", { get: () => resolve });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n Object.defineProperty(promise, \"_error\", { get: () => renderError });\n } else if ((resolve as TrackedPromise)._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status =\n promise._error !== undefined\n ? AwaitRenderStatus.error\n : promise._data !== undefined\n ? AwaitRenderStatus.success\n : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n promise = resolve.then(\n (data: any) =>\n Object.defineProperty(resolve, \"_data\", { get: () => data }),\n (error: any) =>\n Object.defineProperty(resolve, \"_error\", { get: () => error })\n );\n }\n\n if (\n status === AwaitRenderStatus.error &&\n promise._error instanceof AbortedDeferredError\n ) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return <AwaitContext.Provider value={promise} children={errorElement} />;\n }\n\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return <AwaitContext.Provider value={promise} children={children} />;\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n children,\n}: {\n children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n children: React.ReactNode,\n parentPath: number[] = []\n): RouteObject[] {\n let routes: RouteObject[] = [];\n\n React.Children.forEach(children, (element, index) => {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n\n let treePath = [...parentPath, index];\n\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(\n routes,\n createRoutesFromChildren(element.props.children, treePath)\n );\n return;\n }\n\n invariant(\n element.type === Route,\n `[${\n typeof element.type === \"string\" ? element.type : element.type.name\n }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n );\n\n invariant(\n !element.props.index || !element.props.children,\n \"An index route cannot have child routes.\"\n );\n\n let route: RouteObject = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary:\n element.props.ErrorBoundary != null ||\n element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy,\n };\n\n if (element.props.children) {\n route.children = createRoutesFromChildren(\n element.props.children,\n treePath\n );\n }\n\n routes.push(route);\n });\n\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n matches: RouteMatch[] | null\n): React.ReactElement | null {\n return _renderMatches(matches);\n}\n","import * as React from \"react\";\nimport type {\n ActionFunction,\n ActionFunctionArgs,\n Blocker,\n BlockerFunction,\n ErrorResponse,\n Fetcher,\n HydrationState,\n InitialEntry,\n JsonFunction,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n Navigation,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RedirectFunction,\n RelativeRoutingType,\n Router as RemixRouter,\n FutureConfig as RouterFutureConfig,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"@remix-run/router\";\nimport {\n AbortedDeferredError,\n Action as NavigationType,\n createMemoryHistory,\n createPath,\n createRouter,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n resolvePath,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n AwaitProps,\n FutureConfig,\n IndexRouteProps,\n LayoutRouteProps,\n MemoryRouterProps,\n NavigateProps,\n OutletProps,\n PathRouteProps,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n} from \"./lib/components\";\nimport {\n Await,\n MemoryRouter,\n Navigate,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createRoutesFromChildren,\n renderMatches,\n} from \"./lib/components\";\nimport type {\n DataRouteMatch,\n DataRouteObject,\n IndexRouteObject,\n NavigateOptions,\n Navigator,\n NonIndexRouteObject,\n RouteMatch,\n RouteObject,\n} from \"./lib/context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n useActionData,\n useAsyncError,\n useAsyncValue,\n useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteId,\n useRouteLoaderData,\n useRoutes,\n useRoutesImpl,\n} from \"./lib/hooks\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n DataRouteMatch,\n DataRouteObject,\n ErrorResponse,\n Fetcher,\n FutureConfig,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LayoutRouteProps,\n LazyRouteFunction,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n PathRouteProps,\n Pathname,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n Blocker as unstable_Blocker,\n BlockerFunction as unstable_BlockerFunction,\n};\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n RouterProvider,\n Routes,\n createPath,\n createRoutesFromChildren,\n createRoutesFromChildren as createRoutesFromElements,\n defer,\n generatePath,\n isRouteErrorResponse,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n renderMatches,\n resolvePath,\n useBlocker as unstable_useBlocker,\n useActionData,\n useAsyncError,\n useAsyncValue,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n};\n\nfunction mapRouteProperties(route: RouteObject) {\n let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this -- please and thank you!\n hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n };\n\n if (route.Component) {\n if (__DEV__) {\n if (route.element) {\n warning(\n false,\n \"You should not include both `Component` and `element` on your route - \" +\n \"`Component` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n element: React.createElement(route.Component),\n Component: undefined,\n });\n }\n\n if (route.ErrorBoundary) {\n if (__DEV__) {\n if (route.errorElement) {\n warning(\n false,\n \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n \"`ErrorBoundary` will be used.\"\n );\n }\n }\n Object.assign(updates, {\n errorElement: React.createElement(route.ErrorBoundary),\n ErrorBoundary: undefined,\n });\n }\n\n return updates;\n}\n\nexport function createMemoryRouter(\n routes: RouteObject[],\n opts?: {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n }\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createMemoryHistory({\n initialEntries: opts?.initialEntries,\n initialIndex: opts?.initialIndex,\n }),\n hydrationData: opts?.hydrationData,\n routes,\n mapRouteProperties,\n }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n DataRouterContext as UNSAFE_DataRouterContext,\n DataRouterStateContext as UNSAFE_DataRouterStateContext,\n LocationContext as UNSAFE_LocationContext,\n NavigationContext as UNSAFE_NavigationContext,\n RouteContext as UNSAFE_RouteContext,\n mapRouteProperties as UNSAFE_mapRouteProperties,\n useRouteId as UNSAFE_useRouteId,\n useRoutesImpl as UNSAFE_useRoutesImpl,\n};\n","import type {\n FormEncType,\n HTMLFormMethod,\n RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n MouseEvent,\n \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n event: LimitedMouseEvent,\n target?: string\n) {\n return (\n event.button === 0 && // Ignore everything but left clicks\n (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // Ignore clicks with modifier keys\n );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n | string\n | ParamKeyValuePair[]\n | Record<string, string | string[]>\n | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n * let searchParams = new URLSearchParams([\n * ['sort', 'name'],\n * ['sort', 'price']\n * ]);\n *\n * you can do:\n *\n * let searchParams = createSearchParams({\n * sort: ['name', 'price']\n * });\n */\nexport function createSearchParams(\n init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n return new URLSearchParams(\n typeof init === \"string\" ||\n Array.isArray(init) ||\n init instanceof URLSearchParams\n ? init\n : Object.keys(init).reduce((memo, key) => {\n let value = init[key];\n return memo.concat(\n Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n );\n }, [] as ParamKeyValuePair[])\n );\n}\n\nexport function getSearchParamsForLocation(\n locationSearch: string,\n defaultSearchParams: URLSearchParams | null\n) {\n let searchParams = createSearchParams(locationSearch);\n\n if (defaultSearchParams) {\n // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n // web extensions. Relevant Bugzilla tickets:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n defaultSearchParams.forEach((_, key) => {\n if (!searchParams.has(key)) {\n defaultSearchParams.getAll(key).forEach((value) => {\n searchParams.append(key, value);\n });\n }\n });\n }\n\n return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n | HTMLFormElement\n | HTMLButtonElement\n | HTMLInputElement\n | FormData\n | URLSearchParams\n | JsonValue\n | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n if (_formDataSupportsSubmitter === null) {\n try {\n new FormData(\n document.createElement(\"form\"),\n // @ts-expect-error if FormData supports the submitter parameter, this will throw\n 0\n );\n _formDataSupportsSubmitter = false;\n } catch (e) {\n _formDataSupportsSubmitter = true;\n }\n }\n return _formDataSupportsSubmitter;\n}\n\nexport interface SubmitOptions {\n /**\n * The HTTP method used to submit the form. Overrides `<form method>`.\n * Defaults to \"GET\".\n */\n method?: HTMLFormMethod;\n\n /**\n * The action URL path used to submit the form. Overrides `<form action>`.\n * Defaults to the path of the current route.\n */\n action?: string;\n\n /**\n * The encoding used to submit the form. Overrides `<form encType>`.\n * Defaults to \"application/x-www-form-urlencoded\".\n */\n encType?: FormEncType;\n\n /**\n * Set `true` to replace the current entry in the browser's history stack\n * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n * to `false`.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * In browser-based environments, prevent resetting scroll after this\n * navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * Enable view transitions on this submission navigation\n */\n unstable_viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n warning(\n false,\n `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n `and will default to \"${defaultEncType}\"`\n );\n\n return null;\n }\n return encType;\n}\n\nexport function getFormSubmissionInfo(\n target: SubmitTarget,\n basename: string\n): {\n action: string | null;\n method: string;\n encType: string;\n formData: FormData | undefined;\n body: any;\n} {\n let method: string;\n let action: string | null;\n let encType: string;\n let formData: FormData | undefined;\n let body: any;\n\n if (isFormElement(target)) {\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n formData = new FormData(target);\n } else if (\n isButtonElement(target) ||\n (isInputElement(target) &&\n (target.type === \"submit\" || target.type === \"image\"))\n ) {\n let form = target.form;\n\n if (form == null) {\n throw new Error(\n `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n );\n }\n\n // <button>/<input type=\"submit\"> may override attributes of <form>\n\n // When grabbing the action from the element, it will have had the basename\n // prefixed to ensure non-JS scenarios work, so strip it since we'll\n // re-prefix in the router\n let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n\n method =\n target.getAttribute(\"formmethod\") ||\n form.getAttribute(\"method\") ||\n defaultMethod;\n encType =\n getFormEncType(target.getAttribute(\"formenctype\")) ||\n getFormEncType(form.getAttribute(\"enctype\")) ||\n defaultEncType;\n\n // Build a FormData object populated from a form and submitter\n formData = new FormData(form, target);\n\n // If this browser doesn't support the `FormData(el, submitter)` format,\n // then tack on the submitter value at the end. This is a lightweight\n // solution that is not 100% spec compliant. For complete support in older\n // browsers, consider using the `formdata-submitter-polyfill` package\n if (!isFormDataSubmitterSupported()) {\n let { name, type, value } = target;\n if (type === \"image\") {\n let prefix = name ? `${name}.` : \"\";\n formData.append(`${prefix}x`, \"0\");\n formData.append(`${prefix}y`, \"0\");\n } else if (name) {\n formData.append(name, value);\n }\n }\n } else if (isHtmlElement(target)) {\n throw new Error(\n `Cannot submit element that is not <form>, <button>, or ` +\n `<input type=\"submit|image\">`\n );\n } else {\n method = defaultMethod;\n action = null;\n encType = defaultEncType;\n body = target;\n }\n\n // Send body for <Form encType=\"text/plain\" so we encode it into text\n if (formData && encType === \"text/plain\") {\n body = formData;\n formData = undefined;\n }\n\n return { action, method: method.toLowerCase(), encType, formData, body };\n}\n","/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport type {\n DataRouteObject,\n FutureConfig,\n Location,\n NavigateOptions,\n NavigationType,\n Navigator,\n RelativeRoutingType,\n RouteObject,\n RouterProviderProps,\n To,\n} from \"react-router\";\nimport {\n Router,\n createPath,\n useHref,\n useLocation,\n useMatches,\n useNavigate,\n useNavigation,\n useResolvedPath,\n unstable_useBlocker as useBlocker,\n UNSAFE_DataRouterContext as DataRouterContext,\n UNSAFE_DataRouterStateContext as DataRouterStateContext,\n UNSAFE_NavigationContext as NavigationContext,\n UNSAFE_RouteContext as RouteContext,\n UNSAFE_mapRouteProperties as mapRouteProperties,\n UNSAFE_useRouteId as useRouteId,\n UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n BrowserHistory,\n Fetcher,\n FormEncType,\n FormMethod,\n FutureConfig as RouterFutureConfig,\n GetScrollRestorationKeyFunction,\n HashHistory,\n History,\n HTMLFormMethod,\n HydrationState,\n Router as RemixRouter,\n V7_FormMethod,\n RouterState,\n RouterSubscriber,\n} from \"@remix-run/router\";\nimport {\n createRouter,\n createBrowserHistory,\n createHashHistory,\n joinPaths,\n stripBasename,\n UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n UNSAFE_invariant as invariant,\n UNSAFE_warning as warning,\n matchPath,\n} from \"@remix-run/router\";\n\nimport type {\n SubmitOptions,\n ParamKeyValuePair,\n URLSearchParamsInit,\n SubmitTarget,\n} from \"./dom\";\nimport {\n createSearchParams,\n defaultMethod,\n getFormSubmissionInfo,\n getSearchParamsForLocation,\n shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n FormEncType,\n FormMethod,\n GetScrollRestorationKeyFunction,\n ParamKeyValuePair,\n SubmitOptions,\n URLSearchParamsInit,\n V7_FormMethod,\n};\nexport { createSearchParams };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n ActionFunction,\n ActionFunctionArgs,\n AwaitProps,\n unstable_Blocker,\n unstable_BlockerFunction,\n DataRouteMatch,\n DataRouteObject,\n ErrorResponse,\n Fetcher,\n Hash,\n IndexRouteObject,\n IndexRouteProps,\n JsonFunction,\n LazyRouteFunction,\n LayoutRouteProps,\n LoaderFunction,\n LoaderFunctionArgs,\n Location,\n MemoryRouterProps,\n NavigateFunction,\n NavigateOptions,\n NavigateProps,\n Navigation,\n Navigator,\n NonIndexRouteObject,\n OutletProps,\n Params,\n ParamParseKey,\n Path,\n PathMatch,\n Pathname,\n PathPattern,\n PathRouteProps,\n RedirectFunction,\n RelativeRoutingType,\n RouteMatch,\n RouteObject,\n RouteProps,\n RouterProps,\n RouterProviderProps,\n RoutesProps,\n Search,\n ShouldRevalidateFunction,\n ShouldRevalidateFunctionArgs,\n To,\n UIMatch,\n} from \"react-router\";\nexport {\n AbortedDeferredError,\n Await,\n MemoryRouter,\n Navigate,\n NavigationType,\n Outlet,\n Route,\n Router,\n Routes,\n createMemoryRouter,\n createPath,\n createRoutesFromChildren,\n createRoutesFromElements,\n defer,\n isRouteErrorResponse,\n generatePath,\n json,\n matchPath,\n matchRoutes,\n parsePath,\n redirect,\n redirectDocument,\n renderMatches,\n resolvePath,\n useActionData,\n useAsyncError,\n useAsyncValue,\n unstable_useBlocker,\n useHref,\n useInRouterContext,\n useLoaderData,\n useLocation,\n useMatch,\n useMatches,\n useNavigate,\n useNavigation,\n useNavigationType,\n useOutlet,\n useOutletContext,\n useParams,\n useResolvedPath,\n useRevalidator,\n useRouteError,\n useRouteLoaderData,\n useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n UNSAFE_DataRouterContext,\n UNSAFE_DataRouterStateContext,\n UNSAFE_NavigationContext,\n UNSAFE_LocationContext,\n UNSAFE_RouteContext,\n UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n var __staticRouterHydrationData: HydrationState | undefined;\n interface Document {\n startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n basename?: string;\n future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\nexport function createBrowserRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createBrowserHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nexport function createHashRouter(\n routes: RouteObject[],\n opts?: DOMRouterOpts\n): RemixRouter {\n return createRouter({\n basename: opts?.basename,\n future: {\n ...opts?.future,\n v7_prependBasename: true,\n },\n history: createHashHistory({ window: opts?.window }),\n hydrationData: opts?.hydrationData || parseHydrationData(),\n routes,\n mapRouteProperties,\n window: opts?.window,\n }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n let state = window?.__staticRouterHydrationData;\n if (state && state.errors) {\n state = {\n ...state,\n errors: deserializeErrors(state.errors),\n };\n }\n return state;\n}\n\nfunction deserializeErrors(\n errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n if (!errors) return null;\n let entries = Object.entries(errors);\n let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n for (let [key, val] of entries) {\n // Hey you! If you change this, please change the corresponding logic in\n // serializeErrors in react-router-dom/server.tsx :)\n if (val && val.__type === \"RouteErrorResponse\") {\n serialized[key] = new ErrorResponseImpl(\n val.status,\n val.statusText,\n val.data,\n val.internal === true\n );\n } else if (val && val.__type === \"Error\") {\n // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n if (val.__subType) {\n let ErrorConstructor = window[val.__subType];\n if (typeof ErrorConstructor === \"function\") {\n try {\n // @ts-expect-error\n let error = new ErrorConstructor(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n } catch (e) {\n // no-op - fall through and create a normal Error\n }\n }\n }\n\n if (serialized[key] == null) {\n let error = new Error(val.message);\n // Wipe away the client-side stack trace. Nothing to fill it in with\n // because we don't serialize SSR stack traces for security reasons\n error.stack = \"\";\n serialized[key] = error;\n }\n } else {\n serialized[key] = val;\n }\n }\n return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n | {\n isTransitioning: false;\n }\n | {\n isTransitioning: true;\n currentLocation: Location;\n nextLocation: Location;\n };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n isTransitioning: false,\n});\nif (__DEV__) {\n ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\nfunction startTransitionSafe(cb: () => void) {\n if (startTransitionImpl) {\n startTransitionImpl(cb);\n } else {\n cb();\n }\n}\n\ninterface ViewTransition {\n finished: Promise<void>;\n ready: Promise<void>;\n updateCallbackDone: Promise<void>;\n skipTransition(): void;\n}\n\nclass Deferred<T> {\n status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n promise: Promise<T>;\n // @ts-expect-error - no initializer\n resolve: (value: T) => void;\n // @ts-expect-error - no initializer\n reject: (reason?: unknown) => void;\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (value) => {\n if (this.status === \"pending\") {\n this.status = \"resolved\";\n resolve(value);\n }\n };\n this.reject = (reason) => {\n if (this.status === \"pending\") {\n this.status = \"rejected\";\n reject(reason);\n }\n };\n });\n }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n let [state, setStateImpl] = React.useState(router.state);\n let [pendingState, setPendingState] = React.useState<RouterState>();\n let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n isTransitioning: false,\n });\n let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n let [transition, setTransition] = React.useState<ViewTransition>();\n let [interruption, setInterruption] = React.useState<{\n state: RouterState;\n currentLocation: Location;\n nextLocation: Location;\n }>();\n let { v7_startTransition } = future || {};\n\n let optInStartTransition = React.useCallback(\n (cb: () => void) => {\n if (v7_startTransition) {\n startTransitionSafe(cb);\n } else {\n cb();\n }\n },\n [v7_startTransition]\n );\n\n let setState = React.useCallback<RouterSubscriber>(\n (\n newState: RouterState,\n { unstable_viewTransitionOpts: viewTransitionOpts }\n ) => {\n if (\n !viewTransitionOpts ||\n router.window == null ||\n typeof router.window.document.startViewTransition !== \"function\"\n ) {\n // Mid-navigation state update, or startViewTransition isn't available\n optInStartTransition(() => setStateImpl(newState));\n } else if (transition && renderDfd) {\n // Interrupting an in-progress transition, cancel and let everything flush\n // out, and then kick off a new transition from the interruption state\n renderDfd.resolve();\n transition.skipTransition();\n setInterruption({\n state: newState,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n } else {\n // Completed navigation update with opted-in view transitions, let 'er rip\n setPendingState(newState);\n setVtContext({\n isTransitioning: true,\n currentLocation: viewTransitionOpts.currentLocation,\n nextLocation: viewTransitionOpts.nextLocation,\n });\n }\n },\n [optInStartTransition, transition, renderDfd, router.window]\n );\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n // When we start a view transition, create a Deferred we can use for the\n // eventual \"completed\" render\n React.useEffect(() => {\n if (vtContext.isTransitioning) {\n setRenderDfd(new Deferred<void>());\n }\n }, [vtContext.isTransitioning]);\n\n // Once the deferred is created, kick off startViewTransition() to update the\n // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n // happened)\n React.useEffect(() => {\n if (renderDfd && pendingState && router.window) {\n let newState = pendingState;\n let renderPromise = renderDfd.promise;\n let transition = router.window.document.startViewTransition(async () => {\n optInStartTransition(() => setStateImpl(newState));\n await renderPromise;\n });\n transition.finished.finally(() => {\n setRenderDfd(undefined);\n setTransition(undefined);\n setPendingState(undefined);\n setVtContext({ isTransitioning: false });\n });\n setTransition(transition);\n }\n }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n // When the new location finally renders and is committed to the DOM, this\n // effect will run to resolve the transition\n React.useEffect(() => {\n if (\n renderDfd &&\n pendingState &&\n state.location.key === pendingState.location.key\n ) {\n renderDfd.resolve();\n }\n }, [renderDfd, transition, state.location, pendingState]);\n\n // If we get interrupted with a new navigation during a transition, we skip\n // the active transition, let it cleanup, then kick it off again here\n React.useEffect(() => {\n if (!vtContext.isTransitioning && interruption) {\n setPendingState(interruption.state);\n setVtContext({\n isTransitioning: true,\n currentLocation: interruption.currentLocation,\n nextLocation: interruption.nextLocation,\n });\n setInterruption(undefined);\n }\n }, [vtContext.isTransitioning, interruption]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return (\n <>\n <DataRouterContext.Provider value={dataRouterContext}>\n <DataRouterStateContext.Provider value={state}>\n <ViewTransitionContext.Provider value={vtContext}>\n <Router\n basename={basename}\n location={state.location}\n navigationType={state.historyAction}\n navigator={navigator}\n >\n {state.initialized ? (\n <DataRoutes routes={router.routes} state={state} />\n ) : (\n fallbackElement\n )}\n </Router>\n </ViewTransitionContext.Provider>\n </DataRouterStateContext.Provider>\n </DataRouterContext.Provider>\n {null}\n </>\n );\n}\n\nfunction DataRoutes({\n routes,\n state,\n}: {\n routes: DataRouteObject[];\n state: RouterState;\n}): React.ReactElement | null {\n return useRoutesImpl(routes, undefined, state);\n}\n\nexport interface BrowserRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n basename,\n children,\n future,\n window,\n}: BrowserRouterProps) {\n let historyRef = React.useRef<BrowserHistory>();\n if (historyRef.current == null) {\n historyRef.current = createBrowserHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HashRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n basename,\n children,\n future,\n window,\n}: HashRouterProps) {\n let historyRef = React.useRef<HashHistory>();\n if (historyRef.current == null) {\n historyRef.current = createHashHistory({ window, v5Compat: true });\n }\n\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nexport interface HistoryRouterProps {\n basename?: string;\n children?: React.ReactNode;\n future?: FutureConfig;\n history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n basename,\n children,\n future,\n history,\n}: HistoryRouterProps) {\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location,\n });\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: { action: NavigationType; location: Location }) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n return (\n <Router\n basename={basename}\n children={children}\n location={state.location}\n navigationType={state.action}\n navigator={history}\n />\n );\n}\n\nif (__DEV__) {\n HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n reloadDocument?: boolean;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n to: To;\n unstable_viewTransition?: boolean;\n}\n\nconst isBrowser =\n typeof window !== \"undefined\" &&\n typeof window.document !== \"undefined\" &&\n typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n function LinkWithRef(\n {\n onClick,\n relative,\n reloadDocument,\n replace,\n state,\n target,\n to,\n preventScrollReset,\n unstable_viewTransition,\n ...rest\n },\n ref\n ) {\n let { basename } = React.useContext(NavigationContext);\n\n // Rendered into <a href> for absolute URLs\n let absoluteHref;\n let isExternal = false;\n\n if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n // Render the absolute href server- and client-side\n absoluteHref = to;\n\n // Only check for external origins client-side\n if (isBrowser) {\n try {\n let currentUrl = new URL(window.location.href);\n let targetUrl = to.startsWith(\"//\")\n ? new URL(currentUrl.protocol + to)\n : new URL(to);\n let path = stripBasename(targetUrl.pathname, basename);\n\n if (targetUrl.origin === currentUrl.origin && path != null) {\n // Strip the protocol/origin/basename for same-origin absolute URLs\n to = path + targetUrl.search + targetUrl.hash;\n } else {\n isExternal = true;\n }\n } catch (e) {\n // We can't do external URL detection without a valid URL\n warning(\n false,\n `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n `when clicked - please update to a valid URL path.`\n );\n }\n }\n }\n\n // Rendered into <a href> for relative URLs\n let href = useHref(to, { relative });\n\n let internalOnClick = useLinkClickHandler(to, {\n replace,\n state,\n target,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n function handleClick(\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n ) {\n if (onClick) onClick(event);\n if (!event.defaultPrevented) {\n internalOnClick(event);\n }\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/anchor-has-content\n <a\n {...rest}\n href={absoluteHref || href}\n onClick={isExternal || reloadDocument ? onClick : handleClick}\n ref={ref}\n target={target}\n />\n );\n }\n);\n\nif (__DEV__) {\n Link.displayName = \"Link\";\n}\n\ntype NavLinkRenderProps = {\n isActive: boolean;\n isPending: boolean;\n isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n caseSensitive?: boolean;\n className?: string | ((props: NavLinkRenderProps) => string | undefined);\n end?: boolean;\n style?:\n | React.CSSProperties\n | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n function NavLinkWithRef(\n {\n \"aria-current\": ariaCurrentProp = \"page\",\n caseSensitive = false,\n className: classNameProp = \"\",\n end = false,\n style: styleProp,\n to,\n unstable_viewTransition,\n children,\n ...rest\n },\n ref\n ) {\n let path = useResolvedPath(to, { relative: rest.relative });\n let location = useLocation();\n let routerState = React.useContext(DataRouterStateContext);\n let { navigator } = React.useContext(NavigationContext);\n let isTransitioning =\n routerState != null &&\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useViewTransitionState(path) &&\n unstable_viewTransition === true;\n\n let toPathname = navigator.encodeLocation\n ? navigator.encodeLocation(path).pathname\n : path.pathname;\n let locationPathname = location.pathname;\n let nextLocationPathname =\n routerState && routerState.navigation && routerState.navigation.location\n ? routerState.navigation.location.pathname\n : null;\n\n if (!caseSensitive) {\n locationPathname = locationPathname.toLowerCase();\n nextLocationPathname = nextLocationPathname\n ? nextLocationPathname.toLowerCase()\n : null;\n toPathname = toPathname.toLowerCase();\n }\n\n let isActive =\n locationPathname === toPathname ||\n (!end &&\n locationPathname.startsWith(toPathname) &&\n locationPathname.charAt(toPathname.length) === \"/\");\n\n let isPending =\n nextLocationPathname != null &&\n (nextLocationPathname === toPathname ||\n (!end &&\n nextLocationPathname.startsWith(toPathname) &&\n nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n let renderProps = {\n isActive,\n isPending,\n isTransitioning,\n };\n\n let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n let className: string | undefined;\n if (typeof classNameProp === \"function\") {\n className = classNameProp(renderProps);\n } else {\n // If the className prop is not a function, we use a default `active`\n // class for <NavLink />s that are active. In v5 `active` was the default\n // value for `activeClassName`, but we are removing that API and can still\n // use the old default behavior for a cleaner upgrade path and keep the\n // simple styling rules working as they currently do.\n className = [\n classNameProp,\n isActive ? \"active\" : null,\n isPending ? \"pending\" : null,\n isTransitioning ? \"transitioning\" : null,\n ]\n .filter(Boolean)\n .join(\" \");\n }\n\n let style =\n typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n return (\n <Link\n {...rest}\n aria-current={ariaCurrent}\n className={className}\n ref={ref}\n style={style}\n to={to}\n unstable_viewTransition={unstable_viewTransition}\n >\n {typeof children === \"function\" ? children(renderProps) : children}\n </Link>\n );\n }\n);\n\nif (__DEV__) {\n NavLink.displayName = \"NavLink\";\n}\n\nexport interface FetcherFormProps\n extends React.FormHTMLAttributes<HTMLFormElement> {\n /**\n * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n * \"put\", \"delete\", \"patch\".\n */\n method?: HTMLFormMethod;\n\n /**\n * `<form encType>` - enhancing beyond the normal string type and limiting\n * to the built-in browser supported values\n */\n encType?:\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"text/plain\";\n\n /**\n * Normal `<form action>` but supports React Router's relative paths.\n */\n action?: string;\n\n /**\n * Determines whether the form action is relative to the route hierarchy or\n * the pathname. Use this if you want to opt out of navigating the route\n * hierarchy and want to instead route based on /-delimited URL segments\n */\n relative?: RelativeRoutingType;\n\n /**\n * Prevent the scroll position from resetting to the top of the viewport on\n * completion of the navigation when using the <ScrollRestoration> component\n */\n preventScrollReset?: boolean;\n\n /**\n * A function to call when the form is submitted. If you call\n * `event.preventDefault()` then this form will not do anything.\n */\n onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\nexport interface FormProps extends FetcherFormProps {\n /**\n * Forces a full document navigation instead of a fetch.\n */\n reloadDocument?: boolean;\n\n /**\n * Replaces the current entry in the browser history stack when the form\n * navigates. Use this if you don't want the user to be able to click \"back\"\n * to the page with the form on it.\n */\n replace?: boolean;\n\n /**\n * State object to add to the history stack entry for this navigation\n */\n state?: any;\n\n /**\n * Enable view transitions on this Form navigation\n */\n unstable_viewTransition?: boolean;\n}\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n (props, ref) => {\n let submit = useSubmit();\n return <FormImpl {...props} submit={submit} ref={ref} />;\n }\n);\n\nif (__DEV__) {\n Form.displayName = \"Form\";\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n SubmitEvent,\n Event,\n HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\ninterface FormImplProps extends FormProps {\n submit: SubmitFunction | FetcherSubmitFunction;\n}\n\nconst FormImpl = React.forwardRef<HTMLFormElement, FormImplProps>(\n (\n {\n reloadDocument,\n replace,\n state,\n method = defaultMethod,\n action,\n onSubmit,\n submit,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n ...props\n },\n forwardedRef\n ) => {\n let formMethod: HTMLFormMethod =\n method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n let formAction = useFormAction(action, { relative });\n let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n onSubmit && onSubmit(event);\n if (event.defaultPrevented) return;\n event.preventDefault();\n\n let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n .submitter as HTMLFormSubmitter | null;\n\n let submitMethod =\n (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n method;\n\n submit(submitter || event.currentTarget, {\n method: submitMethod,\n replace,\n state,\n relative,\n preventScrollReset,\n unstable_viewTransition,\n });\n };\n\n return (\n <form\n ref={forwardedRef}\n method={formMethod}\n action={formAction}\n onSubmit={reloadDocument ? onSubmit : submitHandler}\n {...props}\n />\n );\n }\n);\n\nif (__DEV__) {\n FormImpl.displayName = \"FormImpl\";\n}\n\nexport interface ScrollRestorationProps {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n getKey,\n storageKey,\n}: ScrollRestorationProps) {\n useScrollRestoration({ getKey, storageKey });\n return null;\n}\n\nif (__DEV__) {\n ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n UseScrollRestoration = \"useScrollRestoration\",\n UseSubmit = \"useSubmit\",\n UseSubmitFetcher = \"useSubmitFetcher\",\n UseFetcher = \"useFetcher\",\n useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n UseFetchers = \"useFetchers\",\n UseScrollRestoration = \"useScrollRestoration\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n to: To,\n {\n target,\n replace: replaceProp,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n }: {\n target?: React.HTMLAttributeAnchorTarget;\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_viewTransition?: boolean;\n } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n let navigate = useNavigate();\n let location = useLocation();\n let path = useResolvedPath(to, { relative });\n\n return React.useCallback(\n (event: React.MouseEvent<E, MouseEvent>) => {\n if (shouldProcessLinkClick(event, target)) {\n event.preventDefault();\n\n // If the URL hasn't changed, a regular <a> will do a replace instead of\n // a push, so do the same here unless the replace prop is explicitly set\n let replace =\n replaceProp !== undefined\n ? replaceProp\n : createPath(location) === createPath(path);\n\n navigate(to, {\n replace,\n state,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n });\n }\n },\n [\n location,\n navigate,\n path,\n replaceProp,\n state,\n target,\n to,\n preventScrollReset,\n relative,\n unstable_viewTransition,\n ]\n );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n warning(\n typeof URLSearchParams !== \"undefined\",\n `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n `support the URLSearchParams API. If you need to support Internet ` +\n `Explorer 11, we recommend you load a polyfill such as ` +\n `https://github.com/ungap/url-search-params\\n\\n` +\n `If you're unsure how to load polyfills, we recommend you check out ` +\n `https://polyfill.io/v3/ which provides some recommendations about how ` +\n `to load polyfills only for users that need them, instead of for every ` +\n `user.`\n );\n\n let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n let hasSetSearchParamsRef = React.useRef(false);\n\n let location = useLocation();\n let searchParams = React.useMemo(\n () =>\n // Only merge in the defaults if we haven't yet called setSearchParams.\n // Once we call that we want those to take precedence, otherwise you can't\n // remove a param with setSearchParams({}) if it has an initial value\n getSearchParamsForLocation(\n location.search,\n hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n ),\n [location.search]\n );\n\n let navigate = useNavigate();\n let setSearchParams = React.useCallback<SetURLSearchParams>(\n (nextInit, navigateOptions) => {\n const newSearchParams = createSearchParams(\n typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n );\n hasSetSearchParamsRef.current = true;\n navigate(\"?\" + newSearchParams, navigateOptions);\n },\n [navigate, searchParams]\n );\n\n return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n nextInit?:\n | URLSearchParamsInit\n | ((prev: URLSearchParams) => URLSearchParamsInit),\n navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n (\n /**\n * Specifies the `<form>` to be submitted to the server, a specific\n * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n * arbitrary data to submit.\n *\n * Note: When using a `<button>` its `name` and `value` will also be\n * included in the form data that is submitted.\n */\n target: SubmitTarget,\n\n /**\n * Options that override the `<form>`'s own attributes. Required when\n * submitting arbitrary data without a backing `<form>`.\n */\n options?: SubmitOptions\n ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n (\n target: SubmitTarget,\n // Fetchers cannot replace or set state because they are not navigation events\n options?: Omit<SubmitOptions, \"replace\" | \"state\">\n ): void;\n}\n\nfunction validateClientSideSubmission() {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"You are calling submit during the server render. \" +\n \"Try calling submit within a `useEffect` or callback instead.\"\n );\n }\n}\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n let { basename } = React.useContext(NavigationContext);\n let currentRouteId = useRouteId();\n\n return React.useCallback<SubmitFunction>(\n (target, options = {}) => {\n validateClientSideSubmission();\n\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n router.navigate(options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n replace: options.replace,\n state: options.state,\n fromRouteId: currentRouteId,\n unstable_viewTransition: options.unstable_viewTransition,\n });\n },\n [router, basename, currentRouteId]\n );\n}\n\n/**\n * Returns the implementation for fetcher.submit\n */\nfunction useSubmitFetcher(\n fetcherKey: string,\n fetcherRouteId: string\n): FetcherSubmitFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseSubmitFetcher);\n let { basename } = React.useContext(NavigationContext);\n\n return React.useCallback<FetcherSubmitFunction>(\n (target, options = {}) => {\n validateClientSideSubmission();\n\n let { action, method, encType, formData, body } = getFormSubmissionInfo(\n target,\n basename\n );\n\n invariant(\n fetcherRouteId != null,\n \"No routeId available for useFetcher()\"\n );\n router.fetch(fetcherKey, fetcherRouteId, options.action || action, {\n preventScrollReset: options.preventScrollReset,\n formData,\n body,\n formMethod: options.method || (method as HTMLFormMethod),\n formEncType: options.encType || (encType as FormEncType),\n });\n },\n [router, basename, fetcherKey, fetcherRouteId]\n );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n action?: string,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n let { basename } = React.useContext(NavigationContext);\n let routeContext = React.useContext(RouteContext);\n invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n let [match] = routeContext.matches.slice(-1);\n // Shallow clone path so we can modify it below, otherwise we modify the\n // object referenced by useMemo inside useResolvedPath\n let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n // Previously we set the default action to \".\". The problem with this is that\n // `useResolvedPath(\".\")` excludes search params of the resolved URL. This is\n // the intended behavior of when \".\" is specifically provided as\n // the form action, but inconsistent w/ browsers when the action is omitted.\n // https://github.com/remix-run/remix/issues/927\n let location = useLocation();\n if (action == null) {\n // Safe to write to this directly here since if action was undefined, we\n // would have called useResolvedPath(\".\") which will never include a search\n path.search = location.search;\n\n // When grabbing search params from the URL, remove the automatically\n // inserted ?index param so we match the useResolvedPath search behavior\n // which would not include ?index\n if (match.route.index) {\n let params = new URLSearchParams(path.search);\n params.delete(\"index\");\n path.search = params.toString() ? `?${params.toString()}` : \"\";\n }\n }\n\n if ((!action || action === \".\") && match.route.index) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the form action. If this is a root navigation, then just use\n // the raw basename which allows the basename to have full control over the\n // presence of a trailing slash on root actions\n if (basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\nfunction createFetcherForm(fetcherKey: string, routeId: string) {\n let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n (props, ref) => {\n let submit = useSubmitFetcher(fetcherKey, routeId);\n return <FormImpl {...props} ref={ref} submit={submit} />;\n }\n );\n if (__DEV__) {\n FetcherForm.displayName = \"fetcher.Form\";\n }\n return FetcherForm;\n}\n\nlet fetcherId = 0;\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n Form: ReturnType<typeof createFetcherForm>;\n submit: FetcherSubmitFunction;\n load: (href: string) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>(): FetcherWithComponents<TData> {\n let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n\n let route = React.useContext(RouteContext);\n invariant(route, `useFetcher must be used inside a RouteContext`);\n\n let routeId = route.matches[route.matches.length - 1]?.route.id;\n invariant(\n routeId != null,\n `useFetcher can only be used on routes that contain a unique \"id\"`\n );\n\n let [fetcherKey] = React.useState(() => String(++fetcherId));\n let [Form] = React.useState(() => {\n invariant(routeId, `No routeId available for fetcher.Form()`);\n return createFetcherForm(fetcherKey, routeId);\n });\n let [load] = React.useState(() => (href: string) => {\n invariant(router, \"No router available for fetcher.load()\");\n invariant(routeId, \"No routeId available for fetcher.load()\");\n router.fetch(fetcherKey, routeId, href);\n });\n let submit = useSubmitFetcher(fetcherKey, routeId);\n\n let fetcher = router.getFetcher<TData>(fetcherKey);\n\n let fetcherWithComponents = React.useMemo(\n () => ({\n Form,\n submit,\n load,\n ...fetcher,\n }),\n [fetcher, Form, submit, load]\n );\n\n React.useEffect(() => {\n // Is this busted when the React team gets real weird and calls effects\n // twice on mount? We really just need to garbage collect here when this\n // fetcher is no longer around.\n return () => {\n if (!router) {\n console.warn(`No router available to clean up from useFetcher()`);\n return;\n }\n router.deleteFetcher(fetcherKey);\n };\n }, [router, fetcherKey]);\n\n return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): Fetcher[] {\n let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n return [...state.fetchers.values()];\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n getKey,\n storageKey,\n}: {\n getKey?: GetScrollRestorationKeyFunction;\n storageKey?: string;\n} = {}) {\n let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n DataRouterStateHook.UseScrollRestoration\n );\n let { basename } = React.useContext(NavigationContext);\n let location = useLocation();\n let matches = useMatches();\n let navigation = useNavigation();\n\n // Trigger manual scroll restoration while we're active\n React.useEffect(() => {\n window.history.scrollRestoration = \"manual\";\n return () => {\n window.history.scrollRestoration = \"auto\";\n };\n }, []);\n\n // Save positions on pagehide\n usePageHide(\n React.useCallback(() => {\n if (navigation.state === \"idle\") {\n let key = (getKey ? getKey(location, matches) : null) || location.key;\n savedScrollPositions[key] = window.scrollY;\n }\n try {\n sessionStorage.setItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n JSON.stringify(savedScrollPositions)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n );\n }\n window.history.scrollRestoration = \"auto\";\n }, [storageKey, getKey, navigation.state, location, matches])\n );\n\n // Read in any saved scroll locations\n if (typeof document !== \"undefined\") {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n try {\n let sessionPositions = sessionStorage.getItem(\n storageKey || SCROLL_RESTORATION_STORAGE_KEY\n );\n if (sessionPositions) {\n savedScrollPositions = JSON.parse(sessionPositions);\n }\n } catch (e) {\n // no-op, use default empty object\n }\n }, [storageKey]);\n\n // Enable scroll restoration in the router\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n getKey && basename !== \"/\"\n ? (location, matches) =>\n getKey(\n // Strip the basename to match useLocation()\n {\n ...location,\n pathname:\n stripBasename(location.pathname, basename) ||\n location.pathname,\n },\n matches\n )\n : getKey;\n let disableScrollRestoration = router?.enableScrollRestoration(\n savedScrollPositions,\n () => window.scrollY,\n getKeyWithoutBasename\n );\n return () => disableScrollRestoration && disableScrollRestoration();\n }, [router, basename, getKey]);\n\n // Restore scrolling when state.restoreScrollPosition changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(() => {\n // Explicit false means don't do anything (used for submissions)\n if (restoreScrollPosition === false) {\n return;\n }\n\n // been here before, scroll to it\n if (typeof restoreScrollPosition === \"number\") {\n window.scrollTo(0, restoreScrollPosition);\n return;\n }\n\n // try to scroll to the hash\n if (location.hash) {\n let el = document.getElementById(\n decodeURIComponent(location.hash.slice(1))\n );\n if (el) {\n el.scrollIntoView();\n return;\n }\n }\n\n // Don't reset if this navigation opted out\n if (preventScrollReset === true) {\n return;\n }\n\n // otherwise go to the top on new locations\n window.scrollTo(0, 0);\n }, [location, restoreScrollPosition, preventScrollReset]);\n }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n callback: (event: BeforeUnloadEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"beforeunload\", callback, opts);\n return () => {\n window.removeEventListener(\"beforeunload\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes. This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n callback: (event: PageTransitionEvent) => any,\n options?: { capture?: boolean }\n): void {\n let { capture } = options || {};\n React.useEffect(() => {\n let opts = capture != null ? { capture } : undefined;\n window.addEventListener(\"pagehide\", callback, opts);\n return () => {\n window.removeEventListener(\"pagehide\", callback, opts);\n };\n }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open. Use at your own risk.\n */\nfunction usePrompt({ when, message }: { when: boolean; message: string }) {\n let blocker = useBlocker(when);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\") {\n let proceed = window.confirm(message);\n if (proceed) {\n // This timeout is needed to avoid a weird \"race\" on POP navigations\n // between the `window.history` revert navigation and the result of\n // `window.confirm`\n setTimeout(blocker.proceed, 0);\n } else {\n blocker.reset();\n }\n }\n }, [blocker, message]);\n\n React.useEffect(() => {\n if (blocker.state === \"blocked\" && !when) {\n blocker.reset();\n }\n }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href. You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n to: To,\n opts: { relative?: RelativeRoutingType } = {}\n) {\n let vtContext = React.useContext(ViewTransitionContext);\n\n invariant(\n vtContext != null,\n \"`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. \" +\n \"Did you accidentally import `RouterProvider` from `react-router`?\"\n );\n\n let { basename } = useDataRouterContext(\n DataRouterHook.useViewTransitionState\n );\n let path = useResolvedPath(to, { relative: opts.relative });\n if (!vtContext.isTransitioning) {\n return false;\n }\n\n let currentPath =\n stripBasename(vtContext.currentLocation.pathname, basename) ||\n vtContext.currentLocation.pathname;\n let nextPath =\n stripBasename(vtContext.nextLocation.pathname, basename) ||\n vtContext.nextLocation.pathname;\n\n // Transition is active if we're going to or coming from the indicated\n // destination. This ensures that other PUSH navigations that reverse\n // an indicated transition apply. I.e., on the list view you have:\n //\n // <NavLink to=\"/details/1\" unstable_viewTransition>\n //\n // If you click the breadcrumb back to the list view:\n //\n // <NavLink to=\"/list\" unstable_viewTransition>\n //\n // We should apply the transition because it's indicated as active going\n // from /list -> /details/1 and therefore should be active on the reverse\n // (even though this isn't strictly a POP reverse)\n return (\n matchPath(path.pathname, nextPath) != null ||\n matchPath(path.pathname, currentPath) != null\n );\n}\n\nexport { useViewTransitionState as unstable_useViewTransitionState };\n\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","entries","initialEntries","initialIndex","v5Compat","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","createHref","createPath","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","getUrlBasedHistory","window","globalHistory","usr","createHashHistory","substr","startsWith","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","invariant","value","message","Error","cond","console","warn","e","getHistoryState","idx","current","_extends","random","toString","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","history","getIndex","handlePop","origin","replaceState","addEventListener","removeEventListener","historyState","pushState","error","DOMException","name","assign","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","route","treePath","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","sort","a","b","score","siblings","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","matchRouteBranch","safelyDecodeURI","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","joinPaths","concat","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","keyMatch","optional","param","pattern","matcher","paramNames","regexpSource","_","paramName","RegExp","compilePath","captureGroups","memo","splatValue","decodeURIComponent","safelyDecodeURIComponent","decodeURI","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","pop","resolvePathname","normalizeSearch","normalizeHash","getInvalidPathError","char","field","dest","getPathContributingMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","reject","pendingKeysSet","subscribers","deferredKeys","Array","isArray","this","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","_ref2","unwrapTrackedPromise","pendingKeys","_tracked","isTrackedPromise","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","inFlightDataRoutes","dataRoutes","future","v7_normalizeFormMethod","v7_prependBasename","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","router","pendingNavigationController","initialized","m","lazy","loader","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","errors","fetchers","Map","blockers","pendingAction","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","updateState","newState","viewTransitionOpts","unstable_viewTransitionOpts","completeNavigation","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","currentLocation","toPaths","getSavedScrollPosition","async","startNavigation","opts","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","routesToUse","loadingNavigation","overrideNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","submission","pendingActionData","pendingError","request","createClientSideRequest","findNearestBoundary","actionOutput","interruptActiveLoads","getSubmittingNavigation","actionMatch","getTargetMatch","callLoaderOrAction","shortCircuited","type","method","routeId","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","pendingActionError","isDeferredResult","handleAction","getLoadingNavigation","Request","fetcherSubmission","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","fetcher","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","getFetcher","_temp","revalidate","redirectLocation","isDocumentReload","reloadDocument","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","setFetcherError","deleteFetcher","markFetchersDone","doneFetcher","getDoneFetcher","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","blockerKey","blockerFunction","predicate","cancelledRouteIds","dfd","y","initialize","_window","transitions","sessionPositions","sessionStorage","getItem","parse","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","normalizeTo","fromRouteId","relative","normalizeNavigateOptions","userReplace","unstable_viewTransition","fetch","requestMatches","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResult","loadingFetcher","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","resolveDeferredData","handleFetcherLoader","dispose","clear","getBlocker","_internalFetchControllers","_internalActiveDeferreds","_internalSetRoutes","newRoutes","Symbol","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","body","isSubmissionNavigation","isValidMethod","searchParams","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","_ref3","convertFormDataToSearchParams","convertSearchParamsToFormData","append","getLoaderMatchesUntilBoundary","boundaryId","boundaryMatches","findIndex","values","currentUrl","nextUrl","navigationMatches","currentLoaderData","currentMatch","isNew","isMissingData","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","resultType","onReject","runHandler","handler","context","requestContext","handlerError","isResponse","isStaticRequest","protocol","isSameBasename","isRouteRequest","contentType","statusCode","deferred","isDeferredData","_result$init","_result$init2","processRouteLoaderData","foundError","loaderHeaders","newLoaderData","mergedLoaderData","hasOwnProperty","reverse","find","_temp4","errorMessage","signals","isRevalidatingLoader","unwrap","getAll","pathMatches","DataRouterContext","React","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","outlet","isDataRoute","RouteErrorContext","useHref","useInRouterContext","UNSAFE_invariant","navigator","useResolvedPath","joinedPathname","useLocation","useNavigationType","navigationType","useMatch","useIsomorphicLayoutEffect","cb","static","useNavigate","useDataRouterContext","DataRouterHook","UseNavigateStable","useCurrentRouteId","DataRouterStateHook","activeRef","useNavigateStable","dataRouterContext","routePathnamesJson","UNSAFE_getPathContributingMatches","useNavigateUnstable","OutletContext","useOutletContext","useOutlet","Provider","useParams","routeMatch","_temp2","useRoutes","useRoutesImpl","dataRouterState","parentMatches","parentParams","parentPathnameBase","locationFromContext","_parsedLocationArg$pa","parsedLocationArg","renderedMatches","_renderMatches","DefaultErrorComponent","useRouteError","stack","lightgrey","preStyles","padding","backgroundColor","style","fontStyle","defaultErrorElement","RenderErrorBoundary","props","super","getDerivedStateFromError","getDerivedStateFromProps","componentDidCatch","errorInfo","render","routeContext","component","RenderedRoute","staticContext","errorElement","ErrorBoundary","_deepestRenderedBoundaryId","_dataRouterState2","_dataRouterState","errorIndex","reduceRight","getChildren","Component","element","hookName","ctx","useDataRouterState","useRouteContext","thisRoute","useRouteId","UseRouteId","useNavigation","UseNavigation","useRevalidator","UseRevalidator","useMatches","UseMatches","UNSAFE_convertRouteMatchToUiMatch","useLoaderData","UseLoaderData","useRouteLoaderData","UseRouteLoaderData","useActionData","UseActionData","_state$errors","UseRouteError","useAsyncValue","useAsyncError","blockerId","useBlocker","shouldBlock","UseBlocker","setBlockerKey","startTransitionImpl","MemoryRouter","historyRef","setStateImpl","v7_startTransition","setState","Router","Navigate","_ref4","jsonPath","Outlet","Route","_props","_ref5","basenameProp","locationProp","staticProp","navigationContext","locationContext","trailingPathname","Routes","_ref6","createRoutesFromChildren","Await","_ref7","AwaitErrorBoundary","ResolveAwait","AwaitRenderStatus","neverSettledPromise","pending","renderError","success","_ref8","toRender","apply","renderMatches","updates","createMemoryRouter","defaultMethod","defaultEncType","isHtmlElement","object","tagName","createSearchParams","_formDataSupportsSubmitter","supportedFormEncTypes","getFormEncType","encType","getFormSubmissionInfo","target","attr","isButtonElement","isInputElement","form","isFormDataSubmitterSupported","createBrowserRouter","parseHydrationData","UNSAFE_mapRouteProperties","createHashRouter","__staticRouterHydrationData","deserializeErrors","serialized","val","__type","UNSAFE_ErrorResponseImpl","__subType","ErrorConstructor","ViewTransitionContext","isTransitioning","Deferred","reason","RouterProvider","fallbackElement","pendingState","setPendingState","vtContext","setVtContext","renderDfd","setRenderDfd","transition","setTransition","interruption","setInterruption","optInStartTransition","startTransitionSafe","startViewTransition","skipTransition","renderPromise","finished","finally","UNSAFE_DataRouterContext","UNSAFE_DataRouterStateContext","DataRoutes","UNSAFE_useRoutesImpl","BrowserRouter","HashRouter","HistoryRouter","Link","ref","absoluteHref","onClick","_objectWithoutPropertiesLoose","_excluded","UNSAFE_NavigationContext","isExternal","targetUrl","internalOnClick","useLinkClickHandler","event","defaultPrevented","NavLink","ariaCurrentProp","className","classNameProp","styleProp","_excluded2","routerState","useViewTransitionState","nextLocationPathname","isActive","isPending","renderProps","ariaCurrent","Form","submit","useSubmit","FormImpl","_ref9","forwardedRef","onSubmit","_excluded3","useFormAction","preventDefault","submitter","nativeEvent","submitMethod","currentTarget","ScrollRestoration","_ref10","storageKey","useScrollRestoration","replaceProp","button","metaKey","altKey","ctrlKey","shiftKey","isModifiedEvent","shouldProcessLinkClick","useSearchParams","defaultInit","defaultSearchParamsRef","hasSetSearchParamsRef","locationSearch","defaultSearchParams","getSearchParamsForLocation","setSearchParams","nextInit","navigateOptions","newSearchParams","validateClientSideSubmission","UseSubmit","currentRouteId","UNSAFE_useRouteId","useSubmitFetcher","fetcherRouteId","UseSubmitFetcher","UNSAFE_RouteContext","fetcherId","useFetcher","_route$matches","UseFetcher","createFetcherForm","load","fetcherWithComponents","useFetchers","UseFetchers","SCROLL_RESTORATION_STORAGE_KEY","_temp3","UseScrollRestoration","scrollRestoration","callback","capture","usePageHide","scrollY","getKeyWithoutBasename","disableScrollRestoration","el","getElementById","scrollIntoView","scrollTo","useBeforeUnload","usePrompt","_ref11","when","unstable_useBlocker","confirm","setTimeout","nextPath"],"sourceRoot":""}