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

Addresses FE-3107.

**Removed:**

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

**Changed:**

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

**Added:**

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

## To test

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

---------

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

490 lines
18 KiB
TypeScript

import { createRootRoute, createRoute } from '@tanstack/react-router'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { platformComponents as components } from 'api-types'
import { HttpResponse } from 'msw'
import type { UrlUpdateEvent } from 'nuqs/adapters/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Usage } from './Usage'
import type { Branch } from '@/data/branches/branches-query'
import { createMockOrganizationResponse, createMockProject } from '@/tests/helpers'
import { createTestBranch } from '@/tests/lib/branch-test-utils'
import { createTestRouter, customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { mockPermissions } from '@/tests/lib/msw-permissions'
import { ALL_FGA_PERMISSIONS, allPermissionsFor } from '@/tests/lib/permissions-fixtures'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
vi.mock('common', async (importOriginal) => ({
...(await importOriginal<typeof import('common')>()),
useIsLoggedIn: () => true,
}))
vi.mock('@/lib/constants', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/constants')>()),
IS_PLATFORM: true,
}))
const parent = createMockProject({ ref: 'parent-ref', name: 'Parent project' })
const branch = createTestBranch({ name: 'Preview branch' })
const main = createTestBranch({ id: 'main-id', project_ref: parent.ref, is_default: true })
const parentDetail: components['schemas']['ProjectDetailResponse_Output'] = {
...parent,
connectionString: null,
db_host: 'db.parent-ref.supabase.co',
high_availability: false,
integration_source: null,
inserted_at: '2026-01-01T00:00:00Z',
is_physical_backups_enabled: false,
restUrl: 'https://parent-ref.supabase.co',
status: 'ACTIVE_HEALTHY',
subscription_id: 'subscription-1',
updated_at: '2026-01-01T00:00:00Z',
}
const branchDetail = {
...parentDetail,
ref: branch.project_ref,
name: branch.name,
parent_project_ref: parent.ref,
}
function renderUsage(branchRef: string | null = branch.project_ref, projectRef = parent.ref) {
const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>()
const searchParams: Record<string, string> = { projectRef }
if (branchRef !== null) searchParams.branchRef = branchRef
const rootRoute = createRootRoute()
const usageRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/org/$slug/usage',
})
const query = new URLSearchParams(searchParams).toString()
const router = createTestRouter(
`/org/test-org/usage${query ? `?${query}` : ''}`,
rootRoute.addChildren([usageRoute])
)
customRender(<Usage />, {
router,
profileContext: createMockProfileContext(),
nuqs: { searchParams, hasMemory: true, onUrlUpdate },
})
return { onUrlUpdate }
}
function captureUsageRequests() {
const requests: { usage: (string | null)[]; daily: (string | null)[] } = {
usage: [],
daily: [],
}
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/usage',
response: ({ request }) => {
const ref = new URL(request.url).searchParams.get('project_ref')
requests.usage.push(ref)
let usage = 23
if (ref === branch.project_ref) usage = 7
if (ref === parent.ref) usage = 13
return HttpResponse.json<components['schemas']['OrgUsageResponse_Output']>({
usages: [
{
metric: 'EGRESS',
usage,
usage_original: usage * 1e9,
available_in_plan: true,
capped: true,
cost: 0,
pricing_free_units: 5,
pricing_strategy: 'UNIT',
project_allocations: [],
unit_price_desc: 'Egress per GB',
unlimited: false,
},
],
usage_billing_enabled: false,
})
},
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/usage/daily',
response: ({ request }) => {
requests.daily.push(new URL(request.url).searchParams.get('project_ref'))
return HttpResponse.json<components['schemas']['OrgDailyUsageResponse_Output']>({
usages: [],
})
},
})
return requests
}
function expectUsageRefs(
requests: ReturnType<typeof captureUsageRequests>,
refs: (string | null)[]
) {
expect(new Set(requests.usage)).toEqual(new Set(refs))
expect(new Set(requests.daily)).toEqual(new Set(refs))
}
describe('Usage branch URLs', () => {
beforeEach(() => {
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
params.ref === branch.project_ref ? branchDetail : parentDetail
),
})
addAPIMock({
method: 'get',
path: '/platform/organizations',
response: () =>
HttpResponse.json<components['schemas']['OrganizationResponse_Output'][]>([
createMockOrganizationResponse({ slug: 'test-org' }),
]),
})
mockPermissions(allPermissionsFor(['test-org']))
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/billing/subscription',
response: () =>
HttpResponse.json<components['schemas']['GetSubscriptionResponse']>({
addons: [],
billing_via_partner: false,
current_period_start: 1767225600,
current_period_end: 1769904000,
next_invoice_at: 1769904000,
payment_method_type: 'card',
plan: { id: 'free', name: 'Free' },
project_addons: [],
usage_billing_enabled: false,
}),
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () => HttpResponse.json<Branch[]>([main, branch]),
})
})
it('shows the permission notice when subscription access is denied', async () => {
captureUsageRequests()
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: () =>
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
projects: [],
pagination: { count: 0, limit: 96, offset: 0 },
}),
})
mockPermissions({
organizations: [{ slug: 'test-org', role: 'readonly', permissions: [], projects: [] }],
})
const subscriptionRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/billing/subscription',
response: () => {
subscriptionRequested()
return HttpResponse.json<APIErrorBody>({ message: 'Forbidden' }, { status: 403 })
},
})
renderUsage()
expect(
await screen.findByText(/additional permissions to view organization usage/)
).toBeVisible()
expect(screen.queryByRole('button', { name: 'Current billing cycle' })).not.toBeInTheDocument()
expect(subscriptionRequested).not.toHaveBeenCalled()
})
it('requests both usage endpoints with the branch project ref from the URL', async () => {
const requests = captureUsageRequests()
renderUsage()
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
})
it('resolves a direct branch URL and switches to main and organization totals', async () => {
const user = userEvent.setup()
const requests = captureUsageRequests()
const branchListRefs: string[] = []
const projectRefs: string[] = []
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) => {
projectRefs.push(String(params.ref))
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
params.ref === branch.project_ref ? branchDetail : parentDetail
)
},
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: ({ params }) => {
branchListRefs.push(String(params.ref))
return HttpResponse.json<Branch[]>([main, branch])
},
})
const { onUrlUpdate } = renderUsage(null, branch.project_ref)
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(await screen.findByText('7 GB')).toBeVisible()
expect(new Set(projectRefs)).toEqual(new Set([branch.project_ref, parent.ref]))
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(branch.name)
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent(parent.name)
await user.click(screen.getByLabelText('Filter by branch'))
await user.click(await screen.findByRole('option', { name: main.name }))
expect(await screen.findByText(/Main branch only/)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref, parent.ref])
})
expect(await screen.findByText('13 GB')).toBeVisible()
expect(screen.getByLabelText('Filter by branch')).toHaveTextContent(main.name)
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
await user.click(screen.getByLabelText('Filter by branch'))
await user.click(await screen.findByRole('option', { name: branch.name }))
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'View organization total' }))
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref, parent.ref, null])
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
expect(searchParams).toBeDefined()
expect(searchParams?.has('projectRef')).toBe(false)
expect(searchParams?.has('branchRef')).toBe(false)
})
expect(await screen.findByText('23 / 5 GB')).toBeVisible()
expect(screen.queryByLabelText('Filter by branch')).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'View organization total' })
).not.toBeInTheDocument()
})
it('waits for direct branch project details before requesting branches or usage', async () => {
const requests = captureUsageRequests()
const response = Promise.withResolvers<void>()
const projectRequested = vi.fn()
const branchListRefs: string[] = []
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: async ({ params }) => {
if (params.ref === branch.project_ref) {
projectRequested()
await response.promise
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
branchDetail
)
}
return HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(
parentDetail
)
},
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: ({ params }) => {
branchListRefs.push(String(params.ref))
return HttpResponse.json<Branch[]>([main, branch])
},
})
renderUsage(null, branch.project_ref)
try {
await waitFor(() => expect(projectRequested).toHaveBeenCalled())
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(branchListRefs).toEqual([])
expect(requests).toEqual({ usage: [], daily: [] })
} finally {
await act(async () => response.resolve())
}
expect(await screen.findByText(`${branch.name} branch only.`)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
expect(new Set(branchListRefs)).toEqual(new Set([parent.ref]))
})
it('blocks a direct branch link when its parent project lookup fails', async () => {
const requests = captureUsageRequests()
const branchRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
params.ref === branch.project_ref
? HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail)
: HttpResponse.json<APIErrorBody>({ message: 'Parent lookup failed' }, { status: 500 }),
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () => {
branchRequested()
return HttpResponse.json<Branch[]>([main, branch])
},
})
renderUsage(null, branch.project_ref)
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(branchRequested).not.toHaveBeenCalled()
expect(requests).toEqual({ usage: [], daily: [] })
})
it('does not request parent usage while the branch list is pending', async () => {
const requests = captureUsageRequests()
const response = Promise.withResolvers<Branch[]>()
const branchRequested = vi.fn()
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: async () => {
branchRequested()
return HttpResponse.json<Branch[]>(await response.promise)
},
})
renderUsage()
try {
await waitFor(() => expect(branchRequested).toHaveBeenCalled())
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
expect(screen.getByRole('status', { name: 'Loading branch usage' })).toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
} finally {
await act(async () => response.resolve([main, branch]))
}
await waitFor(() => {
expectUsageRefs(requests, [branch.project_ref])
})
})
it('shows a branch error without requesting parent usage when the branch list fails', async () => {
const requests = captureUsageRequests()
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/branches',
response: () =>
HttpResponse.json<APIErrorBody>({ message: 'Branch lookup failed' }, { status: 500 }),
})
renderUsage()
expect(await screen.findByText('Failed to retrieve branches')).toBeInTheDocument()
expect(await screen.findByText('Free Plan')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Branch unavailable')).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
})
it('blocks branch usage without falling back to the parent when branch access is denied', async () => {
const requests = captureUsageRequests()
mockPermissions({
organizations: [
{
slug: 'test-org',
role: 'owner',
permissions: ALL_FGA_PERMISSIONS.filter(
(permission) => !permission.startsWith('branching_')
),
projects: [],
},
],
})
renderUsage()
expect(
await screen.findByText(/additional permissions to view this branch's usage/)
).toBeVisible()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
})
it('shows Branch unavailable and requests parent usage for a deleted branch ref', async () => {
const requests = captureUsageRequests()
renderUsage('deleted-branch-ref')
expect(await screen.findByText('Branch unavailable')).toBeInTheDocument()
expect(screen.getByText(/Main branch only/)).toBeInTheDocument()
await waitFor(() => {
expectUsageRefs(requests, [parent.ref])
})
})
it('keeps filters usable after a project lookup failure and recovers through All projects', async () => {
const user = userEvent.setup()
const requests = captureUsageRequests()
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: ({ params }) =>
params.ref === parent.ref
? HttpResponse.json<APIErrorBody>({ message: 'Project lookup failed' }, { status: 404 })
: HttpResponse.json<components['schemas']['ProjectDetailResponse_Output']>(branchDetail),
})
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/projects',
response: () =>
HttpResponse.json<components['schemas']['OrganizationProjectsResponse_Output']>({
projects: [],
pagination: { count: 0, limit: 96, offset: 0 },
}),
})
const { onUrlUpdate } = renderUsage()
expect(await screen.findByText('Failed to retrieve project')).toBeInTheDocument()
expect(screen.queryByRole('status', { name: 'Loading branch usage' })).not.toBeInTheDocument()
expect(screen.queryByText('Usage Summary')).not.toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
await user.click(await screen.findByRole('button', { name: 'Current billing cycle' }))
expect(
await screen.findByRole('menuitemradio', { name: 'Current billing cycle' })
).toBeInTheDocument()
await user.keyboard('{Escape}')
const projectPicker = screen.getByRole('combobox', { name: '' })
expect(projectPicker).toHaveTextContent(parent.ref)
await user.click(projectPicker)
const allProjects = await screen.findByRole('option', { name: 'All projects' })
expect(screen.getByText('Failed to retrieve project')).toBeInTheDocument()
expect(requests).toEqual({ usage: [], daily: [] })
await user.click(allProjects)
await waitFor(() => {
expectUsageRefs(requests, [null])
const searchParams = onUrlUpdate.mock.lastCall?.[0].searchParams
expect(searchParams).toBeDefined()
expect(searchParams?.has('projectRef')).toBe(false)
expect(searchParams?.has('branchRef')).toBe(false)
})
expect(screen.queryByText('Failed to retrieve project')).not.toBeInTheDocument()
expect(screen.getByText('Usage Summary')).toBeInTheDocument()
expect(screen.getByRole('combobox', { name: '' })).toHaveTextContent('All projects')
})
})