Repository navigation
fix(studio): TanStack post-merge fixes — Monaco loader, fonts, CSP (from #46424) - #47657
Conversation
…path #47182 dropped CDN loading for Monaco in every environment and moved the locally-served assets from a flat public/monaco-editor/ layout into public/monaco-editor/vs/. The Next entry (pages/_app.tsx) was updated to match, but the TanStack root (routes/__root.tsx) still pointed loader.config at ${BASE_PATH}/monaco-editor, so after that landed the loader looked for loader.js at /monaco-editor/loader.js (404) and no Monaco editor mounted. Mirror the Next config: serve from ${origin}${BASE_PATH}/monaco-editor/vs for all environments, window-guarded since __root.tsx is also evaluated during SSR. Fixes the app-wide Monaco breakage that was failing the TanStack E2E shard (RLS policy editor, cron SQL, realtime JSON payload, database functions, GraphiQL coexistence).
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
5 Skipped Deployments
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughStudio now standardizes Monaco/font setup, security headers, URL/search/redirect behavior, edge diff file keys, integration overview loading, and Vite compatibility shims. ChangesStudio asset loading and security headers
Studio URL compatibility and redirect handling
Studio edge diff file key normalization
Studio Vite bundling shims and integration overviews
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant RootRoute as routes/__root.tsx
participant IndexRoute as routes/index.tsx
participant Redirects as redirects.shared.ts
RootRoute->>Redirects: matchRedirect({ pathname, search, hash })
IndexRoute->>Redirects: redirect({ href }) with carried search/hash
Redirects-->>RootRoute: matched destination with preserved query/hash
sequenceDiagram
participant NuqsAdapter as nuqs-tanstack-adapter.tsx
participant NextRouter as compat/next/router.ts
participant Navigation as compat/next/navigation.ts
participant TanStackRouter as TanStack Router
NuqsAdapter->>TanStackRouter: buildSearchUpdateArgs(pathname, search)
NextRouter->>TanStackRouter: withDefaultPathname() / resolveSearchOrHashOnlyTarget()
Navigation->>TanStackRouter: splitInternalUrl(href) -> to/search/hash
TanStackRouter-->>NuqsAdapter: navigate() with normalized href
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🎭 Playwright Test ResultsDetails
Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
#47306 renamed Tailwind's sans var from --font-custom to --font-sans and added --font-heading (Manrope), setting both via next/font on the Next build. The TanStack fonts.css was never updated — it still only set the now-ignored --font-custom, so --font-sans was unset and resolved to theme.css's fallback chain (Circular, custom-font, Helvetica Neue, ...) i.e. system fonts, and --font-heading/Manrope was missing entirely. Body text rendered as Helvetica at weight 450, which is why the Inter weights looked wrong. - fonts.css: set --font-sans (vendored Inter) and --font-heading (Manrope) to match what next/font provides on Next; drop the dead --font-custom. - __root.tsx: load Manrope over the same Google Fonts <link> already used for Source Code Pro (Inter stays vendored via @font-face). Verified against the built CSS bundle in a browser: computed body font-family is now Inter (was the Circular/system fallback) and headings resolve to Manrope. The unlayered :root wins over theme.css's @layer theme self-referential --font-sans, same as the Next inline-style approach.
Follow-up to the font fix: drop the Google Fonts <link> and self-host all three families via @font-face in fonts.css, matching next/font (which self-hosts them on the Next build). Keeps self-hosted / offline studio working — no runtime CDN dependency. - Inter + Source Code Pro reuse the woff2 fonts/index.ts already ships. - Manrope: vendored latin + latin-ext subset variable woff2 (fonts/manrope/, from @fontsource-variable/manrope) with the standard Google unicode-ranges; no italic axis. Weight ranges mirror fonts/index.ts. - __root.tsx: remove the googleapis/gstatic preconnects + stylesheet link. Verified in a browser against the built bundle: Inter (body), Manrope (headings) and Source Code Pro (mono) all load from local /assets/*.woff2, and no fonts.googleapis/gstatic references remain in the client output.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/styles/fonts.css`:
- Around line 42-51: Remove the unnecessary quotes around the Manrope font
family in both `@font-face` blocks in fonts.css. Update the font-family
declarations for the Manrope entries to use the unquoted name, while leaving
quoted families like Source Code Pro unchanged; use the `@font-face` rules as the
location reference.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f0b2c783-c389-49ff-8df6-b30817785d2b
⛔ Files ignored due to path filters (2)
apps/studio/fonts/manrope/manrope-latin-ext-wght-normal.woff2is excluded by!**/*.woff2apps/studio/fonts/manrope/manrope-latin-wght-normal.woff2is excluded by!**/*.woff2
📒 Files selected for processing (2)
apps/studio/routes/__root.tsxapps/studio/styles/fonts.css
The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / Content-Security-Policy / Referrer-Policy via next.config.ts `headers()`. The TanStack build never carried these over — vercel.ts only set cache-control, so the deployed dashboard shipped with no CSP. The TanStack deploy serves a static shell (no server to attach headers), so the headers go in the Vercel config. Add security-headers.ts as the shared source of truth (reuses getCSP(), env-gated exactly like next.config) and: - vercel.ts: apply to every response (source '/(.*)'), all base-path prefixes — full getCSP() + HSTS on platform, the deployed surface that matters. - scripts/serve.js: apply the non-platform set (frame-ancestors 'none') for the self-hosted server, matching next.config's non-platform branch. Note: font-src in the CSP is 'self' + cloudflare + supabase-assets (no fonts.gstatic.com), so vendoring the fonts locally in the previous commit is what keeps them CSP-compliant. X-Content-Type-Options keeps next.config's 'no-sniff' value verbatim for parity.
GraphiQL's bundled Monaco ships the codicon icon font as a data: URI, and Stripe's payment element inlines its fonts the same way, but font-src didn't allow data: — so those fonts were blocked once the CSP is enforced (surfaced while testing the CSP on the TanStack build; would affect the Next build too). Verified in a browser: with the CSP applied, the data: font violations (37 of them on a cold load) drop to zero, and the SQL editor Monaco renders.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/security-headers.ts`:
- Around line 19-21: The X-Content-Type-Options header is using an invalid value
in the shared security headers setup, so update the value to nosniff in
security-headers.ts and keep the mirrored copies in next.config.ts and
scripts/serve.js consistent. Make the change in the shared header definition and
the matching header arrays/config paths so all Studio deployment paths use the
same valid setting.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 971f6fbf-f052-4856-8604-ddbc578cca2d
📒 Files selected for processing (4)
apps/studio/csp.tsapps/studio/scripts/serve.jsapps/studio/security-headers.tsapps/studio/vercel.ts
✅ Files skipped from review due to trivial changes (1)
- apps/studio/csp.ts
| // Mirrors next.config.ts (note: the effective value browsers honour is | ||
| // `nosniff`; kept identical to the Next build to avoid a behaviour split). | ||
| { key: 'X-Content-Type-Options', value: 'no-sniff' }, |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm the broken value's blast radius across the studio header paths.
rg -n "no-sniff|X-Content-Type-Options" apps/studioRepository: supabase/supabase
Length of output: 459
🏁 Script executed:
#!/bin/bash
sed -n '1,120p' apps/studio/security-headers.ts
printf '\n--- next.config.ts ---\n'
sed -n '80,130p' apps/studio/next.config.ts
printf '\n--- serve.js ---\n'
sed -n '160,190p' apps/studio/scripts/serve.jsRepository: supabase/supabase
Length of output: 4295
🌐 Web query:
X-Content-Type-Options valid value nosniff MDN
💡 Result:
The only valid value for the X-Content-Type-Options HTTP response header is nosniff [1]. According to MDN Web Docs, this header is used to signal that the MIME type advertised in the Content-Type header should be respected and not changed [2][3]. By setting X-Content-Type-Options: nosniff, you prevent the browser from performing MIME type sniffing [3]. This is a security measure that ensures browsers do not execute or render content as a type different from what is explicitly declared, helping to mitigate attacks such as cross-site scripting (XSS) where malicious content might otherwise be interpreted as a script or stylesheet [4][3].
Citations:
- 1: https://howhttpworks.com/headers/x-content-type-options
- 2: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Content-Type-Options
- 3: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options?level=0
- 4: https://github.com/mdn/content/blob/main/files/en-us/web/security/practical_implementation_guides/mime_types/index.md
X-Content-Type-Options should be nosniff everywhere
no-sniff is not a valid value, so MIME-sniffing protection is effectively off here and in the mirrored copies in apps/studio/next.config.ts and apps/studio/scripts/serve.js. Update all three to nosniff so the Next, Vercel, and self-hosted paths stay aligned.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/security-headers.ts` around lines 19 - 21, The
X-Content-Type-Options header is using an invalid value in the shared security
headers setup, so update the value to nosniff in security-headers.ts and keep
the mirrored copies in next.config.ts and scripts/serve.js consistent. Make the
change in the shared header definition and the matching header arrays/config
paths so all Studio deployment paths use the same valid setting.
Vite doesn't polyfill Node's path module in the browser bundle (webpack on
Next did), so `import { basename } from 'path'` crashed the whole
/project/[ref]/merge route on the TanStack build with 'Module "path" has
been externalized for browser compatibility'. Replace the two basename
call sites with a string helper.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…uter TanStack's default JSON search-param codec coerced ?page=2 to a number and ?flag=true to a boolean, JSON-quoted any string that parses as JSON (?flag=%22true%22 in the address bar), and collapsed repeated keys — so multi-value filters like ?filter=a:eq:1&filter=b:eq:2 could never survive a round trip. The whole app (compat shims, nuqs, useUrlState consumers) was written against Next pages-router semantics where every search value is a plain string and repeated keys become arrays. Provide custom parseSearch/stringifySearch implementing the Next semantics: URLSearchParams-based, no JSON parsing or type coercion, repeated keys ↔ string arrays, byte-stable round trips. SSR-safe (no window access). Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…rams Two URL-shape bugs in the next/link compat shim's splitInternalUrl: - URL.hash includes the leading '#' but TanStack's hash prop expects the bare fragment and prepends its own — every <Link href="...#section"> navigated to '...##section' and hash-scroll never fired. - Object.fromEntries(parsed.searchParams) kept only the last occurrence of a repeated query key, silently dropping multi-value params like ?filter=a&filter=b. Collapse to string | string[] per key instead, matching the router's Next-style parseSearch shape. basePath stripping is unchanged; splitInternalUrl is now exported for the new unit tests. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
TanStack resolves a `?`-only relative `to` by appending it to the current path, so any navigation that only changes the query string landed on `<path>/?<query>` — e.g. picking a preset on the advisors page produced `/advisors/security/?preset=...` and changing an auth provider produced `/auth/providers/?provider=...`. Two producers fixed: - The next/router compat shim's push/replace: a resolved `?`/`#`-only target is now prefixed with the current (basepath-stripped) pathname. - nuqs writes (useQueryState/useQueryStates across ~123 files): the stock `nuqs/adapters/tanstack-router` adapter navigates with `to: renderQueryString(search) || '.'`. Replaced with a custom adapter (via nuqs's unstable_createAdapterProvider) that navigates to `pathname + renderQueryString(search)`, preserving replace/push, scroll, and hash behavior of the stock adapter. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Next's redirects() carries the incoming query string and hash through to the redirect destination; the TanStack beforeLoad redirects dropped them — deep links like /project/x/sql/quickstarts?template=... lost the template on the rewrite to /sql/examples, and /?next=new-project&projectName=foo lost projectName. matchRedirect (redirects.shared.ts) now merges the incoming query and hash onto the destination via a new pure preserveQueryAndHash helper: params already set on the destination win, keys the rule matched on (`has`) are consumed, and a destination hash (e.g. billing#invoices) wins over the incoming one. The `/` index route redirect does the same, consuming `next` only when it matched. The shared module stays runtime-agnostic; the config consumers (next.config.ts / vercel.ts) only import the tables and are unaffected. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…ions Drives an actual TanStack router configured with the app's custom search codec through the navigation shapes the compat shims and the custom nuqs adapter produce, asserting Next-shaped hrefs: no JSON coercion or quoting, repeated keys preserved, no trailing slash injected on ?-only navigations, single '#' on hash links. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…the query
Next resolves `push({ query })` (no pathname) against the current route
pattern and re-consumes dynamic params from query into the path. The shim
navigated to a ?-only target instead, so `ref`/`id` — merged into
`router.query` per Next's shape — leaked into the query string on every
query-only push (table editor filter/sort, linter panels, advisor
shortcuts): `/editor/17597?schema=public&ref=<ref>&id=17597&filter=...`.
Default the pathname to the current route pattern and backfill omitted
params (minus TanStack's _splat) so interpolation consumes them.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
There was a problem hiding this comment.
🧹 Nitpick comments (4)
apps/studio/routes/__root.tsx (1)
136-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMonaco loader guard and absolute path look correct, but duplicated with
pages/_app.tsx.This logic — window guard,
${window.location.origin}${BASE_PATH}/monaco-editor/vs— is byte-for-byte duplicated inapps/studio/pages/_app.tsx:121-128. Since both files intentionally exist to support the dual Next/TanStack pipelines (per thefonts.cssimport comment above), consider extracting the loader config into a small shared helper (e.g.lib/monaco-loader-config.ts) imported by both entry points, so future path changes don't need to be kept in sync manually across two files.♻️ Proposed extraction
// apps/studio/lib/configure-monaco-loader.ts import { loader } from '`@monaco-editor/react`' import { BASE_PATH } from '`@/lib/constants`' export function configureMonacoLoader() { if (typeof window !== 'undefined') { loader.config({ paths: { vs: `${window.location.origin}${BASE_PATH}/monaco-editor/vs` } }) } }-if (typeof window !== 'undefined') { - loader.config({ paths: { vs: `${window.location.origin}${BASE_PATH}/monaco-editor/vs` } }) -} +configureMonacoLoader()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/routes/__root.tsx` around lines 136 - 145, The Monaco loader setup is duplicated between __root.tsx and pages/_app.tsx, so future path changes will drift. Extract the window-guarded loader.config logic that builds `${window.location.origin}${BASE_PATH}/monaco-editor/vs` into a shared helper (for example, a configureMonacoLoader function in a small lib module) and import it from both entry points. Keep the SSR window check inside the shared helper so both pipelines still behave identically.apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx (1)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winBrowser-safe rewrite looks correct; consider deduplicating
fileKey.Removing the
node:pathimport and inlining the last-slash slice is a reasonable way to avoid crashing under Vite's browser bundle. However, the identicalfileKeyimplementation is duplicated verbatim inapps/studio/hooks/branches/useEdgeFunctionsDiff.ts. Since both copies must stay behaviorally identical for file matching to work correctly (per the downstreamfileKey(f.name)calls in that hook), consider extracting this into a shared utility to avoid drift.♻️ Suggested consolidation
-const fileKey = (fullPath: string) => fullPath.slice(fullPath.lastIndexOf('/') + 1) +import { fileKey } from './fileKey.utils'Also applies to: 33-36
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx` at line 1, The browser-safe `fileKey` logic is duplicated in `EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so keep the behavior in sync by extracting the shared implementation into a common utility and updating both call sites to use it. Use the existing `fileKey` helper and the downstream `fileKey(f.name)` matching in `useEdgeFunctionsDiff` as the anchor points when consolidating, so file matching continues to behave identically everywhere.apps/studio/lib/nuqs-tanstack-adapter.tsx (1)
29-48: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winEnable structural sharing on the filtered location selector
selectreturns a fresh object on every location change, so this hook will still re-render on unrelated updates unless the selected value is structurally shared. PassstructuralSharing: truehere (or enable it at the router level) so unchanged watched search values keep the same reference.Possible fix
const search = useLocation({ + structuralSharing: true, select: (state) => Object.fromEntries(Object.entries(state.search).filter(([key]) => watchKeys.includes(key))), })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/lib/nuqs-tanstack-adapter.tsx` around lines 29 - 48, Enable structural sharing for the filtered location selector in useNuqsTanStackRouterAdapter so unrelated location updates do not force re-renders. Update the useLocation call that computes search to pass structuralSharing: true, or apply the same setting at the router level, and keep the filtering logic based on watchKeys unchanged.apps/studio/routes/index.tsx (1)
14-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the redirect-suffix logic into a tested utility.
The
suffixclosure implements non-trivial, easy-to-regress logic (carrying query + hash, conditionally droppingnext) inline in the route'sbeforeLoad. Per Studio testing conventions, pure transformation logic like this should live in a.utils.tsfile next to the route and be unit tested directly, rather than only being exercised indirectly through this route.As per coding guidelines: "PR adds business logic inline in a component that could be extracted to a
ComponentName.utils.tsfile next to the component and unit tested... PR adds a utility function without test coverage."♻️ Proposed extraction
-import { stringifySearch } from '`@/lib/router-search-params`' +import { stringifySearch } from '`@/lib/router-search-params`' +import { buildRedirectSuffix } from './index.utils' export const Route = createFileRoute('/')({ validateSearch: (search: Record<string, unknown>) => ({ next: typeof search.next === 'string' ? search.next : undefined, }), beforeLoad: ({ search, location }) => { - const suffix = (consumeNext: boolean) => { - const carried = { ...location.search } as Record<string, unknown> - if (consumeNext) delete carried.next - return `${stringifySearch(carried)}${location.hash ? `#${location.hash}` : ''}` - } + const suffix = (consumeNext: boolean) => + buildRedirectSuffix(location.search, location.hash, consumeNext) if (IS_PLATFORM) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/routes/index.tsx` around lines 14 - 34, The redirect suffix logic in the route’s beforeLoad is non-trivial and should be extracted into a tested utility. Move the suffix/redirect-query-hash transformation out of the inline beforeLoad closure in index.tsx into a nearby .utils.ts helper (for example, a function that accepts location.search, location.hash, and whether next should be consumed), then update beforeLoad to call that helper and keep only the redirect decisions there. Add unit tests for the helper to cover preserving arbitrary query params and hash, and dropping next only when the redirect consumes it.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In
`@apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx`:
- Line 1: The browser-safe `fileKey` logic is duplicated in
`EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so keep the behavior in
sync by extracting the shared implementation into a common utility and updating
both call sites to use it. Use the existing `fileKey` helper and the downstream
`fileKey(f.name)` matching in `useEdgeFunctionsDiff` as the anchor points when
consolidating, so file matching continues to behave identically everywhere.
In `@apps/studio/lib/nuqs-tanstack-adapter.tsx`:
- Around line 29-48: Enable structural sharing for the filtered location
selector in useNuqsTanStackRouterAdapter so unrelated location updates do not
force re-renders. Update the useLocation call that computes search to pass
structuralSharing: true, or apply the same setting at the router level, and keep
the filtering logic based on watchKeys unchanged.
In `@apps/studio/routes/__root.tsx`:
- Around line 136-145: The Monaco loader setup is duplicated between __root.tsx
and pages/_app.tsx, so future path changes will drift. Extract the
window-guarded loader.config logic that builds
`${window.location.origin}${BASE_PATH}/monaco-editor/vs` into a shared helper
(for example, a configureMonacoLoader function in a small lib module) and import
it from both entry points. Keep the SSR window check inside the shared helper so
both pipelines still behave identically.
In `@apps/studio/routes/index.tsx`:
- Around line 14-34: The redirect suffix logic in the route’s beforeLoad is
non-trivial and should be extracted into a tested utility. Move the
suffix/redirect-query-hash transformation out of the inline beforeLoad closure
in index.tsx into a nearby .utils.ts helper (for example, a function that
accepts location.search, location.hash, and whether next should be consumed),
then update beforeLoad to call that helper and keep only the redirect decisions
there. Add unit tests for the helper to cover preserving arbitrary query params
and hash, and dropping next only when the redirect consumes it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2b6c8543-ecff-4747-b22d-6f8ae003d160
📒 Files selected for processing (16)
apps/studio/compat/next/link.test.tsxapps/studio/compat/next/link.tsxapps/studio/compat/next/router.test.tsapps/studio/compat/next/router.tsapps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsxapps/studio/hooks/branches/useEdgeFunctionsDiff.tsapps/studio/lib/nuqs-tanstack-adapter.test.tsapps/studio/lib/nuqs-tanstack-adapter.tsxapps/studio/lib/router-search-params.test.tsapps/studio/lib/router-search-params.tsapps/studio/lib/router-url-shape.test.tsxapps/studio/redirects.shared.test.tsapps/studio/redirects.shared.tsapps/studio/router.tsxapps/studio/routes/__root.tsxapps/studio/routes/index.tsx
✅ Files skipped from review due to trivial changes (3)
- apps/studio/lib/nuqs-tanstack-adapter.test.ts
- apps/studio/lib/router-search-params.ts
- apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
… in navigations
Under the TanStack build, three navigation producers embedded the query
string inside the router's `to` (`navigate({ to: '/path?s=...' })`): the
custom nuqs adapter's updateUrl, the next/router compat shim's
push/replace, and the next/navigation compat shim's push/replace.
TanStack router-core treats the whole `to` string as a path —
buildLocation → interpolatePath → decodePath percent-DECODES it, then
sanitizePathSegment strips control characters (/[\x00-\x1f\x7f]/). Every
%0A newline in a query value was silently deleted.
User-visible symptom: Logs Explorer SQL (the `s` param) lost its
newlines on Run/reload, gluing `order by timestamp desc` and `limit 5`
into `order by timestamp desclimit 5`, which then failed the LIMIT lint.
Any query value with control characters was affected on client-side
navigations. The Next build was unaffected.
Fix: never embed `?query`/`#hash` in `to`.
- Hoist the next/link shim's splitInternalUrl into lib/internal-url.ts
(shared; behavior unchanged for Link) and use it in the next/router
and next/navigation shims to pass { to, search, hash } separately —
`search: {}` / `hash: ''` keep Next's push-without-query semantics.
Prefetch/preloadRoute paths are split the same way so they preload
the real target.
- The nuqs adapter now navigates with `to` = current pathname and the
full search state as a record (buildSearchUpdateArgs, replacing
buildSearchUpdateTarget), letting the app's Next-style search codec
serialize values losslessly. Side effect: nuqs-written URLs now
percent-encode reserved chars like `:` (URLSearchParams semantics),
consistent with every other producer; values round-trip identically.
- Also fix the pre-existing tsc error on the navigate pipeline
(`useParams({ strict: false })` can type as undefined).
Tests: lib/router-url-shape.test.tsx now drives a real router through
both producer shapes with multi-line SQL fixtures asserting lossless
round-trips ("limit 5" intact); splitInternalUrl tests moved to
lib/internal-url.test.ts with %0A and already-basepath-relative cases;
nuqs adapter tests updated for buildSearchUpdateArgs.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Every integration detail page's overview text was blank under the Vite
dev/TanStack build: the two MarkdownContent components loaded their copy
via a template-literal dynamic import
(import(`@/static-data/integrations/${id}/overview.md`)), which webpack
turns into a context module but Vite/Rolldown leaves untouched, so the
browser threw "TypeError: Failed to resolve module specifier" for every
integration (data_api, cron, queues, vault, graphiql, ...).
Replace the template-literal import with an explicit registry of literal
dynamic imports (static-data/integrations/overviews.ts) that both
bundlers can statically analyze and code-split, and add an mdRawLoader
Vite plugin mirroring next.config.ts's raw-loader rule so .md files
resolve to their text content under Vite without query-suffixed
specifiers (which would break the turbopack rule). A unit test keeps the
registry in sync with the overview.md files on disk, and types/markdown.d.ts
types the literal .md imports.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…led Monaco
On /project/<ref>/integrations/graphiql/graphiql under the Vite build,
the editor pane never mounted and the console showed
"ReferenceError: exports is not defined" inside the optimized
monaco-editor dep chunk (twice).
Root cause: monaco-editor/esm/vs/base/common/marked/marked.js (pulled in
by @graphiql/react's bundled Monaco — the only place studio bundles
Monaco instead of using the CDN loader) wraps marked's UMD bundle in a
*local* define shim (function define(deps, factory) {
factory(__marked_exports) }; define.amd = true) and its ESM tail reads
__marked_exports.X || exports.X. The umdAmdShortCircuit() plugin
rewrote the UMD check 'typeof define === "function" && define.amd' to a
bare 'false', diverting the factory to the global-object branch,
leaving __marked_exports empty, so the tail's exports.X fallback threw
at module evaluation and the whole graphiql chunk failed to load.
Fix: replace the check with
'(typeof define === "function" && define !== globalThis.define && define.amd)'
instead of 'false' — it still disarms UMD wrappers that would register
against Monaco's global CDN loader (papaparse on
/functions/[slug]/invocations, the original bug), but leaves local AMD
shims like marked's working. Also drop 'define.amd': 'false' from the
config-level define, which would have broken the same file in the
production Rolldown build; the transform plugin now owns this
substitution for both pipelines.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…anStack build The built TanStack bundle (vite build) crashed at module load on the table editor route (and any other lazy route whose chunk pulled in Sentry) with "ReferenceError: process is not defined". The chain: studio code does `import * as Sentry from '@sentry/nextjs'` in ~25 client files -> @sentry/nextjs's client entry imports next/dist/shared/lib/constants -> its module scope evaluates `...(process?.features?.typescript ? ['next.config.mts'] : [])`, and optional chaining does not guard an undeclared `process` identifier in the browser, so the whole chunk throws before any component runs. The Vite dev server shims `process`, which is why this only surfaced in the production/test build (caught by E2E). Fix: alias the bare `@sentry/nextjs` id to compat/sentry-nextjs.ts in vite.config.ts (TanStack build only -- the Next build doesn't read this config). The shim re-exports @sentry/react (the same-version package @sentry/nextjs wraps on the client; every API studio uses at runtime -- captureException, captureMessage, startSpan, withScope, setTag, setUser, init, and the Event/Breadcrumb/StackFrame types -- exists there) and adds explicit stand-ins for the Next-only APIs (captureRouterTransitionStart, captureRequestError, withSentryConfig) so the alias can never surface an "undefined is not a function". The alias also obsoletes the previous @sentry/nextjs SSR workarounds (ssr.noExternal entry + ssr.optimizeDeps.include) -- the id is rewritten before SSR resolution ever sees it, and @sentry/react ships real ESM. No dependency changes: @sentry/react is already a direct studio dep resolving to 10.59.0, exactly matching @sentry/[email protected]'s own dependency. Verified: test-mode TanStack build passes (prerender + smoke), no built client chunk contains process?.features / middleware-manifest.json / PHASE_PRODUCTION_BUILD / next/dist / __NEXT_DATA__, and tsc is clean apart from the known pre-existing ui-patterns InstructionBlocks error. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…k build The routerPush helper reached for window.next.router, which only exists under the Next runtime — on the TanStack build both coexistence tests failed with 'Next router not available'. Fall back to History-API pushState + popstate, which TanStack Router subscribes to, keeping the client-side (chunk-preserving) navigation these tests depend on. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
| * --font-sans -> body (Inter) [theme.css: --font-sans] | ||
| * --font-heading -> headings (Manrope) [globals.css @theme inline] | ||
| * --font-source-code-pro -> mono (Source Code Pro) | ||
| * If a var is renamed on the Next side (fonts/index.ts / theme.css), rename it |
There was a problem hiding this comment.
Review context for the sentence I trimmed from this header: #47306 renamed the sans var from --font-custom to --font-sans and added --font-heading (Manrope), but this file was never updated — so on the TanStack build the body fell through to the theme fallback chain (Circular/system) and headings never got Manrope. That is the regression the renames + Manrope @font-face below fix.
| optimizeDeps: { | ||
| include: ['@sentry/nextjs'], | ||
| }, | ||
| // `@sentry/nextjs` deliberately has no entry here: the resolve.alias |
There was a problem hiding this comment.
Change context: @sentry/nextjs previously needed CJS workarounds here — a noExternal entry plus ssr.optimizeDeps.include (Vite 8.0.13's SSR module runner evaluated its CJS without the compat wrapper and crashed with "exports is not defined"). I dropped both in this PR: the resolve.alias above rewrites the id to the @sentry/react-backed shim before SSR resolution ever sees it, so the workarounds became unreachable.
| // 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. |
There was a problem hiding this comment.
For the record, the "failure mode" referenced here was hit on this branch: the previous blanket 'define.amd': 'false' define (and an earlier unguarded transform) also rewrote the read inside monaco's vendored marked.js, whose local define shim relies on the AMD branch — the GraphiQL editor pane died with ReferenceError: exports is not defined. Hence the substitution now lives only in the guarded umdAmdShortCircuit() transform.
| // `navigate({ to: renderQueryString(search) || '.', from })`. That shape is | ||
| // doubly broken for us: | ||
| // - TanStack resolves a `?`-only relative `to` by *appending* it to the | ||
| // current path, injecting a trailing slash — every nuqs write turns |
There was a problem hiding this comment.
Both failure modes listed here were live regressions on this branch, not theoretical: every nuqs write on /auth/providers picked up a trailing slash, and Logs Explorer SQL in s lost its newlines (desc\nlimit 5 → desclimit 5). The unit tests alongside (nuqs-tanstack-adapter.test.ts, router-url-shape.test.tsx) pin both.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
apps/studio/lib/internal-url.test.ts (1)
63-68: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd an SSR-mode test case for cross-origin URLs.
All current tests run with
windowdefined, so they don't exercise thetypeof window === 'undefined'branch insplitInternalUrl— which is the exact branch with the cross-origin detection gap flagged ininternal-url.ts. Once that's fixed, add a case simulating SSR (e.g.vi.stubGlobal('window', undefined)) assertingsplitInternalUrl('https://supabase.com/docs')still returns the full URL unchanged.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/lib/internal-url.test.ts` around lines 63 - 68, The existing cross-origin URL test only covers the browser path, so add an SSR-specific case in the splitInternalUrl test suite that simulates typeof window === 'undefined' (for example by stubbing global window to undefined) and asserts splitInternalUrl keeps a cross-origin URL like https://supabase.com/docs unchanged. Place it alongside the current splitInternalUrl assertions so the new test explicitly covers the SSR branch and the cross-origin handling gap.apps/studio/static-data/integrations/overviews.ts (1)
58-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider unit-testing
loadIntegrationOverview's branch behavior.
overviews.test.tsonly assertsINTEGRATION_OVERVIEW_IDSstays in sync with disk; thenull-for-unknown-id and stringified-markdown-for-known-id branches ofloadIntegrationOverviewitself aren't directly exercised. Since bothMarkdownContentcomponents branch onmarkdown !== null, a regression here (e.g., accidentally returningundefinedor throwing instead ofnull) wouldn't be caught by the existing test.As per path instructions for
apps/studio/**(Studio Testing Review Rules): "PR adds a utility function without test coverage" should be flagged.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/static-data/integrations/overviews.ts` around lines 58 - 63, Add unit tests for loadIntegrationOverview to cover both branches: verify it returns null for an unknown integrationId and returns the stringified default markdown for a known integration. Mock the dynamic loader in INTEGRATION_OVERVIEWS so the test exercises loadIntegrationOverview directly, and assert the return type/value rather than only the disk sync behavior currently covered in overviews.test.ts. This should also indirectly protect the MarkdownContent null-check path by ensuring the utility keeps returning null instead of undefined or throwing for missing ids.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/lib/internal-url.ts`:
- Around line 62-80: The cross-origin check in splitInternalUrl() is still gated
on window, which makes SSR treat absolute external URLs as internal links.
Update the origin comparison to use the parsed URL against the computed base
origin unconditionally, so compat/next/link.tsx gets the same href-to result on
server and client. Keep the fix localized to splitInternalUrl() and preserve the
existing fallback behavior when URL parsing fails.
---
Nitpick comments:
In `@apps/studio/lib/internal-url.test.ts`:
- Around line 63-68: The existing cross-origin URL test only covers the browser
path, so add an SSR-specific case in the splitInternalUrl test suite that
simulates typeof window === 'undefined' (for example by stubbing global window
to undefined) and asserts splitInternalUrl keeps a cross-origin URL like
https://supabase.com/docs unchanged. Place it alongside the current
splitInternalUrl assertions so the new test explicitly covers the SSR branch and
the cross-origin handling gap.
In `@apps/studio/static-data/integrations/overviews.ts`:
- Around line 58-63: Add unit tests for loadIntegrationOverview to cover both
branches: verify it returns null for an unknown integrationId and returns the
stringified default markdown for a known integration. Mock the dynamic loader in
INTEGRATION_OVERVIEWS so the test exercises loadIntegrationOverview directly,
and assert the return type/value rather than only the disk sync behavior
currently covered in overviews.test.ts. This should also indirectly protect the
MarkdownContent null-check path by ensuring the utility keeps returning null
instead of undefined or throwing for missing ids.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5e7910e6-510f-4f0b-92fc-a40a2e7a5212
📒 Files selected for processing (34)
apps/studio/TANSTACK_MIGRATION.mdapps/studio/compat/next/link.tsxapps/studio/compat/next/navigation.tsapps/studio/compat/next/router.test.tsapps/studio/compat/next/router.tsapps/studio/compat/sentry-nextjs.tsapps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsxapps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/MarkdownContent.tsxapps/studio/components/interfaces/Integrations/Integration/MarkdownContent.tsxapps/studio/components/ui/AIEditor/index.tsxapps/studio/hooks/branches/useEdgeFunctionsDiff.tsapps/studio/lib/configure-monaco-loader.tsapps/studio/lib/internal-url.test.tsapps/studio/lib/internal-url.tsapps/studio/lib/nuqs-tanstack-adapter.test.tsapps/studio/lib/nuqs-tanstack-adapter.tsxapps/studio/lib/router-search-params.test.tsapps/studio/lib/router-search-params.tsapps/studio/lib/router-url-shape.test.tsxapps/studio/next.config.tsapps/studio/pages/_app.tsxapps/studio/redirects.shared.test.tsapps/studio/redirects.shared.tsapps/studio/router.tsxapps/studio/routes/__root.tsxapps/studio/routes/index.tsxapps/studio/scripts/serve.jsapps/studio/security-headers.tsapps/studio/static-data/integrations/overviews.test.tsapps/studio/static-data/integrations/overviews.tsapps/studio/styles/fonts.cssapps/studio/types/markdown.d.tsapps/studio/vite.config.tse2e/studio/features/monaco-graphiql-coexistence.spec.ts
✅ Files skipped from review due to trivial changes (2)
- apps/studio/types/markdown.d.ts
- apps/studio/TANSTACK_MIGRATION.md
🚧 Files skipped from review as they are similar to previous changes (14)
- apps/studio/router.tsx
- apps/studio/security-headers.ts
- apps/studio/routes/index.tsx
- apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
- apps/studio/styles/fonts.css
- apps/studio/lib/router-search-params.ts
- apps/studio/redirects.shared.test.ts
- apps/studio/compat/next/router.test.ts
- apps/studio/scripts/serve.js
- apps/studio/routes/__root.tsx
- apps/studio/redirects.shared.ts
- apps/studio/lib/router-search-params.test.ts
- apps/studio/compat/next/router.ts
- apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
joshenlim
left a comment
There was a problem hiding this comment.
Tested changes locally, verified manually
- Fonts loading
- Monaco loading
- GraphiQL loading + typings
- Integrations markdown
- Edge Function typings
- Branching merge page crash
The other fixes, just checked through the code changes which generally look alright to me
Issues found
- SQL editor content query param -> doesn’t populate the editor content
- e.g Navigating to /project/_/sql/new?skip=true&content=select (Might be from the router stuff?)
Approving nonetheless 🙂 🙏
The TanStack __root.tsx hardcoded the prod favicon route, so local and hosted staging showed the prod icon. pages/_app.tsx passes /favicon/staging to MetaFaviconsPagesRouter for non-prod (per Joshen's review) — mirror that with the same synchronous NEXT_PUBLIC_ENVIRONMENT signal already used by IS_DEV_TOOLBAR_ENABLED (the head() route option can't run _app's async CLI check, but the env signal covers the reported local/staging case). Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/studio/routes/__root.tsx (1)
138-147: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicate non-prod condition with
IS_DEV_TOOLBAR_ENABLED.
FAVICON_ROUTE's ternary repeats the exact sameNEXT_PUBLIC_ENVIRONMENT === 'local' || 'staging'check already computed forIS_DEV_TOOLBAR_ENABLED(Lines 110-112). Consider extracting a sharedIS_NON_PROD_ENVconstant to avoid the two checks drifting independently later.♻️ Proposed refactor
+const IS_NON_PROD_ENV = + process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' || + process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging' + // Keep dev-only components out of the production bundle. -const IS_DEV_TOOLBAR_ENABLED = - process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' || - process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging' +const IS_DEV_TOOLBAR_ENABLED = IS_NON_PROD_ENV ... -const FAVICON_ROUTE = - process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' || - process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging' - ? '/favicon/staging' - : '/favicon' +const FAVICON_ROUTE = IS_NON_PROD_ENV ? '/favicon/staging' : '/favicon'🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/routes/__root.tsx` around lines 138 - 147, `FAVICON_ROUTE` repeats the same non-prod environment check already used for `IS_DEV_TOOLBAR_ENABLED`, so extract a shared `IS_NON_PROD_ENV` constant and use it in both places. Update the root route module so the environment logic is defined once near the existing `NEXT_PUBLIC_ENVIRONMENT` checks, then reference that constant in the `FAVICON_ROUTE` ternary to keep the non-prod behavior consistent and avoid future drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@apps/studio/routes/__root.tsx`:
- Around line 138-147: `FAVICON_ROUTE` repeats the same non-prod environment
check already used for `IS_DEV_TOOLBAR_ENABLED`, so extract a shared
`IS_NON_PROD_ENV` constant and use it in both places. Update the root route
module so the environment logic is defined once near the existing
`NEXT_PUBLIC_ENVIRONMENT` checks, then reference that constant in the
`FAVICON_ROUTE` ternary to keep the non-prod behavior consistent and avoid
future drift.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c22a768f-f1fc-4c46-8c24-66ef0f3392ad
📒 Files selected for processing (1)
apps/studio/routes/__root.tsx
- splitInternalUrl: compare against the parse base's origin unconditionally (not gated on window) so SSR no longer treats external absolute URLs like https://supabase.com/docs as internal paths; client behavior unchanged. - internal-url.test.ts: add SSR-mode cases (window stubbed undefined) — external absolute URL passes through untouched, relative path still splits. - __root.tsx: extract shared IS_NON_PROD_ENV const used by both IS_DEV_TOOLBAR_ENABLED and FAVICON_ROUTE (behavior identical). Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
… and migrations query 400s (#47667) App-level fixes that reproduce on BOTH the Next and TanStack builds — split out of #47657 (which stays TanStack-only) for reviewability. All were found by a full-site click-through of the dashboard. ## Invalid HTML nesting (React 19 "will cause a hydration error" console errors) - **FormLayout description rendered in a `<p>`** (`packages/ui-patterns`): consumers pass arbitrary JSX (the RowEditor's `created_at` timezone note passes a `<div>` with `<p>`s) → `<p>`-in-`<p>` / `<div>`-in-`<p>`. Container is now a `<div>` with identical classes (Tailwind preflight makes them render the same). - **Switch toggles nested inside Tooltip trigger buttons** (button-in-button) in ColumnEditor ("Allow Nullable" + "Is Unique"), ExtensionRow, and PublicationsTableItem → repo-standard `TooltipTrigger asChild` + `<div>` wrapper. - **Saved log queries rendered a `<div>` directly inside `<tbody>`** (`/logs/explorer/saved`) → rows are now proper `<tr><td colSpan>` wrappers; the component itself is untouched (it's valid in its sidebar usage). - **Nested anchors in observability metric cards**: a card-level `<Link>` wrapped MetricCard's "More information" `<Link>` (identical URLs) → the chevron affordance renders as a `<span>` when no `href` is passed; clicks bubble to the card link, tooltips preserved. Design-system standalone usage unaffected. - **`objectFit="cover"` passed to modern `next/image`** on the featured integration card (unknown-prop warning) — the className already had `object-cover`; prop dropped. ## Ghost dead-snippet after deletion Deleting the active SQL snippet left its id in `useDashboardHistory` (`history.sql`), so the "SQL Editor" nav item navigated to `/sql/<deleted-id>` — content fetch 404s, no editor pane renders, and a phantom tab reappears. Fixed both ends: delete flows now purge dashboard history (and the tabs store clears a stale `previewTabId`), and `/sql/[id]` treats a snippet 404 as "clean up + `router.replace` to `/sql/new` + toast" instead of rendering the dead state. Unit tests for the store/history cleanup. ## `pg-meta` migrations query 400s on every project load `ActivityStats` on project home runs the migrations list query, whose SQL was a bare `select * from supabase_migrations.schema_migrations` — that table only exists once a migration has run, so every other project logged a failed `?key=migrations` request on every load (visible in production consoles too). The SQL is now guarded with `to_regclass` + `query_to_xml` (same pattern as the advisor lints' `storage.buckets` guard), returning zero rows instead of erroring; legacy version-only tables still work. Tested against real dockerized Postgres (absent table, populated ordering, special chars, legacy schema) + MSW hook tests. Found and verified via /test-supabase-local (browser click-through + console audit on both builds). ## To test Console must stay free of React DOM-nesting errors ("cannot be a descendant of" / "cannot contain a nested") on each surface: 1. Table editor → Insert row panel (`created_at` field renders its timezone note) and Edit column panel ("Allow Nullable"/"Is Unique" tooltips still hover). 2. `/database/extensions` and `/database/publications` → toggle switches render, tooltips hover. 3. `/logs/explorer/saved` (with ≥1 saved query) → rows render full-width inside the table, hover shows Actions. 4. `/observability` → no nested-anchor error on load; card body click and the chevron both navigate; label help-icons still show tooltips. 5. `/integrations` → no `objectFit` unknown-prop warning; featured card images still cover. 6. **Ghost snippet**: open a SQL snippet → delete it via the sidebar → click the "SQL Editor" nav item → lands on `/sql/new` (no phantom tab, no 404 content fetch). Direct-load `/sql/<random-uuid>` → toast + redirect to `/sql/new`. 7. **Migrations 400**: load project home with a project that has never run a migration → the `pg-meta/<ref>/query?key=migrations` request returns **200** with `[]` (previously a 400 on every load). Database → Migrations still lists real migrations when they exist. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit * **Bug Fixes** * Deleted SQL snippets are fully removed from dashboard history and stale editor/tab state; users are redirected with a toast. * Closing preview tabs no longer leaves stale references. * Improved toggle/tooltip/dialog interactions to avoid broken UI, including metric headers showing tooltips even without direct links. * Migrations display safely when migration tables/relations are missing. * **UI Improvements** * Refreshed layout for saved queries, form descriptions, and integration imagery. * **Tests** * Added coverage for snippet history cleanup, tab removal, migrations SQL behavior, and query edge cases. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ### Review feedback: `query_to_xml` breaks on Multigres (Ivan) The defensive migrations query (added here to stop the `?key=migrations` 400 when the table doesn't exist yet) originally guarded with `query_to_xml`, which is forbidden through Multigres's pooler (MUL-736 / PSQL-1318). Rewritten without `query_to_xml`/`xmltable` using the splinter#170 pattern: a PL/pgSQL `do` block guarded by `to_regclass` (PL/pgSQL defers planning, so a missing table never errors) stashes the rows into a transaction-local GUC via `set_config`, and a trailing `select` reads them back with `jsonb_array_elements`. Verified that postgres-meta sends the whole SQL as one simple-query string → single implicit transaction → the local GUC survives to the `select` and doesn't leak into the pooled connection. 6/6 dockerized-Postgres tests (absent table → `[]`, populated/ordered/special-chars, legacy version-only table, full pg-meta-shaped multi-statement string, GUC non-leakage). Note (out of scope, pre-existing): `packages/pg-meta/src/sql/studio/advisor/lints.ts` still uses `query_to_xml` — a separate pre-existing Multigres risk that should get its own splinter-pattern sync. --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Joshen Lim <[email protected]> Co-authored-by: Saxon Fletcher <[email protected]>
Braintrust eval report
|
…ilent no-ops) (#47666) Stacked on #47657 (base is `alaister/tanstack-migration-fixes`; retarget to `master` once that merges). The TanStack runtime never ran `Sentry.init` — `instrumentation-client.ts` is a Next-convention file nothing imports under TanStack Start, so every `Sentry.captureException` on that build (including the `routes/__root.tsx` error-boundary / `routerErrorComponent` reports) was a silent no-op. - **Shared config source**: the entire client config moves verbatim from `instrumentation-client.ts` into `lib/sentry-client-options.ts` (`buildSentryClientOptions`). Both runtimes build from it, so Next and TanStack can't drift — the builds differ only in two explicit knobs. - **TanStack init**: `sentry.tanstack.ts` initializes `@sentry/react` from `getRouter()` (TanStack Start's real client bootstrap — the earliest point with the router instance), wiring `tanstackRouterBrowserTracingIntegration(router)`. Window-guarded + idempotent; `router.tsx` is TanStack-only so the Next build is untouched. (Named without `.client.` — Start's import-protection fails the build for `*.client.*` in the server graph.) - **Third-party error filter is intentionally Next-only**: without the bundler-injected `applicationKey` metadata (only `withSentryConfig` provides it), the SDK tags *every* event `third_party_code: true` and `beforeSend` would drop them all — recreating the silent no-op with a DSN set. Follow-up: add `@sentry/vite-plugin` moduleMetadata, then enable. - **DSN-less builds stay crash-free**: `vite.config.ts` inlines `undefined` for unset `NEXT_PUBLIC_SENTRY_DSN`/`NEXT_PUBLIC_SENTRY_ENVIRONMENT` (a literal `process.env.*` in the bundle is the exact `process is not defined` class #47657 fixed). No-DSN → disabled client, plus the existing `IS_PLATFORM`/consent gates. - Tests: `instrumentation-client.test.ts` moved to `lib/sentry-client-options.test.ts` with all 36 assertions kept, plus integration-gating and Next/TanStack parity tests. `tsc` clean; full `vite build --mode test` passes. Follow-up (separate): server-side Sentry for the Start handler (`server.ts` entry + `@sentry/node`-style init). ## To test - **Locally (no DSN set)**: load the TanStack build — no Sentry network requests, no console errors, and crucially no `ReferenceError: process is not defined` (the define fallback). Forcing an error must not POST to any `/envelope` endpoint. - **On a preview/deploy (DSN set, telemetry consent accepted)**: throw a test error (e.g. crash a route component) → a POST to `o…ingest.sentry.io/api/…/envelope/` fires, and the event lands in Sentry with a `codeSampleRate` tag and **no** `third_party_code` tag. Navigation spans named after TanStack routes appear when the 2% pageload trace samples in. - **Next build regression check**: the Next dev/preview still reports errors exactly as before (`instrumentation-client.ts` now builds its options from the same shared source). --- ### Review feedback: Sentry `/envelope` never fires on TanStack (Joshen) Root-caused: `@sentry/core`'s `Client.sendSession` silently drops the session when the client has no `release`. The Next build gets a release injected by `withSentryConfig` (the Vercel commit SHA); the Vite build runs no Sentry bundler plugin, so it had no release → session envelopes were discarded before transport → zero `/envelope` traffic (errors/transactions are separate). Fix: inject `release: NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA` on the TanStack build (vite.config re-exposes `VERCEL_GIT_COMMIT_SHA` under the `NEXT_PUBLIC_` name, same SHA the Next release resolves to). Also switched `integrations` to the function form so defaults are preserved by contract (not just by current SDK behavior). 45 unit tests green. **To test (deploys only — the SHA is unset locally, so this can't be reproduced on a local dev build):** on this PR's Vercel preview with a DSN + telemetry consent, load any page and watch the Network tab for a POST to `…ingest.sentry.io/…/envelope/` — a session envelope should now fire on load, matching the Next build. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved client-side error and performance monitoring for the Studio app across both router setups. * Added support for passing release/version information into monitoring data. * **Bug Fixes** * Reduced noisy error reporting by better filtering common browser, extension, cancellation, and load-related issues. * Prevented browser bundles from referencing missing environment values at runtime. * Made monitoring initialization safer in server-rendered and client-only environments. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <[email protected]>
) (#47119) **Stack 6/6 (final)** of the TanStack Start migration (#46424). The middle slices (#47107 → #47118) have all merged, so this now sits directly on master. ## What's in this PR One file: `.github/workflows/studio-e2e-test.yml` — adds `framework: [next, tanstack]` to the test/report matrices and sets `STUDIO_FRAMEWORK` (consumed by `scripts/dispatch.js`). Until now CI only built/tested Next. This flips on the dual-framework E2E matrix so the TanStack build gets exercised end-to-end on every run. ##⚠️ Depends on #47657 (merge that first) The `tanstack` shard needs the Monaco loader fix in **#47657** to be on master. Quick version: master's #47182 re-nested the Monaco assets under `public/monaco-editor/vs/` and the TanStack root was still pointing at the old flat path, so Monaco didn't mount anywhere in the TanStack build and every editor-backed test timed out (RLS, cron SQL, realtime JSON, db functions, GraphiQL). Kept that fix on its own branch rather than piling it onto this one. Merge order: 1. #47657 → master 2. re-merge master into here (I'll cascade it) 3. `tanstack` shard goes green → merge this ##⚠️ Branch-protection note This renames the E2E jobs (`E2E tests` → `E2E tests (next|tanstack, shard)`), so master's current required status checks (`E2E tests (1, 2)` / `(2, 2)`) stop being reported. The required-check list in branch protection needs updating to the new names when this merges. ## Verification Config-only, no app code. The real validation is this matrix running both shards green once #47657 lands — the `next` shards already pass here; the `tanstack` shards pass once the Monaco fix is on master. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Integration overview markdown can now be loaded more reliably from a synchronized on-disk registry (raw markdown support). * **Bug Fixes** * Navigation, redirects, and prefetch now preserve query strings and hash fragments more consistently using Next-like semantics (including repeated keys, empty clearing, and lossless encoding like newlines). * Improved internal-link/router compatibility for Next-style `?`/`#` targets and base-path handling. * Edge Functions diff tab matching works correctly in the browser without Node-specific path utilities. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Ivan Vasilov <[email protected]>
… @sentry/nextjs compat alias The stub's only real-world importer was @sentry/nextjs's isBuild.js, which the @sentry/nextjs -> compat/sentry-nextjs.ts alias (already on master via #47657) removes from the browser graph entirely. Dropping it brings this branch to a zero diff against master.
Post-merge fixes for the TanStack Start migration (#46424) — things that broke on the TanStack build as master evolved under the migration branches. Kept on their own branch off master rather than piling onto the E2E-matrix PR (#47119); all land on master and cascade up to S6 + the big PR.
Common theme: a master PR changed something the Next pipeline handles via
next/font/pages/_app.tsx/next.config.ts, but the hand-rolled TanStack equivalent (routes/__root.tsx,styles/fonts.css,vercel.ts) wasn't updated to match — invisible on the Next deploy, broken only on TanStack.1. Monaco loader path (#47182)
#47182 re-nested the served Monaco assets from a flat
public/monaco-editor/layout intopublic/monaco-editor/vs/and updatedpages/_app.tsx, butroutes/__root.tsxstill pointedloader.configat the old path, soloader.js404'd and no Monaco editor mounted anywhere in the TanStack build. Now mirrors the Next config (${origin}${BASE_PATH}/monaco-editor/vs, window-guarded for SSR). Was failing the wholetanstackE2E shard on #47119.2. Inter + Manrope fonts (#47306)
#47306 renamed Tailwind's sans var
--font-custom→--font-sansand added--font-heading(Manrope), set vianext/fonton Next.fonts.cssstill only set the now-ignored--font-custom, so the body fell back to the theme's system chain (Circular, custom-font, Helvetica…) at weight 450 — that's the "Inter weights look wrong". Manrope was missing entirely.--font-sans(Inter) +--font-heading(Manrope) to matchnext/font.@font-faceso nothing depends on the Google Fonts CDN — matchesnext/fontself-hosting, and (see below)font-srcdoesn't allowfonts.gstatic.comanyway.Verified in-browser: computed
body→Inter, headings →Manrope, all loading from local/assets/*.woff2.3. Security headers / CSP (next.config.ts
headers())The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / Content-Security-Policy / Referrer-Policy via
next.config.ts. The TanStack build never carried these over —vercel.tsonly set cache-control, so the deployed TanStack dashboard shipped with no CSP at all.The TanStack deploy serves a static shell (no server to attach headers), so they go in the Vercel config:
security-headers.ts— shared source of truth, reusesgetCSP(), env-gated exactly like next.config.vercel.ts— apply to every response (all base-path prefixes): fullgetCSP()+ HSTS on platform.scripts/serve.js— the non-platform set (frame-ancestors 'none') for the self-hosted server.Tested the policy in a real browser (temporarily enforced it on the TanStack build via /test-supabase-local): everything passed except one real gap —
font-srcwas missingdata:, so GraphiQL's bundled Monaco codicon font and Stripe's payment-element fonts (both data: URIs) were blocked (37 violations on a cold load). Addeddata:tofont-srcincsp.ts→ violations drop to zero, SQL editor Monaco renders clean. That gap affects the Next build too.4.
node:pathimport crashing/project/[ref]/mergeFound by a full-site click-through of the TanStack build (all product areas, ongoing — see below).
useEdgeFunctionsDiff.ts+EdgeFunctionsDiffPanel.tsxdidimport { basename } from 'path'in client code. Webpack (Next) polyfillspathin the browser; Vite externalizes it, so the whole/mergeroute crashed with "Module "path" has been externalized for browser compatibility". Replaced the twobasenamecall sites with a string helper. Verified in-browser:/mergerenders.5. URL shape — Next-style search-param semantics + shim fixes
The dashboard produced malformed URLs vs the Next build (strange query params, trailing slashes,
##hashes). Root cause + audit verified empirically against@tanstack/[email protected]; all fixed with unit tests and browser-verified:createRouterused TanStack's default JSON search codec —?flag=truebecame?flag=%22true%22via links, repeated?filter=…&filter=…collapsed into a JSON array (breaking multi-filter/sort table-editor URLs and the account-page round-trip, which double-encoded), and search values arrived as numbers/booleans where the app expects strings. Newlib/router-search-params.ts(Next-style: strings in, strings out, repeated keys → string[]) wired into the router.compat/next/link.tsx):URL.hashincludes the leading#while TanStack'shashprop adds its own → everyhref="…#section"navigated to##section(hash-scroll broke);Object.fromEntries(searchParams)dropped repeated query params. Both fixed.?-only relative navigation (/auth/providers/?provider=…): fixed in the compat router (prefix current pathname) and via a custom nuqs adapter (lib/nuqs-tanstack-adapter.tsx) replacing the stock tanstack-router adapter, whosenavigate({ to: '?…' })writes hit the same TanStack behavior (123 files use nuqs).router.push({ query })leaked path params — Next re-consumesref/idfromqueryinto the path pattern; the shim didn't, yielding/editor/17597?schema=public&ref=<ref>&id=17597&filter=…from table-editor filter/sort, linter panels, and advisor shortcuts. The shim now defaults the pathname to the current route pattern and backfills omitted params.redirects()preserves them):__root.tsxmatchRedirectandroutes/index.tsxnow carry incoming params/hash through (consumed rule params excluded, destination's own params win)./?next=new-project&projectName=zzz→/new/new-project?projectName=zzz;/sql/quickstarts?template=x#frag→/sql/examples?template=x#frag.Browser-verified post-fix: advisors
?preset=WARN, providers?provider=Google,?schema=auth— all clean (no/?, no leaks); repeatedfilterparams survive hydration;=trueunquoted; single#.6. TanStack
navigatecorrupting query values (Logs Explorer SQL newline loss)TanStack router-core treats a query string embedded in
navigate({ to })as part of the path:decodePathpercent-decodes it andsanitizePathSegmentstrips control characters, silently deleting every%0A. Logs Explorer's SQL (sparam) lost its newlines on Run/reload —order by timestamp desc/limit 5glued intodesclimit 5, which then failed the LIMIT lint. Pre-existing on the TanStack build (the stock nuqs adapter had the same shape); Next unaffected.Fixed by never embedding query strings in
to: the nuqs adapter and the compatrouter.push/replace/prefetch(plus thenext/navigationshim) now pass search as an object through the app codec (splitInternalUrlhoisted tolib/internal-url.ts). Guard test drives a realcreateRouterwith multi-line SQL through both producers. Browser-verified: newlines survive the full Run → reload → re-Run cycle.7. Integration overview markdown never loaded (all integrations)
MarkdownContentused a template-literal dynamic import (import(`@/static-data/integrations/${id}/overview.md`)) — webpack builds a context module for that, Vite can't analyze it, so every integration detail page threwFailed to resolve module specifierand rendered no overview text. Fixed with an explicit lazy registry of literal imports (static-data/integrations/overviews.ts, drift-guarded by a test) plus anmdRawLoader()Vite plugin mirroring next.config's turbopack raw-loader rule. Both runtimes keep working; md stays out of the main bundle.8. GraphiQL editor never mounted (
exports is not defined)Our
umdAmdShortCircuit()Vite plugin (which disarms Monaco's global AMD loader for deps like papaparse) rewrotetypeof define === 'function' && define.amdtofalseinsidemonaco-editor's bundled copy of marked — whose UMD relies on its own localdefineshim — so the whole optimized monaco chunk failed to evaluate and GraphiQL's editor pane stayed blank. The check now only short-circuits whendefineis the global AMD loader. Browser-verified: all four GraphiQL Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco workers fall back to the main thread under Vite — functional, worker wiring is Next-specificsetup-workers/webpack.)9.
@sentry/nextjsbundling Next internals — built TanStack bundle crashed (caught by E2E)The E2E suite against the built TanStack bundle (not the dev server) found lazy chunks like
table-editor-*.jsdead on arrival:@sentry/nextjs(imported by ~25 client files) drags innext/dist/shared/lib/constants, whose module scope evaluatesprocess?.features?.typescript— optional chaining doesn't guard an undeclaredprocessin the browser, so the whole chunk failed at load withReferenceError: process is not defined. Dev shimsprocess, which is why weeks of dev-server testing never saw it.Fixed by aliasing
@sentry/nextjs→compat/sentry-nextjs.ts(re-exports@sentry/react, same deduped 10.59.0, plus explicit stand-ins for the three Next-only APIs) in the Vite build only. Verified: fresh build has zero Next-internals markers in any chunk; table editor loads clean; full E2E suite run against the built bundle.Note for the stack:
alaister/tanstack-start/ the E2E-matrix branch already carried a different fix for the same crash (anext/constantsshim) that never made it to master — the cherry-pick onto those branches keeps both (the shim covers any other transitive importer; the alias keeps Next internals out of the client bundle entirely).Follow-up found while fixing: Sentry is never initialized in the TanStack runtime —
instrumentation-client.ts/sentry.server.config.tsare Next-convention files nothing imports under TanStack, socaptureExceptioncalls are silent no-ops. Needs an@sentry/reactinit (+tanstackRouterBrowserTracingIntegration) wired into the TanStack client entry as its own PR.10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only gaps)
setup-workers/webpack'snew URL(...)form isn't rewritten by Vite). AgraphiqlViteWorkers()plugin resolves the import to graphiql's ownsetup-workers/vitevariant for client builds (SSR untouched, Next untouched); the setup-workers chain isoptimizeDeps.excluded because the Rolldown optimizer can't load?workerids.AIEditorloadedpublic/deno/*.d.tsvia/* @vite-ignore */imports that always failed at runtime under Vite. The.mdraw loader is generalized intorawTextLoader(exact-path allowlist for the two typings files, served as virtual string modules so the dep scanner never parses.d.tssyntax), and the imports are now static-analyzable literals that both bundlers handle (turbopack's raw-loader rules match them on the Next side).Split out for reviewability
App-level fixes that reproduce on the Next build too (DOM-nesting hydration errors, the ghost deleted-snippet nav, the recurring pg-meta
migrations400) moved to their own PR: #47667. Sentry initialization for the TanStack runtime (captures were silent no-ops) is #47666, stacked on this PR.Full-site test campaign
Drove every dashboard product area on the local TanStack build (Playwright, human-style) hunting migration regressions: redirects/404/catch-alls, org, account, project home/branches/merge, table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all database pages, all auth pages, storage CRUD, edge functions + realtime, logs/observability, advisors, settings, integrations hub incl. nested routes, global UI (palette/connect/switchers/theme/fonts), and a cross-cutting sweep (document titles, back/forward chain, hard-refresh hydration on deep URLs, trailing-slash active state). Every failure found is fixed above and re-verified in-browser; remaining console quirks were cross-checked against the deployed Next build and are pre-existing (tracked separately).
To test
Most fixes are already browser-verified + covered by unit tests and the self-hosted E2E suite; the last two landed after the final browser pass and still need an in-browser check:
apps/studio/node_modules/.viteonce first — the optimizer cache may hold a stale prebundle of the worker chain). Open/project/<ref>/integrations/graphiql/graphiqlwith the console open: theCould not create web worker(s). Falling back to loading web worker code in main threadwarning must be gone, and DevTools → Sources → Threads shows the three workers (json, editor, graphql). Autocomplete in the query editor stays responsive./project/<ref>/functions/new: no "Failed to load … typings" console error, and typingDeno.in the editor offers typed completions (e.g.Deno.env).Spot-checks for the rest (all previously verified):
/project/<ref>/mergerenders (no "Module path" crash).desclimitgluing, no LIMIT-lint false failure);sparam keeps%0A./auth/providers→ open a provider →?provider=…with no trailing slash before?; table-editor filter/sort URLs carry no leakedref/idparams;/?next=new-project&projectName=xlands on/new/new-project?projectName=x.MODE=test vite build+start:tanstack): table editor loads with noprocess is not defined.curl -sIany page on a platform deploy:X-Content-Type-Options: nosniff(was the invalidno-sniff).Summary by CodeRabbit
Review feedback: non-prod favicon (Joshen)
The TanStack
__root.tsxhardcoded the prod favicon; local + hosted staging now use the white staging favicon (/favicon/staging), matching whatpages/_app.tsxpasses toMetaFaviconsPagesRouterfor non-prod. Rather than pull the pages-router component into the TanStack head, it reuses the same synchronousNEXT_PUBLIC_ENVIRONMENTsignal the file already uses forIS_DEV_TOOLBAR_ENABLED(thehead()route option isn't a React component, so it can't run_app's async CLI check — but the env signal covers the reported local/staging case).