Repository navigation
fix(studio): initialize Sentry on the TanStack build (captures were silent no-ops) - #47666
Conversation
|
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 (8)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughSentry client configuration is extracted from Next.js instrumentation into a shared ChangesSentry client options extraction and consumption
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Router as getRouter
participant Init as initSentryTanStackClient
participant Options as buildSentryClientOptions
participant Sentry as Sentry (react)
Router->>Init: initSentryTanStackClient(router)
Init->>Init: check window / initialized guard
Init->>Options: buildSentryClientOptions({includeThirdPartyErrorFilter:false, extraIntegrations, release})
Options-->>Init: BrowserOptions
Init->>Sentry: Sentry.init(options)
Router->>Router: setupRouterSsrQueryIntegration
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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
Flaky testsFeatures › realtime-inspector.spec.ts › Realtime Inspector › Message Display › messages counter shows correct count Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/studio/lib/sentry-client-options.ts (1)
103-118: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the typed named export here.
thirdPartyErrorFilterIntegrationis exposed by@sentry/react, so importing it directly removes theanycast and avoids a silent no-op if the symbol ever disappears.🤖 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/sentry-client-options.ts` around lines 103 - 118, The Sentry third-party error filter setup in buildThirdPartyErrorFilterIntegration is using an untyped access through (Sentry as any), which should be replaced with the typed named export from `@sentry/react`. Import thirdPartyErrorFilterIntegration directly, use that symbol in the null check and integration निर्माण, and remove the any cast so the code fails clearly if the export is unavailable instead of silently no-oping.apps/studio/sentry.tanstack.ts (1)
29-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo test coverage for the new initializer.
initSentryTanStackClienthas multiple testable branches (SSR no-op, double-init guard, options passed toSentry.init) but there's no accompanying test file in this PR. Per the Studio Testing guidelines, extracted init/utility logic like this should get coverage (e.g., mocking@sentry/reactand assertingSentry.initis called exactly once across repeated invocations, and not called whenwindowis undefined).As per path instructions for
apps/studio/**: "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/sentry.tanstack.ts` around lines 29 - 42, The new initSentryTanStackClient initializer lacks test coverage for its SSR no-op, single-run guard, and Sentry.init wiring. Add a test file for the sentry.tanstack module that mocks `@sentry/react` and verifies initSentryTanStackClient does not initialize when window is undefined, calls Sentry.init with the expected options when run in the browser, and only initializes once across repeated calls by exercising the initialized guard.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.
Nitpick comments:
In `@apps/studio/lib/sentry-client-options.ts`:
- Around line 103-118: The Sentry third-party error filter setup in
buildThirdPartyErrorFilterIntegration is using an untyped access through (Sentry
as any), which should be replaced with the typed named export from
`@sentry/react`. Import thirdPartyErrorFilterIntegration directly, use that symbol
in the null check and integration निर्माण, and remove the any cast so the code
fails clearly if the export is unavailable instead of silently no-oping.
In `@apps/studio/sentry.tanstack.ts`:
- Around line 29-42: The new initSentryTanStackClient initializer lacks test
coverage for its SSR no-op, single-run guard, and Sentry.init wiring. Add a test
file for the sentry.tanstack module that mocks `@sentry/react` and verifies
initSentryTanStackClient does not initialize when window is undefined, calls
Sentry.init with the expected options when run in the browser, and only
initializes once across repeated calls by exercising the initialized guard.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1708006c-f2b9-493a-a741-1f1d15286795
📒 Files selected for processing (7)
apps/studio/.github/eslint-rule-baselines.jsonapps/studio/instrumentation-client.tsapps/studio/lib/sentry-client-options.test.tsapps/studio/lib/sentry-client-options.tsapps/studio/router.tsxapps/studio/sentry.tanstack.tsapps/studio/vite.config.ts
| // convention file that nothing loads under TanStack Start. Without this init | ||
| // every `Sentry.captureException` in the TanStack runtime (including the | ||
| // globalErrorBoundary / routerErrorComponent captures in routes/__root.tsx) | ||
| // would be a silent no-op. |
There was a problem hiding this comment.
Review context (moved out of the code comment): before this PR, nothing initialized Sentry on the TanStack build at all — so the globalErrorBoundary / routerErrorComponent captureException calls in routes/__root.tsx were silently no-oping. This file is the fix.
…rom #46424) (#47657) 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 into `public/monaco-editor/vs/` and updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed `loader.config` at the old path, so `loader.js` 404'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 whole `tanstack` E2E shard on #47119. ## 2. Inter + Manrope fonts (#47306) #47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and added `--font-heading` (Manrope), set via `next/font` on Next. `fonts.css` still 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. - Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match `next/font`. - **Vendor all three families** (Inter, Manrope, Source Code Pro) via `@font-face` so nothing depends on the Google Fonts CDN — matches `next/font` self-hosting, and (see below) `font-src` doesn't allow `fonts.gstatic.com` anyway. 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.ts` only 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, reuses `getCSP()`, env-gated exactly like next.config. - `vercel.ts` — apply to every response (all base-path prefixes): full `getCSP()` + 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-src` was missing `data:`, so GraphiQL's bundled Monaco codicon font and Stripe's payment-element fonts (both data: URIs) were blocked (37 violations on a cold load). Added `data:` to `font-src` in `csp.ts` → violations drop to zero, SQL editor Monaco renders clean. That gap affects the Next build too. --- ## 4. `node:path` import crashing `/project/[ref]/merge` Found by a full-site click-through of the TanStack build (all product areas, ongoing — see below). `useEdgeFunctionsDiff.ts` + `EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in client code. Webpack (Next) polyfills `path` in the browser; Vite externalizes it, so the whole `/merge` route crashed with "Module \"path\" has been externalized for browser compatibility". Replaced the two `basename` call sites with a string helper. Verified in-browser: `/merge` renders. ## 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: - **`createRouter` used TanStack's default JSON search codec** — `?flag=true` became `?flag=%22true%22` via 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. New `lib/router-search-params.ts` (Next-style: strings in, strings out, repeated keys → string[]) wired into the router. - **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the leading `#` while TanStack's `hash` prop adds its own → every `href="…#section"` navigated to `##section` (hash-scroll broke); `Object.fromEntries(searchParams)` dropped repeated query params. Both fixed. - **Trailing slash injected before the query** on every `?`-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, whose `navigate({ to: '?…' })` writes hit the same TanStack behavior (123 files use nuqs). - **Pathname-less `router.push({ query })` leaked path params** — Next re-consumes `ref`/`id` from `query` into 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 dropped query + hash** (Next's `redirects()` preserves them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now 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); repeated `filter` params survive hydration; `=true` unquoted; single `#`. ## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL newline loss) TanStack router-core treats a query string embedded in `navigate({ to })` as part of the *path*: `decodePath` percent-decodes it and `sanitizePathSegment` strips control characters, silently deleting every `%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload — `order by timestamp desc` / `limit 5` glued into `desclimit 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 compat `router.push`/`replace`/`prefetch` (plus the `next/navigation` shim) now pass search as an object through the app codec (`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives a real `createRouter` with 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) `MarkdownContent` used 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 threw `Failed to resolve module specifier` and rendered no overview text. Fixed with an explicit lazy registry of literal imports (`static-data/integrations/overviews.ts`, drift-guarded by a test) plus an `mdRawLoader()` 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) rewrote `typeof define === 'function' && define.amd` to `false` inside `monaco-editor`'s bundled copy of marked — whose UMD relies on its own *local* `define` shim — so the whole optimized monaco chunk failed to evaluate and GraphiQL's editor pane stayed blank. The check now only short-circuits when `define` is 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-specific `setup-workers/webpack`.) ## 9. `@sentry/nextjs` bundling 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-*.js` dead on arrival: `@sentry/nextjs` (imported by ~25 client files) drags in `next/dist/shared/lib/constants`, whose module scope evaluates `process?.features?.typescript` — optional chaining doesn't guard an undeclared `process` in the browser, so the whole chunk failed at load with `ReferenceError: process is not defined`. Dev shims `process`, 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 (a `next/constants` shim) 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.ts` are Next-convention files nothing imports under TanStack, so `captureException` calls are silent no-ops. Needs an `@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired into the TanStack client entry as its own PR. ## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only gaps) - **GraphiQL's Monaco workers ran on the main thread** under Vite ("Could not create web worker(s)…" — `setup-workers/webpack`'s `new URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()` plugin resolves the import to graphiql's own `setup-workers/vite` variant for client builds (SSR untouched, Next untouched); the setup-workers chain is `optimizeDeps.exclude`d because the Rolldown optimizer can't load `?worker` ids. - **Edge-function editors silently lost their Deno typings** — `AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports that always failed at runtime under Vite. The `.md` raw loader is generalized into `rawTextLoader` (exact-path allowlist for the two typings files, served as virtual string modules so the dep scanner never parses `.d.ts` syntax), 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 `migrations` 400) 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: 1. **GraphiQL Monaco workers** — restart the dev server (clear `apps/studio/node_modules/.vite` once first — the optimizer cache may hold a stale prebundle of the worker chain). Open `/project/<ref>/integrations/graphiql/graphiql` with the console open: the `Could not create web worker(s). Falling back to loading web worker code in main thread` warning must be gone, and DevTools → Sources → Threads shows the three workers (json, editor, graphql). Autocomplete in the query editor stays responsive. 2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no "Failed to load … typings" console error, and typing `Deno.` in the editor offers typed completions (e.g. `Deno.env`). Spot-checks for the rest (all previously verified): - `/project/<ref>/merge` renders (no "Module path" crash). - Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit` gluing, no LIMIT-lint false failure); `s` param keeps `%0A`. - `/auth/providers` → open a provider → `?provider=…` with no trailing slash before `?`; table-editor filter/sort URLs carry no leaked `ref`/`id` params; `/?next=new-project&projectName=x` lands on `/new/new-project?projectName=x`. - Integration detail pages (cron/queues/vault/data_api) show their overview prose; GraphiQL query editor mounts. - Built bundle (`MODE=test vite build` + `start:tanstack`): table editor loads with no `process is not defined`. - `curl -sI` any page on a platform deploy: `X-Content-Type-Options: nosniff` (was the invalid `no-sniff`). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Centralized integration overview markdown loading with registry-based lookup. * Improved Monaco loading/asset path handling for smoother editor startup. * **Bug Fixes** * Next-style navigation/search handling now preserves pathname, hash, repeated query keys, and special characters (including newlines). * Redirects now reliably carry over query and hash with correct precedence. * **Security/Configuration** * Updated CSP font sourcing and unified security headers delivery across environments; conditional HSTS behavior. * Refreshed font CSS variables and font-face definitions to match the theme. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ### Review feedback: non-prod favicon (Joshen) The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted staging now use the white staging favicon (`/favicon/staging`), matching what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod. Rather than pull the pages-router component into the TanStack head, it reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` 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). --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Joshen Lim <[email protected]>
…ilent no-ops) Nothing loads Next's convention files (instrumentation-client.ts) under TanStack Start, so the TanStack runtime never called Sentry.init — every Sentry.captureException there (including the globalErrorBoundary and routerErrorComponent captures in routes/__root.tsx) was a silent no-op. - Extract the entire client config (DSN/environment envs, sample rates, integrations, allowUrls, beforeBreadcrumb, beforeSend filters, ignoreErrors) from instrumentation-client.ts into a shared builder, lib/sentry-client-options.ts, so the two runtimes cannot drift. instrumentation-client.ts now just calls Sentry.init with it. - Add sentry.tanstack.ts, called from getRouter() (router.tsx) — the earliest point with access to the router instance — wiring tanstackRouterBrowserTracingIntegration for pageload/navigation spans. Guarded to the browser (getRouter also runs during SSR/prerender) and idempotent. Not named *.client.* on purpose: TanStack Start's import-protection denies such modules in the server bundle. - thirdPartyErrorFilterIntegration stays Next-only: the Vite build runs no Sentry bundler plugin, so frames carry no applicationKey metadata and the integration would tag EVERY event third_party_code=true — beforeSend would then drop all non-error-boundary events. Follow-up: annotate via @sentry/vite-plugin moduleMetadata, then enable it. - vite.config.ts: inline `undefined` for unset NEXT_PUBLIC_SENTRY_DSN / NEXT_PUBLIC_SENTRY_ENVIRONMENT so self-hosted builds without a DSN don't ship a literal `process.env.*` (undeclared `process` throws in the browser). With no DSN the init is a clean no-op. - Move instrumentation-client.test.ts to lib/sentry-client-options.test.ts and add coverage for the integration gating and Next/TanStack parity. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- Use the typed named thirdPartyErrorFilterIntegration export from @sentry/react instead of an untyped (Sentry as any) lookup, so the build fails loudly if the export ever disappears (verified present in @sentry/react 10.59.0). - Add sentry.tanstack.test.ts covering the initializer: no init during SSR (no window), browser init with the shared options and DSN gating, exactly one init across repeated calls (including SSR-then-browser ordering), and the TanStack Router tracing integration wiring with the third-party filter left off. - Rename the thirdPartyErrorFilter option to includeThirdPartyErrorFilter and the module flag to isInitialized per studio boolean-naming conventions. - Ratchet the no-explicit-any baseline down for the removed cast. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
On the TanStack build Sentry initialized but never sent any /envelope requests, while the Next build sends a session envelope on every page load. Root cause: the SDK silently drops session envelopes when the client has no release — Client.sendSession in @sentry/[email protected] early- returns when neither the session nor the client options carry one. The Next build gets its release injected into the bundle at build time by withSentryConfig (SENTRY_RELEASE ?? the Vercel commit SHA); the Vite build runs no Sentry bundler plugin, so its client had no release and browserSessionIntegration's captured sessions were discarded before reaching the transport. Fix: vite.config.ts re-exposes VERCEL_GIT_COMMIT_SHA as NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA (with an inlined-undefined fallback off Vercel) and sentry.tanstack.ts passes it as the release — the same value the Next build's release resolves to. The shared builder only emits the release key when one is provided: a release: undefined entry would override the Next build's injected release, since @sentry/nextjs spreads user options last. Also switch the shared integrations option from a plain array to the documented function form ((defaults) => [...defaults, ...ours]). At @sentry/[email protected] the array form already merged with the default integrations, so this is behavior-preserving — but the function form states the add-don't-replace intent explicitly and is guaranteed by the SDK contract rather than by getIntegrationsToSetup's merge behavior. Tests now invoke the function with representative defaults (BrowserSession, GlobalHandlers) and assert they survive the merge on both builds. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
No code change — Vercel was switched to build this branch with TanStack, so this empty commit kicks a fresh preview build to confirm the session /envelope fix (release injection) fires end-to-end on a deploy. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Real file change to trigger the TanStack Vercel build (the prior empty commit was skipped by Vercel's change detection) so the session /envelope fix can be confirmed on the preview. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
d0155f6 to
3f65818
Compare
…n on the TanStack build Hybrid Sentry setup for the TanStack Start build: - Server: use the unified `@sentry/tanstackstart-react` SDK (pinned to 10.59.0 to share the single @sentry/core hub) for server instrumentation. `sentryGlobalRequestMiddleware` + `sentryGlobalFunctionMiddleware` wrap the whole request / server-function lifecycle — capturing request- and function-scoped errors, including ones downstream code swallows into a 500 that the manual `@sentry/nextjs` path never sees — and `wrapFetchWithSentry` wraps the fetch handler on both Vercel (api/server.js) and self-hosted (scripts/serve.js). `instrument.server.mjs` mirrors sentry.server.config.ts (dsn/environment/tracesSampleRate/ignoreErrors) + release for source maps. `sentryTanstackStart()` runs last in vite.config for source-map/release upload (skipped gracefully without SENTRY_AUTH_TOKEN); middleware auto-wrap is disabled since start.ts wires the middlewares explicitly. - Client: stays on `@sentry/react` (via #47666's `@sentry/nextjs` → compat shim alias). The unified SDK's browser `tanstackRouterBrowserTracingIntegration` is a no-op stub (returns undefined → TypeError), so the client keeps the verified `@sentry/react` integration. The server files import `@sentry/tanstackstart-react` directly — they only run in the SSR/Node bundle, so the broken browser export never loads. Verified the server SDK (`@sentry/node`, global middlewares) does not leak into the client bundle. - Next.js build path (instrumentation.ts / sentry.server.config.ts / next.config.ts) is untouched. Supersedes the manual `@sentry/node` server wrapper. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Braintrust eval report
|
…n on the TanStack build Hybrid Sentry setup for the TanStack Start build: - Server: use the unified `@sentry/tanstackstart-react` SDK (pinned to 10.59.0 to share the single @sentry/core hub) for server instrumentation. `sentryGlobalRequestMiddleware` + `sentryGlobalFunctionMiddleware` wrap the whole request / server-function lifecycle — capturing request- and function-scoped errors, including ones downstream code swallows into a 500 that the manual `@sentry/nextjs` path never sees — and `wrapFetchWithSentry` wraps the fetch handler on both Vercel (api/server.js) and self-hosted (scripts/serve.js). `instrument.server.mjs` mirrors sentry.server.config.ts (dsn/environment/tracesSampleRate/ignoreErrors) + release for source maps. `sentryTanstackStart()` runs last in vite.config for source-map/release upload (skipped gracefully without SENTRY_AUTH_TOKEN); middleware auto-wrap is disabled since start.ts wires the middlewares explicitly. - Client: stays on `@sentry/react` (via #47666's `@sentry/nextjs` → compat shim alias). The unified SDK's browser `tanstackRouterBrowserTracingIntegration` is a no-op stub (returns undefined → TypeError), so the client keeps the verified `@sentry/react` integration. The server files import `@sentry/tanstackstart-react` directly — they only run in the SSR/Node bundle, so the broken browser export never loads. Verified the server SDK (`@sentry/node`, global middlewares) does not leak into the client bundle. - Next.js build path (instrumentation.ts / sentry.server.config.ts / next.config.ts) is untouched. Supersedes the manual `@sentry/node` server wrapper. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…n on the TanStack build (#47724) Stacked on #47666 (base `alaister/tanstack-sentry-init`; retarget to `master` when that merges). **Supersedes #47721** (the manual `@sentry/node` wrapper). Client stays on #47666's `@sentry/react` setup. Adopts the official `@sentry/tanstackstart-react` SDK **on the server only**, after a spike (#47723) evaluating the full unified client+server SDK. The spike found the SDK's **browser** `tanstackRouterBrowserTracingIntegration` is a broken no-op stub at 10.59.0/10.64.0 — so the client stays on `@sentry/react` (whose equivalent integration is a real, working implementation, already shipped in #47666). The **server** exports, however, are a clear upgrade and slot in cleanly. ### What this adds (server-side, TanStack build only) - **`instrument.server.mjs`** — `Sentry.init` from `@sentry/tanstackstart-react`, mirroring `sentry.server.config.ts` + `release: VERCEL_GIT_COMMIT_SHA`. - **`start.ts`** — `sentryGlobalRequestMiddleware` + `sentryGlobalFunctionMiddleware` at the front of the existing `createStart(...)` middleware. **This is the win**: it captures request- and server-function errors *including the ones swallowed into 500s* — the exact class the manual wrapper (and the Next server SDK) miss. - **`api/server.js` / `scripts/serve.js`** — gated (`STUDIO_FRAMEWORK==='tanstack'`) instrument init + `wrapFetchWithSentry` on the handler. - **`vite.config.ts`** — `sentryTanstackStart({ …, autoInstrumentMiddleware: false })` as the last plugin: source-map upload + release injection (skips gracefully without an auth token). Middleware is wired explicitly rather than via the plugin's string-rewrite. ### Guarantees - **Client untouched** — the `@sentry/nextjs`→`@sentry/react` alias and #47666's client init are unchanged. - **Next untouched** — `instrumentation.ts` / `sentry.server.config.ts` etc. stay as-is; all new code is TanStack-gated. - **No server SDK in the client bundle** — verified after build: no `@sentry/node` / server middleware / `wrapFetchWithSentry` in `dist/client/assets` (`start.ts`'s server import is tree-shaken out). ### Verified TanStack build exit 0 (past `assertNoChunkCycles`), post-build server boot served `/api/get-utc-time → 200`, `tsc --noEmit` clean, prettier/eslint clean. Node smoke: no-DSN init is a clean no-op; wrapped handler returns 200. ### To test (deploy with a server DSN) Throw a server error from an `/api/*` route (or a `/_serverFn/*`) — including one that gets turned into a 500 without rethrowing — and confirm a server event in Sentry with `release` = the deploy SHA. Compared to #47721, the swallowed-500 case should now be captured via the middleware. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added Sentry integration for the Studio app’s TanStack Start runtime, including request and server-function instrumentation. * Wrapped server request handling to capture errors reliably, with tracing enabled. * Updated build tooling to conditionally upload source maps when credentials are present. * **Bug Fixes** * Improved resilience by safely falling back to a no-op Sentry setup if instrumentation cannot be loaded. * Ensured existing request protection remains enabled while adding observability middleware. * **Chores / Config** * Added `SKIP_ASSET_UPLOAD` to the build environment list to control cache/build behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Joshen Lim <[email protected]>
Stacked on #47657 (base is
alaister/tanstack-migration-fixes; retarget tomasteronce that merges).The TanStack runtime never ran
Sentry.init—instrumentation-client.tsis a Next-convention file nothing imports under TanStack Start, so everySentry.captureExceptionon that build (including theroutes/__root.tsxerror-boundary /routerErrorComponentreports) was a silent no-op.instrumentation-client.tsintolib/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.sentry.tanstack.tsinitializes@sentry/reactfromgetRouter()(TanStack Start's real client bootstrap — the earliest point with the router instance), wiringtanstackRouterBrowserTracingIntegration(router). Window-guarded + idempotent;router.tsxis TanStack-only so the Next build is untouched. (Named without.client.— Start's import-protection fails the build for*.client.*in the server graph.)applicationKeymetadata (onlywithSentryConfigprovides it), the SDK tags every eventthird_party_code: trueandbeforeSendwould drop them all — recreating the silent no-op with a DSN set. Follow-up: add@sentry/vite-pluginmoduleMetadata, then enable.vite.config.tsinlinesundefinedfor unsetNEXT_PUBLIC_SENTRY_DSN/NEXT_PUBLIC_SENTRY_ENVIRONMENT(a literalprocess.env.*in the bundle is the exactprocess is not definedclass fix(studio): TanStack post-merge fixes — Monaco loader, fonts, CSP (from #46424) #47657 fixed). No-DSN → disabled client, plus the existingIS_PLATFORM/consent gates.instrumentation-client.test.tsmoved tolib/sentry-client-options.test.tswith all 36 assertions kept, plus integration-gating and Next/TanStack parity tests.tscclean; fullvite build --mode testpasses.Follow-up (separate): server-side Sentry for the Start handler (
server.tsentry +@sentry/node-style init).To test
ReferenceError: process is not defined(the define fallback). Forcing an error must not POST to any/envelopeendpoint.o…ingest.sentry.io/api/…/envelope/fires, and the event lands in Sentry with acodeSampleRatetag and nothird_party_codetag. Navigation spans named after TanStack routes appear when the 2% pageload trace samples in.instrumentation-client.tsnow builds its options from the same shared source).Review feedback: Sentry
/envelopenever fires on TanStack (Joshen)Root-caused:
@sentry/core'sClient.sendSessionsilently drops the session when the client has norelease. The Next build gets a release injected bywithSentryConfig(the Vercel commit SHA); the Vite build runs no Sentry bundler plugin, so it had no release → session envelopes were discarded before transport → zero/envelopetraffic (errors/transactions are separate). Fix: injectrelease: NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHAon the TanStack build (vite.config re-exposesVERCEL_GIT_COMMIT_SHAunder theNEXT_PUBLIC_name, same SHA the Next release resolves to). Also switchedintegrationsto 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.Summary by CodeRabbit
New Features
Bug Fixes