mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
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>
635 lines
28 KiB
TypeScript
635 lines
28 KiB
TypeScript
/* eslint-disable no-restricted-exports */
|
|
|
|
import fs from 'node:fs'
|
|
import { createRequire } from 'node:module'
|
|
import path from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite'
|
|
import tailwindcss from '@tailwindcss/vite'
|
|
import { devtools } from '@tanstack/devtools-vite'
|
|
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
|
|
import viteReact from '@vitejs/plugin-react'
|
|
import { nitro } from 'nitro/vite'
|
|
import { defineConfig, loadEnv, type Plugin } from 'vite'
|
|
|
|
import { PRERENDERED_ROUTES } from './lib/prerendered-routes'
|
|
import { vercelSpaRoutes } from './scripts/vercel-spa-routes'
|
|
import { getSecurityHeaders } from './security-headers'
|
|
|
|
const rootDir = path.dirname(fileURLToPath(import.meta.url))
|
|
|
|
// Absolute dir of lodash-es, for the SSR-only lodash alias below. Resolved
|
|
// here (not left as a bare 'lodash-es' replacement) because rollup-alias
|
|
// rewrites the id but resolution still runs from the ORIGINAL importer —
|
|
// under pnpm's strict node_modules, workspace packages that don't declare
|
|
// lodash-es (ui, common) would fail to resolve the bare specifier.
|
|
const lodashEsDir = path.dirname(createRequire(import.meta.url).resolve('lodash-es/package.json'))
|
|
|
|
// Import specifiers (as they appear in app source) for files that import as
|
|
// raw text but whose extension the bundler would otherwise treat as code —
|
|
// the Deno typings that `components/ui/AIEditor` feeds to Monaco as extra
|
|
// libs. Deliberately an exact-specifier allowlist — do NOT widen to
|
|
// `*.d.ts`: hijacking declaration-file resolution globally would corrupt
|
|
// every package that ships `.d.ts` next to its JS.
|
|
const RAW_TEXT_SPECIFIERS: Record<string, string> = {
|
|
'@/public/deno/edge-runtime.d.ts': path.join(rootDir, 'public/deno/edge-runtime.d.ts'),
|
|
'@/public/deno/lib.deno.d.ts': path.join(rootDir, 'public/deno/lib.deno.d.ts'),
|
|
}
|
|
|
|
// `\0`-prefixed so the Rolldown dep scanner externalizes the module instead
|
|
// of descending into it (see `shouldExternalizeDep` in vite); `.js`-suffixed
|
|
// so no TS transform ever sees a `.d.ts`-looking id.
|
|
const RAW_TEXT_PREFIX = '\0studio-raw-text:'
|
|
const RAW_TEXT_SUFFIX = '.js'
|
|
|
|
// Serve `*.md` files (used by `static-data/integrations/*/overview.md` via
|
|
// `static-data/integrations/overviews.ts`) and the Deno typings in
|
|
// `public/deno/*.d.ts` as JS modules whose default export is the file's
|
|
// text. The import specifiers stay query-free (no `?raw`) and this plugin
|
|
// does the conversion.
|
|
//
|
|
// The `.d.ts` files can't go through a plain `transform` like the `.md`
|
|
// files do: the dep scanner's native scan pipeline skips JS transform/load
|
|
// hooks entirely and parses whatever the id resolves to, and raw TS
|
|
// *declaration* syntax (`get stdin(): WritableStream;`) is a parse error in
|
|
// its runtime-TS grammar — the whole dependency scan fails and Vite skips
|
|
// pre-bundling outright. Resolving the specifier to a `\0`-virtual id keeps
|
|
// the scanner out (it externalizes `\0` ids) and the `load` hook then
|
|
// serves the file's text for the real pipelines (dev, build, SSR).
|
|
function rawTextLoader(): Plugin {
|
|
return {
|
|
name: 'studio-raw-text-loader',
|
|
enforce: 'pre',
|
|
resolveId(id) {
|
|
const file = RAW_TEXT_SPECIFIERS[id]
|
|
if (file) return RAW_TEXT_PREFIX + file + RAW_TEXT_SUFFIX
|
|
},
|
|
load(id) {
|
|
if (!id.startsWith(RAW_TEXT_PREFIX)) return
|
|
const file = id.slice(RAW_TEXT_PREFIX.length, -RAW_TEXT_SUFFIX.length)
|
|
const content = fs.readFileSync(file, 'utf-8')
|
|
return { code: `export default ${JSON.stringify(content)}`, map: null }
|
|
},
|
|
transform(code, id) {
|
|
if (!id.endsWith('.md')) return
|
|
return { code: `export default ${JSON.stringify(code)}`, map: null }
|
|
},
|
|
}
|
|
}
|
|
|
|
// Short-circuit UMD wrappers' AMD branch by string-replacing the
|
|
// `define.amd` check. Vite's `config.define` doesn't reach pre-bundled
|
|
// deps (Vite 8's Rolldown-based optimizer doesn't honour member-
|
|
// expression define keys at the prebundle stage), and adding the same
|
|
// substitution to `optimizeDeps.rolldownOptions.define` had no effect
|
|
// on the emitted `node_modules/.vite/deps/*.js`. This transform fires
|
|
// when Vite *serves* the prebundled file, rewriting the runtime AMD
|
|
// check before it reaches the browser.
|
|
//
|
|
// Applied broadly to any module containing the AMD check (not just
|
|
// papaparse) — UMD wrappers all share the same shape, and we never
|
|
// want to take the AMD branch when Monaco's loader is around.
|
|
//
|
|
// Surfaces concretely on /functions/[slug]/invocations: papaparse
|
|
// pre-bundled into `.vite/deps/papaparse.js` retained the literal
|
|
// `"function" == typeof define && define.amd` check; Monaco's CDN
|
|
// loader installs `window.define` first, so papaparse's UMD takes the
|
|
// AMD branch and calls an anonymous `define([], t)` that Monaco
|
|
// rejects with "Can only have one anonymous define call per script
|
|
// file".
|
|
function umdAmdShortCircuit(): Plugin {
|
|
// Matches both unminified (`typeof define === 'function' && define.amd`)
|
|
// and minified (`"function" == typeof define && define.amd`) forms of
|
|
// the UMD AMD-detection check.
|
|
const AMD_CHECK_PATTERNS = [
|
|
/typeof\s+define\s*===?\s*['"]function['"]\s*&&\s*define\.amd/g,
|
|
/['"]function['"]\s*===?\s*typeof\s+define\s*&&\s*define\.amd/g,
|
|
]
|
|
|
|
// Only short-circuit when `define` is the *global* AMD loader (Monaco's
|
|
// CDN loader) — that's the one we never want UMD wrappers to register
|
|
// against. Some vendored bundles install their own *local* `define` shim
|
|
// and rely on the AMD branch to capture their exports:
|
|
// `monaco-editor/esm/vs/base/common/marked/marked.js` (pulled in by
|
|
// @graphiql/react's bundled Monaco) wraps marked's UMD in
|
|
// `function define(deps, factory) { factory(__marked_exports) }` and its
|
|
// ESM tail reads `__marked_exports.X || exports.X`. Replacing the check
|
|
// with a bare `false` diverts the factory to the global-object branch,
|
|
// leaving `__marked_exports` empty, and the tail's `exports.X` fallback
|
|
// then throws `ReferenceError: exports is not defined` — the GraphiQL
|
|
// editor pane never mounts. The `define !== globalThis.define` guard
|
|
// keeps such local AMD shims working while still disarming the global
|
|
// one. (The operand order — guard *before* `define.amd` — also ensures
|
|
// the emitted expression can never re-match AMD_CHECK_PATTERNS.)
|
|
const AMD_CHECK_REPLACEMENT =
|
|
'(typeof define === "function" && define !== globalThis.define && define.amd)'
|
|
|
|
return {
|
|
name: 'studio-umd-amd-short-circuit',
|
|
enforce: 'pre',
|
|
transform(code, id) {
|
|
if (!code.includes('define.amd')) return
|
|
// Skip Monaco's loader.js if it ever ends up in our graph — it
|
|
// legitimately needs `define.amd` to register itself as AMD.
|
|
if (id.includes('monaco-editor/min/vs/loader')) return
|
|
let next = code
|
|
for (const pattern of AMD_CHECK_PATTERNS) {
|
|
next = next.replace(pattern, AMD_CHECK_REPLACEMENT)
|
|
}
|
|
if (next === code) return
|
|
return { code: next, map: null }
|
|
},
|
|
}
|
|
}
|
|
|
|
// Replace our `components/interfaces/GraphQL/GraphiQL` module with a no-op
|
|
// React component in SSR builds only.
|
|
//
|
|
// `@graphiql/react` transitively loads a codemirror addon that touches
|
|
// `document` at module-evaluation time. During the SPA shell prerender,
|
|
// that hard-crashes with "document is not defined" as soon as the graphiql
|
|
// chunk gets loaded.
|
|
//
|
|
// Stubbing `@graphiql/react` directly would require enumerating its 30+ named
|
|
// exports so Rolldown's static analysis is satisfied. Easier to stub the one
|
|
// internal consumer — `GraphiQL.tsx` only exposes a default-export component,
|
|
// and no SSR-reachable route renders it (the GraphiQL tab is client-only).
|
|
// SSR-only lodash → lodash-es rewrite, for the whole SSR module graph (app
|
|
// source, workspace packages, and node_modules deps alike). The CJS lodash
|
|
// in `ssr.noExternal` evaluates as pure ESM in the dev module runner — no
|
|
// `module`/`exports`/`require` — so its UMD wrapper silently attaches `_` to
|
|
// the global and every named import binds to `undefined`, exploding only when
|
|
// first CALLED during SSR render ("(0, __vite_ssr_import_0__.isEqual) is not
|
|
// a function"). Deep imports (`lodash/isEqual`) fail harder: their plain-CJS
|
|
// `require` throws "require is not defined". lodash-es is the same version as
|
|
// real ESM, so both import styles just work. Client bundles are untouched —
|
|
// resolution is gated on `options.ssr`.
|
|
function ssrLodashEs(): Plugin {
|
|
return {
|
|
name: 'studio-ssr-lodash-es',
|
|
enforce: 'pre',
|
|
resolveId(source, _importer, options) {
|
|
if (!options?.ssr) return
|
|
if (source === 'lodash') return path.join(lodashEsDir, 'lodash.js')
|
|
const subpath = source.match(/^lodash\/(.+?)(\.js)?$/)
|
|
if (subpath) return path.join(lodashEsDir, `${subpath[1]}.js`)
|
|
},
|
|
}
|
|
}
|
|
|
|
function ssrStubGraphiql(): Plugin {
|
|
return {
|
|
name: 'studio-ssr-stub-graphiql',
|
|
enforce: 'pre',
|
|
transform(_code, id, options) {
|
|
if (!options?.ssr) return
|
|
if (id.endsWith('/components/interfaces/GraphQL/GraphiQL.tsx')) {
|
|
return { code: 'export default function GraphiQLStub() { return null }', map: null }
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
// Build-time guard: scan the emitted client chunks for cross-chunk
|
|
// circular imports and fail the build if any are found. Catches the
|
|
// class of bug that produces runtime errors like
|
|
// "TypeError: <name> is not a function" at module load — when chunk
|
|
// A imports a binding from chunk B and B (transitively) imports A
|
|
// back, ES module live-bindings can be undefined at the point the
|
|
// chunk that evaluates first tries to use them.
|
|
//
|
|
// Cycles are matched by chunk basename prefix (directory and `-<hash>.js`
|
|
// suffix stripped), so the allowlist stays stable across builds.
|
|
const KNOWN_CHUNK_CYCLES: ReadonlyArray<ReadonlyArray<string>> = []
|
|
|
|
function chunkPrefix(name: string): string {
|
|
return name
|
|
.replace(/^.*\//, '')
|
|
.replace(/-[A-Za-z0-9_-]{6,}\.js$/, '')
|
|
.replace(/\.js$/, '')
|
|
}
|
|
|
|
function isKnownCycle(scc: string[]): boolean {
|
|
const prefixes = new Set(scc.map(chunkPrefix))
|
|
return KNOWN_CHUNK_CYCLES.some(
|
|
(known) => known.length === prefixes.size && known.every((p) => prefixes.has(p))
|
|
)
|
|
}
|
|
|
|
function assertNoChunkCycles(): Plugin {
|
|
return {
|
|
name: 'studio-assert-no-chunk-cycles',
|
|
apply: 'build',
|
|
generateBundle(_options, bundle) {
|
|
const graph: Record<string, Set<string>> = {}
|
|
for (const [name, asset] of Object.entries(bundle)) {
|
|
if (asset.type !== 'chunk') continue
|
|
graph[name] = new Set(asset.imports.filter((i) => i in bundle))
|
|
}
|
|
|
|
// Tarjan's strongly-connected-components algorithm. Any SCC with
|
|
// more than one node is a cycle in the output chunk graph.
|
|
const indices: Record<string, number> = {}
|
|
const lowlinks: Record<string, number> = {}
|
|
const onStack: Record<string, boolean> = {}
|
|
const stack: string[] = []
|
|
const sccs: string[][] = []
|
|
let nextIndex = 0
|
|
|
|
const strongconnect = (v: string) => {
|
|
indices[v] = nextIndex
|
|
lowlinks[v] = nextIndex
|
|
nextIndex++
|
|
stack.push(v)
|
|
onStack[v] = true
|
|
for (const w of graph[v] || []) {
|
|
if (indices[w] === undefined) {
|
|
strongconnect(w)
|
|
lowlinks[v] = Math.min(lowlinks[v], lowlinks[w])
|
|
} else if (onStack[w]) {
|
|
lowlinks[v] = Math.min(lowlinks[v], indices[w])
|
|
}
|
|
}
|
|
if (lowlinks[v] === indices[v]) {
|
|
const scc: string[] = []
|
|
let w: string | undefined
|
|
do {
|
|
w = stack.pop()
|
|
if (w === undefined) break
|
|
onStack[w] = false
|
|
scc.push(w)
|
|
} while (w !== v)
|
|
if (scc.length > 1) sccs.push(scc)
|
|
}
|
|
}
|
|
|
|
for (const v of Object.keys(graph)) {
|
|
if (indices[v] === undefined) strongconnect(v)
|
|
}
|
|
|
|
const unexpected = sccs.filter((scc) => !isKnownCycle(scc))
|
|
if (unexpected.length === 0) return
|
|
|
|
const summary = unexpected
|
|
.map((scc, i) => ` Cycle ${i + 1}:\n` + scc.map((c) => ` ${c}`).join('\n'))
|
|
.join('\n\n')
|
|
const msg =
|
|
`studio-assert-no-chunk-cycles: detected ${unexpected.length} new chunk-level cycle(s) in the client bundle.\n` +
|
|
`These cause "X is not a function" runtime errors at module-load time. ` +
|
|
`Either restructure the modules involved or add the cycle to KNOWN_CHUNK_CYCLES ` +
|
|
`in apps/studio/vite.config.ts.\n\n` +
|
|
summary
|
|
this.error(msg)
|
|
},
|
|
}
|
|
}
|
|
|
|
// Vite bundles `?worker` modules (Monaco's workers via graphiql) with the ROOT
|
|
// `build.assetsDir`, while Nitro only rewrites the client environment's (to
|
|
// `_vercel/immutable/<salt>/nitro` on Vercel). Keep the workers in the same
|
|
// directory so they land in the immutable store too.
|
|
function workersFollowClientAssetsDir(): Plugin {
|
|
return {
|
|
name: 'studio-workers-follow-client-assets-dir',
|
|
apply: 'build',
|
|
configResolved(config) {
|
|
const clientAssetsDir = config.environments.client?.build.assetsDir
|
|
if (clientAssetsDir) config.build.assetsDir = clientAssetsDir
|
|
},
|
|
}
|
|
}
|
|
|
|
export function serverSourceMaps(): Plugin {
|
|
let ssrOutDir: string | undefined
|
|
|
|
return {
|
|
name: 'studio-server-source-maps',
|
|
apply: 'build',
|
|
enforce: 'pre',
|
|
applyToEnvironment: (environment) => environment.name === 'nitro',
|
|
configResolved(config) {
|
|
const outDir = config.environments.ssr?.build.outDir
|
|
if (outDir) ssrOutDir = path.resolve(config.root, outDir) + path.sep
|
|
},
|
|
async load(id) {
|
|
if (!ssrOutDir || !id.startsWith(ssrOutDir) || !/\.m?js$/.test(id)) return
|
|
|
|
// Vite does not load existing maps when Nitro rebundles the SSR service.
|
|
// Returning the adjacent map preserves the original application locations.
|
|
let map: string
|
|
try {
|
|
map = await fs.promises.readFile(`${id}.map`, 'utf8')
|
|
} catch (error) {
|
|
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return
|
|
throw error
|
|
}
|
|
return { code: await fs.promises.readFile(id, 'utf8'), map }
|
|
},
|
|
}
|
|
}
|
|
|
|
export function sentryForFinalOutputs(
|
|
options: Parameters<typeof sentryTanstackStart>[0]
|
|
): Plugin[] {
|
|
return sentryTanstackStart(options).map((plugin) => {
|
|
if (plugin.name !== 'sentry-vite-plugin') return plugin
|
|
const applyToEnvironment = plugin.applyToEnvironment
|
|
return {
|
|
...plugin,
|
|
applyToEnvironment(environment) {
|
|
// Nitro rebundles SSR code, so intermediate debug IDs must not compete with final IDs.
|
|
if (environment.name === 'ssr' && environment.getTopLevelConfig().command === 'build') {
|
|
return false
|
|
}
|
|
return applyToEnvironment?.(environment) ?? true
|
|
},
|
|
}
|
|
})
|
|
}
|
|
|
|
export default defineConfig(({ command, mode }) => {
|
|
// `pnpm dev:studio-local` needs the `.env.test` cascade (self-hosted mode
|
|
// plus the supabase-cli keys that generateLocalEnv.js writes) — `build`
|
|
// selects it via `--mode test` (`MODE=test`), but `vite dev --mode test` is
|
|
// not an option: TanStack Start's dev-server plugin treats mode 'test' as
|
|
// "running under vitest" and skips installing its SSR middleware entirely,
|
|
// so every route 404s (see the `isTest` guard in devServerPlugin,
|
|
// @tanstack/start-plugin-core). So dev keeps mode 'development' and
|
|
// emulates the env cascade of the mode named by MODE instead: load it for
|
|
// the NEXT_PUBLIC_* defines below, and seed process.env for the SSR
|
|
// runtime. The seeding must not clobber shell-provided values, and survives
|
|
// TanStack's own load-env plugin: that plugin Object.assigns loadEnv(mode)
|
|
// at configResolved — after this runs — and loadEnv gives existing
|
|
// process.env values priority over env-file values.
|
|
const envMode = command === 'serve' && process.env.MODE ? process.env.MODE : mode
|
|
|
|
// Inline NEXT_PUBLIC_* env vars at build time so `process.env.NEXT_PUBLIC_*`
|
|
// works in the browser bundle.
|
|
const env = loadEnv(envMode, rootDir, '')
|
|
|
|
if (envMode !== mode) {
|
|
const processEnv = process.env as Record<string, string | undefined>
|
|
for (const [key, value] of Object.entries(env)) {
|
|
processEnv[key] ??= value
|
|
}
|
|
}
|
|
const publicEnvDefines = Object.fromEntries(
|
|
Object.entries(env)
|
|
.filter(([key]) => key.startsWith('NEXT_PUBLIC_'))
|
|
.map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)])
|
|
)
|
|
|
|
// Vercel auto-populates `NEXT_PUBLIC_VERCEL_*` for Next.js projects but not
|
|
// for other frameworks. Mirror that behaviour by re-exposing the unprefixed
|
|
// system vars under their `NEXT_PUBLIC_VERCEL_*` names so call sites that
|
|
// predate the TanStack migration keep working.
|
|
const vercelPublicVars = [
|
|
'VERCEL_ENV',
|
|
'VERCEL_BRANCH_URL',
|
|
// Sentry release (sentry.tanstack.ts): the SDK silently drops session
|
|
// envelopes when the client has no release, so Release Health would send
|
|
// nothing.
|
|
'VERCEL_GIT_COMMIT_SHA',
|
|
] as const
|
|
for (const key of vercelPublicVars) {
|
|
const value = env[key]
|
|
if (value !== undefined) {
|
|
publicEnvDefines[`process.env.NEXT_PUBLIC_${key}`] = JSON.stringify(value)
|
|
}
|
|
}
|
|
|
|
// Pin server-function calls to the build that created them, without a
|
|
// session cookie that also pins document reloads and the update check.
|
|
publicEnvDefines['process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_ID'] =
|
|
JSON.stringify(
|
|
env.VERCEL_SKEW_PROTECTION_ENABLED === '1' ? env.VERCEL_DEPLOYMENT_ID : undefined
|
|
) ?? 'undefined'
|
|
|
|
// `MAINTENANCE_MODE` gates the "redirect everything to /maintenance" rule.
|
|
// It's deliberately unprefixed, and `vercel.ts` reads it at BUILD time
|
|
// while emitting `vercel.json`, so flipping maintenance has always meant a
|
|
// rebuild/redeploy, never just a server restart. Inline it here on the same
|
|
// terms so the isomorphic `beforeLoad` in `routes/__root.tsx` — which
|
|
// mirrors those rules for the Node server — can read it on the client
|
|
// too, without self-hosters having to set a second, NEXT_PUBLIC_-prefixed
|
|
// var. Falls back to `''` (not left undefined) so the browser bundle never
|
|
// ends up with a bare `process.env` reference.
|
|
publicEnvDefines['process.env.MAINTENANCE_MODE'] = JSON.stringify(env.MAINTENANCE_MODE ?? '')
|
|
|
|
// Sentry init (lib/sentry-client-options.ts, reached via router.tsx) and the
|
|
// error sample rates (lib/errors/error-routing.ts) read these at runtime in
|
|
// the browser. When a var is unset it gets no define
|
|
// entry above, which would leave a literal `process.env.*` in the built
|
|
// bundle — and an undeclared `process` throws in the browser. Inline
|
|
// `undefined` as the fallback for unset NEXT_PUBLIC_* vars.
|
|
for (const key of [
|
|
'NEXT_PUBLIC_SENTRY_DSN',
|
|
'NEXT_PUBLIC_SENTRY_ENVIRONMENT',
|
|
'NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA',
|
|
'NEXT_PUBLIC_SENTRY_SAMPLE_RATE_OTHER',
|
|
'NEXT_PUBLIC_SENTRY_SAMPLE_RATE_OWNED',
|
|
'NEXT_PUBLIC_SENTRY_SAMPLE_RATE_USER_FAULT',
|
|
]) {
|
|
publicEnvDefines[`process.env.${key}`] ??= 'undefined'
|
|
}
|
|
|
|
// Vite's public base keeps asset requests under www's `/dashboard` proxy.
|
|
// Nitro's baseURL stays `/`: its immutable manifest must use the reserved
|
|
// root path. vercel-spa-routes rewrites the browser's prefixed asset URLs
|
|
// to that root path, including assets retained from older deployments.
|
|
const basePath = env.NEXT_PUBLIC_BASE_PATH || undefined
|
|
// Self-hosted sign-in redirects straight to the default project, so there's nothing to prerender.
|
|
const prerenderedRoutes = env.NEXT_PUBLIC_IS_PLATFORM === 'true' ? PRERENDERED_ROUTES : []
|
|
const shouldUploadSourceMaps =
|
|
process.env.SKIP_ASSET_UPLOAD !== '1' && !!process.env.SENTRY_AUTH_TOKEN
|
|
|
|
// Self-hosted responses get the security headers via Nitro route rules. On Vercel they come from vercel.ts: a `/**` header route in
|
|
// the Build Output config would stop matching before Nitro's asset and
|
|
// skew-cookie rules.
|
|
const securityHeaders = Object.fromEntries(
|
|
getSecurityHeaders().map(({ key, value }) => [key, value])
|
|
)
|
|
|
|
return {
|
|
server: {
|
|
port: 3000,
|
|
},
|
|
preview: {
|
|
// The prerender step (@tanstack/start-plugin-core) boots `vite preview`
|
|
// on an ephemeral port and crawls the first resolved URL. With the
|
|
// default host (`localhost`) the server can bind the IPv6 loopback
|
|
// while the crawler's fetch connects to 127.0.0.1 — split name
|
|
// resolution that ECONNREFUSEDs the whole prerender inside docker
|
|
// build containers. Pin both sides to IPv4 loopback.
|
|
host: '127.0.0.1',
|
|
},
|
|
resolve: {
|
|
tsconfigPaths: true,
|
|
},
|
|
...(basePath && { base: basePath }),
|
|
optimizeDeps: {
|
|
// graphiql's Vite worker setup imports Monaco's workers with Vite's
|
|
// `?worker` suffix. The dep optimizer can't load `?worker` ids
|
|
// (UNLOADABLE_DEPENDENCY: "No such file or directory" for
|
|
// `json.worker.js?worker` etc.), so keep the whole chain out of
|
|
// pre-bundling; the modules then go through the normal transform
|
|
// pipeline where Vite's built-in worker plugin turns each `?worker`
|
|
// import into a spawnable Worker constructor.
|
|
exclude: ['graphiql/setup-workers/vite', '@graphiql/react/setup-workers/vite'],
|
|
},
|
|
// NOTE: `define.amd` is deliberately NOT substituted here. The AMD
|
|
// short-circuit is handled exclusively by the `umdAmdShortCircuit()`
|
|
// transform above — a blanket `'define.amd': 'false'` define would also
|
|
// rewrite the *read* in vendored bundles that install their own local
|
|
// `define` shim (monaco-editor's `esm/vs/base/common/marked/marked.js`)
|
|
// and break them — see the plugin's comment for the failure mode.
|
|
define: {
|
|
...publicEnvDefines,
|
|
},
|
|
// Group React and Lucide into stable vendor chunks: keeps React as a single
|
|
// leaf chunk ahead of Lucide and prevents Lucide from fanning out into
|
|
// ~100 individual per-icon modulepreload requests in the initial shell.
|
|
build: {
|
|
rollupOptions: {
|
|
output: {
|
|
manualChunks: (id) => {
|
|
if (
|
|
/node_modules\/(react|react-dom|scheduler)(\/|$)/.test(id) ||
|
|
/node_modules\/react\/jsx-(runtime|dev-runtime)/.test(id)
|
|
) {
|
|
return 'react-vendor'
|
|
}
|
|
if (id.includes('node_modules/lucide-react/')) {
|
|
return 'lucide-react'
|
|
}
|
|
return undefined
|
|
},
|
|
},
|
|
},
|
|
},
|
|
css: {
|
|
// Disable PostCSS auto-discovery: `@tailwindcss/vite` (added below)
|
|
// handles Tailwind v4 directives directly, and a discovered PostCSS
|
|
// Tailwind plugin would double-process the output.
|
|
postcss: { plugins: [] },
|
|
},
|
|
ssr: {
|
|
optimizeDeps: {
|
|
include: ['lodash'],
|
|
},
|
|
|
|
// `lodash` is CJS; its named-export interop fails in Node ESM unless bundled.
|
|
// `tslib`'s Node ESM entry (`modules/index.js`) destructures from a
|
|
// default-imported CJS wrapper (`tslib.js`). When consumers like
|
|
// `@ai-sdk/amazon-bedrock` / `configcat-common` `import … from "tslib"`
|
|
// and that ESM-wrapper gets picked, Rolldown botches the flattened UMD
|
|
// body — "__extends is not a function" at SSR module evaluation time.
|
|
// Inlining `tslib` lets the bundler reach the pure ESM entry directly.
|
|
// `react-use` ships a CJS entry that Vite's SSR externalizer emits as
|
|
// `import pkg from 'react-use'` + destructure. Works locally but
|
|
// Vercel's Node resolves it differently and fails at module instantiate
|
|
// (`ModuleJob._instantiate`). Inlining sidesteps the interop entirely.
|
|
// `awesome-debounce-promise`'s CJS entry only emits
|
|
// `exports.default = fn` (no `module.exports = fn`, no `__esModule`
|
|
// flag). Node's CJS→ESM bridge therefore makes the default import the
|
|
// entire exports object `{ default: fn }`, and call sites like
|
|
// `AwesomeDebouncePromise(fn, 500)` crash with "is not a function" at
|
|
// SSR module evaluation. Surfaces on routes that load the table grid.
|
|
// `@sentry/react` ships real ESM ("import" condition → build/esm), so
|
|
// plain externalization works and it needs no entry here.
|
|
// `tslib` is inlined for the BUILD only: Nitro's dev runner has no CJS
|
|
// interop for the `tslib.js` that its ESM wrapper default-imports, and
|
|
// every SSR request would 500. Left external in dev, Node loads it.
|
|
noExternal: [
|
|
'lodash',
|
|
...(command === 'build' ? ['tslib'] : []),
|
|
'react-use',
|
|
'awesome-debounce-promise',
|
|
],
|
|
},
|
|
plugins: [
|
|
rawTextLoader(),
|
|
ssrStubGraphiql(),
|
|
ssrLodashEs(),
|
|
umdAmdShortCircuit(),
|
|
assertNoChunkCycles(),
|
|
workersFollowClientAssetsDir(),
|
|
serverSourceMaps(),
|
|
devtools(),
|
|
tailwindcss(),
|
|
// Nitro builds and hosts the server for every target: the Vercel
|
|
// function (`.vercel/output`, preset auto-detected from `VERCEL`) and
|
|
// the self-hosted node server (`.output`).
|
|
nitro({
|
|
// Nitro controls both SSR and final server maps. Preserve source content for Sentry.
|
|
sourcemap: true,
|
|
experimental: { sourcemapMinify: false },
|
|
// `server.ts` is TanStack Start's SSR entry, not a Nitro entry;
|
|
// without this Nitro's scan picks it up as both and warns.
|
|
serverEntry: false,
|
|
vercel: {
|
|
// Content-addressed chunks under `/_vercel/immutable/`, shared
|
|
// across deployments, so a tab opened before a redeploy keeps
|
|
// loading its lazy chunks.
|
|
immutableStaticFiles: true,
|
|
// Nitro uses a session-wide __vdpl cookie, which pins reloads too.
|
|
// Keep Skew Protection ENABLED in the Vercel dashboard: this flag
|
|
// only disables Nitro's cookie integration, not Vercel's routing.
|
|
// start.ts pins only server functions using Vercel's request header.
|
|
skewProtection: false,
|
|
// One function serves every API route, so the timeout must cover
|
|
// the longest one (integrations/stripe-sync).
|
|
functions: { maxDuration: 300 },
|
|
},
|
|
// Documents from the static shell; only /api/* and /_serverFn/*
|
|
// invoke the function.
|
|
modules: [vercelSpaRoutes({ basePath, prerenderedRoutes })],
|
|
...(!process.env.VERCEL && { routeRules: { '/**': { headers: securityHeaders } } }),
|
|
}),
|
|
tanstackStart({
|
|
srcDirectory: './',
|
|
spa: {
|
|
enabled: true,
|
|
},
|
|
// Only the listed pages: crawling would follow their links into signed-in pages
|
|
// such as /organizations.
|
|
prerender: { crawlLinks: false, autoStaticPathsDiscovery: false },
|
|
pages: prerenderedRoutes.map((path) => ({ path, prerender: { enabled: true } })),
|
|
// Set `configuredBasepath` so `deriveRouterBasepath` short-circuits
|
|
// its slash-stripping branch. See the basePath comment above.
|
|
...(basePath && { router: { basepath: basePath } }),
|
|
}),
|
|
viteReact(),
|
|
// Sentry's TanStack Start plugin(s) MUST be last so source maps reflect
|
|
// every prior transform. `sentryTanstackStart` returns an ARRAY of
|
|
// plugins (route patterns, source-map upload, middleware auto-wrap), so
|
|
// it's spread. Source-map UPLOAD is skipped gracefully without
|
|
// SENTRY_AUTH_TOKEN (and under SKIP_ASSET_UPLOAD). We disable the
|
|
// middleware auto-wrap because start.ts wires the Sentry global
|
|
// middlewares explicitly.
|
|
...sentryForFinalOutputs({
|
|
org: process.env.SENTRY_ORG ?? 'supabase',
|
|
project: process.env.SENTRY_PROJECT ?? 'supabase-studio-tanstack',
|
|
authToken: process.env.SENTRY_AUTH_TOKEN,
|
|
autoInstrumentMiddleware: false,
|
|
silent: true,
|
|
sourcemaps: {
|
|
disable: !shouldUploadSourceMaps,
|
|
// Intermediate SSR maps must survive until Nitro composes the final server maps.
|
|
// Skipped uploads retain private server maps for local diagnostics.
|
|
filesToDeleteAfterUpload: [
|
|
path.join(rootDir, '.output/public/**/*.map'),
|
|
path.join(rootDir, '.vercel/output/static/**/*.map'),
|
|
...(shouldUploadSourceMaps
|
|
? [
|
|
path.join(rootDir, '.output/server/**/*.map'),
|
|
path.join(rootDir, '.vercel/output/functions/**/*.map'),
|
|
]
|
|
: []),
|
|
],
|
|
},
|
|
}),
|
|
],
|
|
}
|
|
})
|