import { createRouter, RootRoute, Route, AnyRoute, } from "@tanstack/react-router"; import { RootLayout } from "./RouteLayout"; import { getRoutes } from "./routeConfigs"; import NotFound from "../Pages/NotFound"; import { Auth } from "../Pages/Auth"; export const rootRoute = new RootRoute({ component: RootLayout, }); export function makeRouter(auth: string | null) { try { const routeConfigs = getRoutes(auth); if (routeConfigs.length === 0) { routeConfigs.push({ path: "/", component: Auth }); } const childRoutes: AnyRoute[] = routeConfigs .map(({ path, component }) => { try { return new Route({ getParentRoute: () => rootRoute, path, component, }) as AnyRoute; } catch (error) { console.error(`Error creating route for path ${path}:`, error); return null; } }) .filter((route): route is AnyRoute => route !== null); const notFoundRoute = new Route({ getParentRoute: () => rootRoute, path: "*", component: auth ? NotFound : Auth, }); const routeTree = rootRoute.addChildren([...childRoutes, notFoundRoute]); const router = createRouter({ routeTree, defaultPreload: "intent", }); return router; } catch (error) { console.error("Error creating router:", error); try { const fallbackRoute = new Route({ getParentRoute: () => rootRoute, path: "/", component: Auth, }); const notFoundRoute = new Route({ getParentRoute: () => rootRoute, path: "*", component: Auth, }); const routeTree = rootRoute.addChildren([fallbackRoute, notFoundRoute]); return createRouter({ routeTree, defaultPreload: "intent", }); } catch (fallbackError) { console.error("Fallback router creation also failed:", fallbackError); throw fallbackError; } } }