@tanstack/react-router 1.15.6 → 1.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n if (!preload) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n return true\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // wrap loader into an async function to be able to catch synchronous exceptions\n async function loader() {\n await route.options.loader?.(loaderContext)\n }\n // Kick off the loader!\n const loaderPromise = loader()\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData) || isNotFound(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n ;(() => {\n var el = document.getElementById('${id}')\n el.parentElement.removeChild(el)\n })()\n </script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["d","searchError","_a","_b","_c"],"mappings":";;;;;;;;;;AA8MO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,aAKd,SACA;AACO,SAAA,IAAI,OAAkD,OAAO;AACtE;AAEO,MAAM,OAIX;AAAA;AAAA;AAAA;AAAA,EAkCA,YACE,SAKA;AAtCF,SAAA,kBAAsC,GAAG,KAAK;AAAA,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AAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;"}
1
+ {"version":3,"file":"router.js","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n if (!preload) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n return true\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // wrap loader into an async function to be able to catch synchronous exceptions\n async function loader() {\n return await route.options.loader?.(loaderContext)\n }\n // Kick off the loader!\n const loaderPromise = loader()\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData) || isNotFound(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = await route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>\n window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n</script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["d","searchError","_a","_b","_c"],"mappings":";;;;;;;;;;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,OAGd,IAAsB,KAAY;AAClC,SAAO,UACF,SACuC;AACpC,UAAA,WAAW,MAAM;AACvB,WAAO,SAAS,OAAO,SAAS,EAAE,GAAG,IAAI;AAAA,EAAA;AAE7C;AAEO,MAAM,yBAAyB,MAAM;AAAC;AAEtC,MAAM,uBAAuB,MAAM;AAAC;AAEpC,SAAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-router",
3
- "version": "1.15.6",
3
+ "version": "1.15.9",
4
4
  "description": "",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
package/src/awaited.tsx CHANGED
@@ -1,8 +1,10 @@
1
+ import * as React from 'react'
1
2
  import warning from 'tiny-warning'
2
3
  import { defaultDeserializeError, isServerSideError } from './Matches'
3
4
  import { useRouter } from './useRouter'
4
5
  import { DeferredPromise, isDehydratedDeferred } from './defer'
5
6
  import { defaultSerializeError } from './router'
7
+ import invariant from 'tiny-invariant'
6
8
 
7
9
  export type AwaitOptions<T> = {
8
10
  promise: DeferredPromise<T>
@@ -14,16 +16,21 @@ export function useAwaited<T>({ promise }: AwaitOptions<T>): [T] {
14
16
  let state = promise.__deferredState
15
17
  const key = `__TSR__DEFERRED__${state.uid}`
16
18
 
17
- if (isDehydratedDeferred(promise)) {
18
- state = router.hydrateData(key)!
19
+ // There's a chance that the promise was resolved before rendering
20
+ // on the server which means that it was be dehydrated in the critical
21
+ // JSON with the rest of the router state. If that's the case
22
+ // it's status will be 'success' and we can just use the data as is
23
+ // and skip streamed hydration.
24
+
25
+ if (isDehydratedDeferred(promise) && state.status === 'pending') {
26
+ const dehydratedState = router.hydrateData(key)
19
27
  if (!state) throw new Error('Could not find dehydrated data')
28
+ Object.assign(state, dehydratedState)
20
29
  promise = Promise.resolve(state.data) as DeferredPromise<any>
21
30
  promise.__deferredState = state
22
31
  }
23
32
 
24
- if (state.status === 'pending') {
25
- throw promise
26
- }
33
+ if (state.status === 'pending') throw promise
27
34
 
28
35
  if (state.status === 'error') {
29
36
  if (typeof document !== 'undefined') {
@@ -49,13 +56,30 @@ export function useAwaited<T>({ promise }: AwaitOptions<T>): [T] {
49
56
  }
50
57
  }
51
58
 
52
- router.dehydrateData(key, state)
59
+ // TODO: This should only happen on the server
60
+ if (!isDehydratedDeferred(promise)) {
61
+ router.dehydrateData(key, state)
62
+ }
53
63
 
54
- return [state.data]
64
+ return [state.data as any]
55
65
  }
56
66
 
57
67
  export function Await<T>(
58
68
  props: AwaitOptions<T> & {
69
+ fallback?: JSX.Element
70
+ children: (result: T) => JSX.Element
71
+ },
72
+ ) {
73
+ const inner = <AwaitInner {...props} />
74
+ if (props.fallback) {
75
+ return <React.Suspense fallback={props.fallback}>{inner}</React.Suspense>
76
+ }
77
+ return inner
78
+ }
79
+
80
+ function AwaitInner<T>(
81
+ props: AwaitOptions<T> & {
82
+ fallback?: JSX.Element
59
83
  children: (result: T) => JSX.Element
60
84
  },
61
85
  ) {
@@ -20,39 +20,13 @@ export type FetchFnCtx = {
20
20
  }
21
21
 
22
22
  export type FetchFn<TPayload, TResponse> = {
23
- (payload: TPayload, ctx: FetchFnCtx): TResponse
23
+ (payload: TPayload, ctx: FetchFnCtx): Promise<TResponse> | TResponse
24
24
  url?: string
25
25
  }
26
26
 
27
- // export type AnyFetchFn = FetchFn<any, any>
28
-
29
- // export type FetchFnReturn<T extends AnyFetchFn> =
30
- // Awaited<ReturnType<T>> extends JsonResponse<infer R> ? R : ReturnType<T>
31
-
32
- // export type FetcherFn<T extends AnyFetchFn> = Parameters<T>[0] extends undefined
33
- // ? (
34
- // payload?: Parameters<T>['0'],
35
- // opts?: FetchFnCtx,
36
- // ) => Promise<Awaited<FetchFnReturn<T>>>
37
- // : (
38
- // payload: Parameters<T>['0'],
39
- // opts?: FetchFnCtx,
40
- // ) => Promise<Awaited<FetchFnReturn<T>>>
41
-
42
- // export type FetcherMethods<T extends AnyFetchFn> = {
43
- // url: string
44
- // fetch: (
45
- // init: RequestInit,
46
- // opts?: FetcherOptions,
47
- // ) => Promise<Awaited<FetchFnReturn<T>>>
48
- // }
49
-
50
- // export type Fetcher<T extends AnyFetchFn> = FetcherFn<T> & FetcherMethods<T>
51
-
52
27
  export type CompiledFetcherFnOptions<TPayload> = {
53
28
  method: 'GET' | 'POST'
54
- type: 'request' | 'payload'
55
- payload: TPayload
29
+ payload: TPayload | undefined
56
30
  requestInit?: RequestInit
57
31
  }
58
32
 
@@ -61,29 +35,29 @@ export type CompiledFetcherFn<TPayload, TResponse> = {
61
35
  url: string
62
36
  }
63
37
 
64
- export type Fetcher<TPayload, TResponse> = (TPayload extends undefined
65
- ? {
66
- (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>
67
- }
68
- : {
69
- (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>
70
- }) & {
71
- url: string
72
- }
73
-
74
- export function createServerFn<TPayload, TResponse>(
38
+ type IsPayloadOptional<T> = [T] extends [undefined] ? true : false
39
+
40
+ export type Fetcher<TPayload, TResponse> =
41
+ (IsPayloadOptional<TPayload> extends true
42
+ ? {
43
+ (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>
44
+ }
45
+ : {
46
+ (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>
47
+ }) & {
48
+ url: string
49
+ }
50
+
51
+ export function createServerFn<
52
+ TPayload extends any = undefined,
53
+ TResponse = unknown,
54
+ >(
75
55
  method: 'GET' | 'POST',
76
56
  fn: FetchFn<TPayload, TResponse>,
77
57
  ): Fetcher<TPayload, TResponse> {
78
58
  // Cast the compiled function that will be injected by vinxi
79
59
  const compiledFn = fn as unknown as CompiledFetcherFn<TPayload, TResponse>
80
60
 
81
- console.log(
82
- compiledFn,
83
- compiledFn.toString(),
84
- JSON.stringify(compiledFn, null, 2),
85
- )
86
-
87
61
  invariant(
88
62
  compiledFn.url,
89
63
  `createServerFn must be called with a function that is marked with the 'use server' pragma.`,
@@ -93,8 +67,7 @@ export function createServerFn<TPayload, TResponse>(
93
67
  async (payload: TPayload, opts?: FetcherOptions) => {
94
68
  return compiledFn({
95
69
  method,
96
- type: payload instanceof Request ? 'request' : 'payload',
97
- payload,
70
+ payload: payload || undefined,
98
71
  requestInit: opts?.requestInit,
99
72
  })
100
73
  },
package/src/qss.ts CHANGED
@@ -33,11 +33,11 @@ function toValue(mix) {
33
33
  return +str * 0 === 0 && +str + '' === str ? +str : str
34
34
  }
35
35
 
36
- export function decode(str) {
36
+ export function decode(str, pfx?: string) {
37
37
  var tmp,
38
38
  k,
39
39
  out = {},
40
- arr = str.split('&')
40
+ arr = (pfx ? str.substr(pfx.length) : str).split('&')
41
41
 
42
42
  while ((tmp = arr.shift())) {
43
43
  tmp = tmp.split('=')