import { lazy, Suspense, type ComponentType } from 'react'; import { createRootRouteWithContext, createRoute, createRouter, Outlet, redirect, } from '@tanstack/react-router'; import type { AuthContextValue } from '@/features/auth/context/auth-context'; import type { SetupStatus } from '@/features/setup/services/types'; import { api, NetworkError } from '@/lib/api-client'; import { AppLayout } from '@/components/layout/AppLayout'; import { LoginPage } from '@/features/auth/pages/LoginPage'; import { NotFoundPage } from '@/pages/NotFoundPage'; import { RoleGuard } from '@/features/auth/components/RoleGuard'; import { ModuleGuard } from '@/features/system/components/ModuleGuard'; export interface RouterContext { auth: AuthContextValue; } // --------------------------------------------------------------------------- // InitGuard: module-level session cache for setup status (BR-U2-08). // One network request per page load; subsequent beforeLoad calls return cached // data synchronously via Promise.resolve(). // --------------------------------------------------------------------------- let _setupStatusCache: SetupStatus | null = null; let _setupStatusPromise: Promise | null = null; async function fetchSetupStatus(): Promise { if (_setupStatusCache !== null) return _setupStatusCache; if (_setupStatusPromise === null) { _setupStatusPromise = api .get<{ initialized?: boolean; Initialized?: boolean; tokenRequired?: boolean; TokenRequired?: boolean }>( '/api/v1/Setup/status', ) .then((raw) => { // Backend may return PascalCase (Initialized) if no camelCase policy is set. const s: SetupStatus = { initialized: raw.initialized ?? raw.Initialized ?? false, tokenRequired: raw.tokenRequired ?? raw.TokenRequired ?? false, }; _setupStatusCache = s; return s; }) .catch((err: unknown) => { _setupStatusPromise = null; throw err; }); } return _setupStatusPromise; } // Exposed for tests so each test starts with a clean cache. export function _resetSetupStatusCache(): void { _setupStatusCache = null; _setupStatusPromise = null; } /** Whether the setup page must ask for the setup token (known once the InitGuard fetched the status). */ export function isSetupTokenRequired(): boolean { return _setupStatusCache?.tokenRequired === true; } export function _markSystemInitialized(): void { _setupStatusCache = { initialized: true }; _setupStatusPromise = null; } function RouteFallback() { return (
); } function BootstrapSplash() { return (
); } function lazyPage

>( factory: () => Promise<{ [key: string]: ComponentType

}>, exportName: string, ) { const Loaded = lazy(() => factory().then((module) => ({ default: module[exportName] }))); return function LazyRouteComponent() { return ( }> ); }; } // --------------------------------------------------------------------------- // Routes // --------------------------------------------------------------------------- const rootRoute = createRootRouteWithContext()({ pendingComponent: BootstrapSplash, pendingMs: 0, notFoundComponent: NotFoundPage, beforeLoad: async ({ location }) => { let status: SetupStatus; try { status = await fetchSetupStatus(); } catch (err) { if (err instanceof NetworkError) { // Backend unreachable: skip setup redirect and show the login page instead. status = { initialized: true }; } else { console.warn('[InitGuard] Setup status check failed, assuming not initialized:', err); status = { initialized: false }; } } const onSetup = location.pathname === '/setup'; const onInvite = location.pathname.startsWith('/invite/complete'); if (!status.initialized && !onSetup && !onInvite) { throw redirect({ to: '/setup' }); } if (status.initialized && onSetup) { throw redirect({ to: '/login' }); } }, component: () => , }); const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', beforeLoad: () => { throw redirect({ to: '/dashboard' }); }, }); const loginRoute = createRoute({ getParentRoute: () => rootRoute, path: '/login', validateSearch: (search: Record): { redirect?: string } => ({ redirect: typeof search.redirect === 'string' ? search.redirect : undefined, }), beforeLoad: ({ context }) => { if (context.auth.isAuthenticated) { throw redirect({ to: '/dashboard' }); } }, component: LoginPage, }); const forgotPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: '/forgot-password', beforeLoad: ({ context }) => { if (context.auth.isAuthenticated) { throw redirect({ to: '/dashboard' }); } }, component: lazyPage(() => import('@/features/auth/pages/ForgotPasswordPage'), 'ForgotPasswordPage'), }); const resetPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: '/reset-password', validateSearch: (search: Record): { uid?: string; token?: string } => ({ uid: typeof search.uid === 'string' ? search.uid : undefined, token: typeof search.token === 'string' ? search.token : undefined, }), component: lazyPage(() => import('@/features/auth/pages/ResetPasswordPage'), 'ResetPasswordPage'), }); const setupRoute = createRoute({ getParentRoute: () => rootRoute, path: '/setup', component: lazyPage(() => import('@/features/setup/pages/SetupPage'), 'SetupPage'), }); const inviteCompleteRoute = createRoute({ getParentRoute: () => rootRoute, path: '/invite/complete', validateSearch: (search: Record): { token?: string } => ({ token: typeof search.token === 'string' ? search.token : undefined, }), component: lazyPage(() => import('@/features/invitation/pages/InviteCompletePage'), 'InviteCompletePage'), }); const authenticatedRoute = createRoute({ getParentRoute: () => rootRoute, id: '_authenticated', beforeLoad: ({ context, location }) => { if (!context.auth.isAuthenticated) { throw redirect({ to: '/login', search: { redirect: location.href } }); } }, component: AppLayout, }); const dashboardRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/dashboard', component: lazyPage(() => import('@/features/dashboard/pages/DashboardPage'), 'DashboardPage'), }); const usersRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/users', component: () => ( {lazyPage(() => import('@/features/users/pages/UsersPage'), 'UsersPage')()} ), }); const cmsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/cms', component: () => ( {lazyPage(() => import('@/features/cms/pages/CmsPage'), 'CmsPage')()} ), }); const offeringsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/offerings', component: () => ( {lazyPage(() => import('@/features/offerings/pages/OfferingsListPage'), 'OfferingsListPage')()} ), }); const offeringsNewRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/offerings/new', component: () => ( {lazyPage(() => import('@/features/offerings/pages/OfferingFormPage'), 'OfferingFormPage')()} ), }); const offeringsEditRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/offerings/$id/edit', component: () => ( {lazyPage(() => import('@/features/offerings/pages/OfferingFormPage'), 'OfferingFormPage')()} ), }); const settingsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/settings', component: () => ( {lazyPage(() => import('@/features/settings/pages/SettingsPage'), 'SettingsPage')()} ), }); const profileRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/profile', component: lazyPage(() => import('@/features/profile/pages/ProfilePage'), 'ProfilePage'), }); const accessDeniedRoute = createRoute({ getParentRoute: () => rootRoute, path: '/403', component: lazyPage(() => import('@/pages/AccessDeniedPage'), 'AccessDeniedPage'), }); export const routeTree = rootRoute.addChildren([ indexRoute, loginRoute, forgotPasswordRoute, resetPasswordRoute, setupRoute, inviteCompleteRoute, accessDeniedRoute, authenticatedRoute.addChildren([ dashboardRoute, usersRoute, cmsRoute, offeringsRoute, offeringsNewRoute, offeringsEditRoute, settingsRoute, profileRoute, ]), ]); export const router = createRouter({ routeTree, defaultPreload: 'intent', // Matches vite.config.ts's `base`: '/admin/' in production builds, '/' in dev. basepath: import.meta.env.BASE_URL, context: { auth: undefined as unknown as AuthContextValue }, }); declare module '@tanstack/react-router' { interface Register { router: typeof router; } }