import { lazy } from "react"; import type { ComponentType } from "react"; const RELOAD_KEY = "spa-chunk-reloaded"; /** * React.lazy that survives a deploy. If a page's dynamic import fails because * its hashed chunk was removed by a newer build, reload once to fetch the fresh * bundle (guarded by sessionStorage so a genuine load failure can't loop). On a * successful load the guard is cleared so the next deploy can recover too. * * The generic mirrors React.lazy's own `ComponentType` constraint — there * is no non-any equivalent that satisfies it, so the `any` is unavoidable here. */ export function lazyWithReload< // eslint-disable-next-line @typescript-eslint/no-explicit-any T extends ComponentType, >(factory: () => Promise<{ default: T }>) { return lazy(() => factory() .then((mod) => { sessionStorage.removeItem(RELOAD_KEY); return mod; }) .catch((err: unknown) => { if (!sessionStorage.getItem(RELOAD_KEY)) { sessionStorage.setItem(RELOAD_KEY, "1"); window.location.reload(); // Never resolves — the reload replaces the document. return new Promise<{ default: T }>(() => {}); } throw err; }), ); }