Files
supabase/apps/studio/lib/chunk-load-error.ts
Alaister YoungandAlaister Young 0c97b9789b [FE-3107] chore(studio): remove remaining Next.js references (#54426)
Removes the remaining Next.js dependencies, compatibility shims, test
mocks, ESLint/TypeScript presets, and webpack/Next workarounds from
Studio following the TanStack Start migration.

Addresses FE-3107.

**Removed:**

- `next` and `next-router-mock` from `apps/studio/package.json` (and
updated `pnpm-lock.yaml`)
- Orphaned `apps/studio/compat/next/script.tsx` shim, `script.test.tsx`,
`compat/**` knip entry, and `nextCompat()` / `ssr.noExternal` `/^next/`
plumbing from `apps/studio/vite.config.ts`
- `apps/studio/tests/lib/route-mock.ts` and all `next-router-mock`
setup/imports across `tests/vitestSetup.ts`,
`tests/lib/custom-render.tsx`, and 12 test files
- `apps/studio/tests/pages/` directory (moved the 3 remaining tests to
`components/interfaces/Organization/Organization.utils.test.ts` and
`apps/studio/tests/routes/`)
- Unused `'use client'` directives across 23 Studio files
- Next.js/webpack workarounds: `graphiqlViteWorkers()` in
`vite.config.ts`, webpack `import.meta.glob` `try/catch` fallback in
`ConnectStepsSection.tsx`, shell `NODE_ENV=test` override in
`vite.config.ts` / root `package.json` / `studio-e2e-test.yml`, Next
`getPathMatch` and `_next` passthrough in `redirects.shared.*`,
`window.next?.router` check in `monaco-graphiql-coexistence.spec.ts`,
and unused `ANALYZE` env var in `apps/studio/turbo.jsonc`
- Next-only Sentry/chunk-load filters (`NEXT_NOT_FOUND`,
`NEXT_REDIRECT`, Next `/org/[slug]/` regex, `/app:\/\//`, dead
`includeThirdPartyErrorFilter` plumbing, webpack chunk error regex) and
stale Next/Pages Router comments, docs, and `#__next` CSS selector

**Changed:**

- `apps/studio/eslint.config.cjs`: switched from
`eslint-config-supabase/next` to the new `eslint-config-supabase/react`
preset (dropping `@next/next/no-img-element: off`, keeping `.next` /
`next-env.d.ts` ignored for local checkouts with stale pre-migration
build artifacts)
- `apps/studio/tsconfig.json`: extends `tsconfig/base.json` directly
instead of `tsconfig/nextjs.json` (identical resolved compiler options)
- `apps/studio/.github/eslint-rule-baselines.json`: pruned 33 stale
`pages/...` and `types/next.ts` entries without changing any rule
thresholds
- `apps/studio/tests/lib/custom-render.tsx`: backed
`TestFrameworkProvider` with TanStack Router instead of
`next-router-mock`
-
`apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx`:
imports `graphiql/setup-workers/vite` directly
- `apps/studio/styles/globals.css`: replaced `@source
'../pages/**/*.{js,ts,jsx,tsx}'` with `@source
'../routes/**/*.{js,ts,jsx,tsx}'`
- `apps/studio/turbo.jsonc`: declared `"NEXT_PUBLIC_*"` in
`tasks.build.env` now that Turborepo infers `nitro` instead of `nextjs`
-
`apps/studio/components/interfaces/Organization/Organization.utils.ts`:
narrowed `buildOrgUrl`'s `slug` parameter to `string[] | undefined`

**Added:**

- `packages/eslint-config-supabase/shared.js` and
`packages/eslint-config-supabase/react.js` (plus `presets.test.ts`),
decoupling non-Next React apps from `eslint-config-next` with verified
zero non-`@next/*` rule drift while keeping
`eslint-config-supabase/next` unchanged for the Next.js apps

## To test

- Run `pnpm --filter eslint-config-supabase run test` and confirm preset
parity tests pass
- Run `pnpm --filter studio run lint`, `pnpm --filter studio run
lint:ratchet`, `pnpm --filter studio run typecheck`, `pnpm knip
--workspace apps/studio`, and `pnpm --filter studio run test`
- Run `pnpm --filter studio run build` and verify the production build,
prerendered routes, chunk-cycle check, and GraphiQL web workers succeed
- Smoke-test Studio locally (`pnpm dev:studio`): verify GraphiQL loads
cleanly, ConnectSheet framework steps render, and Tailwind styles on
route pages are intact

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-02 17:01:50 +08:00

198 lines
6.8 KiB
TypeScript

/**
* 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<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,
]
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
}