mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem
Now that Studio runs on TanStack Start, `apps/studio` still routes 13
`next/dynamic` imports through a local compatibility shim
(`apps/studio/compat/next/dynamic.tsx` aliased in
`apps/studio/vite.config.ts`). Keeping the shim adds unnecessary
indirection during the Next.js teardown (FE-5113).
## Solution
Replaces every `next/dynamic` import in `apps/studio` with `React.lazy`
+ `Suspense` (or static imports where already inside a lazy chunk), then
deletes `compat/next/dynamic.tsx` and its Vite alias.
None of the previously `ssr: false` call sites need `ClientOnly`: Studio
runs TanStack Start with `spa: { enabled: true }` and only prerenders
the signed-out auth routes (`/sign-in`, `/sign-up`, `/sign-in-sso`,
`/forgot-password`), `__root.tsx` gates `<Outlet />` behind
`canRenderPage`, and `StudioCommandMenu` is already gated by
`useCommandMenuInitiated()` (which starts `false` per render).
**Removed:**
- `apps/studio/compat/next/dynamic.tsx` and the `'next/dynamic'` entry
in `nextShims` in `apps/studio/vite.config.ts`
**Changed:**
- Migrated all `next/dynamic` call sites to `React.lazy` + `Suspense`:
- `StudioCommandMenu`, `ContextSearchResults`,
`Marketplace/OverviewTab`, `QueryDetail` (`SqlMonacoBlock`),
`SQLEditorEditorPanel` (`MonacoEditor`, `DiffEditor`),
`SupportAssistantSuccessCard`, `LayoutSidebarProvider`,
`MessageMarkdown` (`Streamdown`), and
`SupportAssistantSuccessCardContent` (`Streamdown`)
- `ConnectStepsSection`: hoisted the lazy component cache out of
`useMemo` to module scope (also clears its
`react/no-unstable-nested-components` warning)
- `Integrations.constants.tsx` and `useAvailableIntegrations.tsx`:
hoisted all lazy integration tab/page definitions (including
`GraphiQLTab`) to module scope so `navigate()` returns stable component
references, added `Suspense` boundaries with `<Loading />` at both
render points (`MarketplaceDetail` and the integration child route), and
keyed integration tab/creation sheet instances (`integration.id` in
`MarketplaceDetail` and `wrapperMeta.name` in `WrappersTab`) so state
cannot leak when switching between wrappers or OAuth integrations;
preserves `umdAmdShortCircuit`, `ssrStubGraphiql`, and
`graphiqlViteWorkers` in `vite.config.ts`
- Replaced `dynamic()` calls for `AiIconAnimation`, `Badge`, and 4
`icons` in `CreateCommands.tsx` with static imports (already inside the
lazy `CommandMenu` chunk)
- Removed the stale `next/dynamic` mention from the
`lib/chunk-load-error.ts` doc comment (`React.lazy` chunk failures
continue bubbling to the root `ErrorBoundary` reload handler)
**Added:**
- Reference-stability tests for `INTEGRATIONS.navigate` in
`Integrations.constants.test.ts` (running in Vitest's Node environment)
## Review instructions
1. Open the SQL Editor and Query Performance query detail panel, and
confirm the Monaco editor and diff view load cleanly.
2. Open the GraphQL integration's GraphiQL tab, and confirm the loading
skeleton displays while the chunk loads and GraphiQL mounts with working
autocomplete/workers.
3. Open a Wrapper integration's Wrappers tab, open the create sheet,
then navigate via history to a different wrapper's create sheet and
confirm the form resets to the new wrapper's defaults.
4. Open the Command Menu (`Cmd+K`), navigate to context search (for
example, Search Database Tables) and Create commands, and confirm icons,
badges, and search results load without flicker.
5. Open the Connect sheet and switch between frameworks/steps,
confirming step content loads with the skeleton fallback.
6. Toggle sidebars (AI Assistant, Inline SQL Editor, Advisor, Help) and
verify markdown streaming in AI Assistant.
7. Confirm CI passes `pnpm --filter studio run build` (including
prerendering and chunk-cycle checks), typecheck, lint ratchet, and
Studio tests.
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
200 lines
6.9 KiB
TypeScript
200 lines
6.9 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,
|
|
// 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
|
|
}
|