/** * Recovery for failed lazy-loaded JS/CSS chunks (route chunks, `React.lazy`, * Monaco, …), which happen on flaky or mobile networks and after * deploys that remove old chunks. * * A page reload is the only reliable recovery: WebKit caches a failed module * fetch in the document's module map, so every later `import()` of the same * URL fails instantly until the document is replaced. */ import { z } from 'zod' export const CHUNK_LOAD_RELOAD_STORAGE_KEY = 'supabase-studio:chunk-load-reload' /** * Minimum time between two automatic reloads in the same tab. A chunk that * fails again within this window after a reload is treated as persistent * (offline, chunk deleted by a deploy) and falls through to the error UI * instead of looping. It's longer than a cold boot on a slow mobile * connection, so a reload that itself takes a while to boot can't loop; a * fresh flake after the window gets its own reload. */ export const CHUNK_LOAD_RELOAD_GUARD_MS = 30_000 /** * Hard cap on automatic reloads per tab, so a chunk that keeps failing on a * page that takes longer than the guard window to boot can't reload forever. */ export const CHUNK_LOAD_RELOAD_MAX_PER_TAB = 3 const reloadStateSchema = z.object({ at: z.number().finite(), count: z.number().int().nonnegative(), }) type ReloadState = z.infer const CHUNK_LOAD_ERROR_PATTERNS = [ // Chrome / Chromium /Failed to fetch dynamically imported module/i, // Firefox /error loading dynamically imported module/i, // Safari / WebKit (incl. every iOS browser); carries no URL /Importing a module script failed/i, // Safari / WebKit (incl. every iOS browser), when a module fetch fails access // control (e.g. a proxy or captive portal redirects a chunk cross-origin, or // a cross-origin response lacks CORS headers); carries no URL /Cross-origin script load denied by Cross-Origin Resource Sharing policy/i, // Vite's dynamic-import dependency preloader /Unable to preload CSS/i, ] export function isChunkLoadError(error: unknown): boolean { if (typeof error !== 'object' || error === null) return false const name = 'name' in error && typeof error.name === 'string' ? error.name : '' if (name === 'ChunkLoadError') return true const message = 'message' in error && typeof error.message === 'string' ? error.message : '' return CHUNK_LOAD_ERROR_PATTERNS.some((pattern) => pattern.test(message)) } /** * The guard is keyed on time, not on the error message: WebKit's message is * identical for every chunk and sessionStorage outlives reloads, so a * message-keyed guard (as in TanStack's `lazyRouteComponent`) only ever * reloads once per tab. */ export function shouldReloadForChunkError({ now, lastReloadAt, guardMs = CHUNK_LOAD_RELOAD_GUARD_MS, }: { now: number lastReloadAt: number | null guardMs?: number }): boolean { if (lastReloadAt === null) return true // A timestamp in the future means the clock moved backwards; don't trust it if (lastReloadAt > now) return false return now - lastReloadAt >= guardMs } type ChunkReloadStorage = Pick function parseReloadState(raw: string): ReloadState | undefined { try { const result = reloadStateSchema.safeParse(JSON.parse(raw)) return result.success ? result.data : undefined } catch { return undefined } } /** * Returns `undefined` when there's no usable value, and `null` when storage * itself can't be read (private mode, blocked site data, SSR). */ function readReloadState(storage: ChunkReloadStorage): ReloadState | undefined | null { try { const raw = storage.getItem(CHUNK_LOAD_RELOAD_STORAGE_KEY) return raw === null ? undefined : parseReloadState(raw) } catch { return null } } /** * Reads the value back after writing it: a storage that silently drops * writes would otherwise look empty on every boot and reload forever. */ function writeReloadState(storage: ChunkReloadStorage, state: ReloadState): boolean { const value = JSON.stringify(state) try { storage.setItem(CHUNK_LOAD_RELOAD_STORAGE_KEY, value) return storage.getItem(CHUNK_LOAD_RELOAD_STORAGE_KEY) === value } catch { return false } } function getSessionStorage(): ChunkReloadStorage | undefined { if (typeof window === 'undefined') return undefined try { return window.sessionStorage } catch { return undefined } } type ChunkReloadOptions = { storage?: ChunkReloadStorage; now?: number } /** The guard state to record if `error` may reload now, without writing it. */ function getNextReloadState( error: unknown, storage: ChunkReloadStorage, now: number ): ReloadState | undefined { if (!isChunkLoadError(error)) return undefined const state = readReloadState(storage) if (state === null) return undefined const count = state?.count ?? 0 if (count >= CHUNK_LOAD_RELOAD_MAX_PER_TAB) return undefined if (!shouldReloadForChunkError({ now, lastReloadAt: state?.at ?? null })) return undefined return { at: now, count: count + 1 } } /** * Decides whether `error` should trigger a page reload, recording the reload * in the guard when it should. Without a working storage there's no loop * guard, so it never reloads. */ export function claimChunkLoadReload( error: unknown, { storage = getSessionStorage(), now = Date.now() }: ChunkReloadOptions = {} ): boolean { if (!storage) return false const next = getNextReloadState(error, storage, now) return next !== undefined && writeReloadState(storage, next) } const claimedErrors = new WeakSet() /** * Whether `error` has claimed, or could claim, a reload, without touching the * guard. Safe to call during render, where a claim could be discarded along * with the render and use up the guard without a reload ever happening. */ export function peekChunkLoadReload( error: unknown, { storage = getSessionStorage(), now = Date.now() }: ChunkReloadOptions = {} ): boolean { if (typeof error === 'object' && error !== null && claimedErrors.has(error)) return true return storage !== undefined && getNextReloadState(error, storage, now) !== undefined } /** * Claims a reload for `error`. Call it after commit (an effect or an error * boundary's `onError`), never during render; use `peekChunkLoadReload` there. * * A claimed reload is remembered per error object, so a boundary's `onError` * and its fallback's effect both see it while the guard is only claimed * once. A refusal isn't remembered: a retry can rethrow * the same error object (`React.lazy` caches its rejected promise), and that * retry should get a fresh decision once the guard window has passed. */ export function getChunkLoadReloadDecision(error: unknown): boolean { if (typeof error !== 'object' || error === null) return false if (claimedErrors.has(error)) return true const decision = claimChunkLoadReload(error) if (decision) claimedErrors.add(error) return decision }