Files
supabase/apps/studio/lib/chunk-load-error.ts
supabase-vercel-tedd[bot]andAlaister Young fb3ed7ee3c fix(studio): treat WebKit's CORS-denied module load as a chunk-load error (#53532)
## Problem

When a lazily loaded module chunk fails an access-control check in
Safari/WebKit (including every iOS browser) — for example, when a
corporate proxy, VPN, or captive portal redirects a chunk request
cross-origin, or a cross-origin response lacks CORS headers — WebKit's
`ScriptModuleLoader` does not throw `"Importing a module script
failed."` Instead it rejects the dynamic `import()` with `TypeError:
Cross-origin script load denied by Cross-Origin Resource Sharing
policy.` and caches the failed module fetch in the document's module
map.

`isChunkLoadError` in `apps/studio/lib/chunk-load-error.ts` did not
recognize this message. The global error boundary and router error
component therefore skipped the guarded auto-reload, showed the error
page immediately, and reported the error without the `chunkLoadError`
tag.

## Solution

Add WebKit's access-control module load error message to
`CHUNK_LOAD_ERROR_PATTERNS`. Because WebKit only emits this message from
`ScriptModuleLoader` (never for `fetch()` or XHR) and Studio only uses
dynamic `import()` for internal chunks, it gets the same handling as
other chunk-load failures:

- one guarded page reload under the existing time window and per-tab cap
- if the error recurs inside the window, it falls through to the error
UI and is reported with the `chunkLoadError` tag

Unit tests cover the new message and verify that a generic CORS-denied
`fetch` error is still not treated as a chunk-load error.

## Review instructions

This change has no UI. Check it with:

1. `pnpm --filter studio exec vitest run lib/chunk-load-error.test.ts
components/ui/ErrorBoundary/useChunkLoadReload.test.tsx` (50 passed).
2. `pnpm --filter studio exec tsc --noEmit` and ESLint on the changed
files.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)


[FE-4940](https://linear.app/supabase/issue/FE-4940/typeerror-cross-origin-script-load-denied-by-cross-origin-resource)

---------

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-23 15:20:18 +00:00

200 lines
6.9 KiB
TypeScript

/**
* Recovery for failed lazy-loaded JS/CSS chunks (route chunks, `next/dynamic`,
* `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<typeof reloadStateSchema>
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,
// Next.js / webpack (JS and CSS chunks)
/Loading (CSS )?chunk [^\s]+ failed/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<Storage, 'getItem' | 'setItem'>
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<object>()
/**
* 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
}