Files
Alaister YoungandAlaister Young 477e2c136f [FE-5109] (part 6) chore(studio): remove next/router shims, aliases, and test mocks (#54058)
Part 6 (final) of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| **6** | **#54058 ← this PR** | **Remove `next/router` &
`next/compat/router` shims, `_router-events.ts`, Vite aliases, and test
mocks** |

Now that no files in `apps/studio` (or `packages/**`) import
`next/router` or `next/compat/router`, deletes the router shims,
`_router-events.ts`, their Vite aliases, and the obsolete router test
mocks. `RouteValidationWrapper` is intentionally left for FE-3107.

**Removed:**

- `apps/studio/compat/next/router.ts`,
`apps/studio/compat/next/compat/router.ts`, and
`apps/studio/compat/next/_router-events.ts`
- `'next/router'` and `'next/compat/router'` entries from `nextShims` in
`apps/studio/vite.config.ts`
- Global `vi.mock('next/router', ...)` and
`vi.mock('next/compat/router', ...)` in
`apps/studio/tests/vitestSetup.ts`, `mockNextRouter` in
`apps/studio/tests/lib/route-aware-hooks.ts`, and the unused
`vi.mock('next/router')` in `tests/features/logs/LogTable.test.tsx`
- Obsolete shim tests and test helpers: `compat/next/router.test.ts`,
`compat/next/router-navigation.test.tsx`, `tests/config/router.tsx`, and
`tests/config/router.test.tsx`

**Changed:**

- Simplified `createNavigationHandler` in
`apps/studio/lib/navigation.ts` (and `navigation.test.ts`) to accept
TanStack's `UseNavigateResult<string>` only, dropping the `NextRouter`
union branch
- Updated `compat/next/link-basepath-navigation.test.tsx` (renamed from
`router-basepath-navigation.test.tsx`), `lib/router-url-shape.test.tsx`,
and `tests/lib/route-render.test.tsx` to exercise TanStack Router hooks
directly instead of the removed router shim
- Cleaned up stale `next/router` comments in `compat/next/link.tsx`,
`lib/internal-url.ts`, `router.tsx`, and `tests/lib/route-mock.ts`

**Simplified:**

- Removed `routerMock` setup from about 19 tests that no longer read it.
`next-router-mock` stays for now, because the test `FrameworkProvider`
still feeds `useParams` from it.
- `AGENTS.md` and the `vite.config.ts` error text now say only
`next/link` and `next/script` are shimmed
- Renamed `compat/next/router-basepath-navigation.test.tsx` to
`link-basepath-navigation.test.tsx`, and removed stale router-shim
references from comments

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] Confirm `git grep -E "next/(compat/)?router|_router-events"
apps/studio` returns no code or config imports (only the prose guideline
in `apps/studio/AGENTS.md`)
- [ ] Confirm `pnpm --filter studio run typecheck`, `pnpm --filter
studio run lint`, `pnpm --filter studio run build`, Knip, and the full
Studio Vitest suite pass
- [ ] Spot-check basePath navigation (`next/link` + `navigateToUrl`) and
multi-line query param URLs in Studio

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 15:04:27 +08:00

261 lines
9.7 KiB
TypeScript

import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import z from 'zod'
import { RoleRow } from './RoleRow'
import { ProjectContextProvider } from '@/components/layouts/ProjectLayout/ProjectContext'
import type { PgRole } from '@/data/database-roles/database-roles-query'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
mockAnimationsApi()
const QueryBodySchema = z.object({ query: z.string() })
const createRole = (overrides: Partial<PgRole> = {}): PgRole => ({
id: 16500,
name: 'app_user',
isSuperuser: false,
canCreateDb: false,
canCreateRole: false,
inheritRole: true,
canLogin: false,
isReplicationRole: false,
canBypassRls: false,
activeConnections: 0,
connectionLimit: -1,
validUntil: null,
config: {},
comment: null,
...overrides,
})
describe('RoleRow', () => {
let queries: string[]
beforeEach(() => {
queries = []
// useSelectedProjectQuery
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
// @ts-expect-error partial project is enough for the connection string lookup
response: {
cloud_provider: 'localhost',
id: 1,
inserted_at: '2021-08-02T06:40:40.646Z',
name: 'Default Project',
organization_id: 1,
ref: 'default',
region: 'local',
status: 'ACTIVE_HEALTHY',
},
})
// useDatabaseRoleUpdateMutation executes SQL, and the invalidated roles query lists roles
addAPIMock({
method: 'post',
path: '/platform/pg-meta/:ref/query',
response: async ({ request }) => {
const body = QueryBodySchema.parse(await request.json())
queries.push(body.query)
return HttpResponse.json<Record<string, unknown>[]>([])
},
})
})
const renderExpandedRow = async (role: PgRole) => {
customRender(
<ProjectContextProvider projectRef="default">
<RoleRow role={role} onSelectDelete={vi.fn()} />
</ProjectContextProvider>
)
const user = userEvent.setup()
await user.click(await screen.findByText(role.name))
return user
}
const getLoginSwitch = () => screen.getByLabelText('User can login')
const submit = (role: PgRole) =>
fireEvent.submit(document.getElementById(`role-update-form-${role.id}`)!)
const getUpdateQuery = () => queries.find((query) => query.includes('alter role'))
test('does not offer a password for a role that can already log in', async () => {
await renderExpandedRow(createRole({ canLogin: true }))
expect(getLoginSwitch()).toBeChecked()
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument()
})
test('shows the password field only while login is turned on for a role that cannot log in', async () => {
const user = await renderExpandedRow(createRole())
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument()
await user.click(getLoginSwitch())
expect(await screen.findByLabelText('Password')).toBeInTheDocument()
// The role may already have a password, so the text must not claim it has none
expect(screen.getByText(/setting a password replaces any existing one/i)).toBeInTheDocument()
await user.click(getLoginSwitch())
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument()
})
test('sets the password when login is turned on', async () => {
const role = createRole()
const user = await renderExpandedRow(role)
await user.click(getLoginSwitch())
await user.click(await screen.findByLabelText('Password'))
await user.paste('s3cret')
submit(role)
await waitFor(() => expect(getUpdateQuery()).toBeDefined())
expect(getUpdateQuery()).toMatch(/\blogin\b/)
expect(getUpdateQuery()).toContain(`'SCRAM-SHA-256$`)
expect(getUpdateQuery()).not.toContain('s3cret')
})
test('turns on login without a password when the field is empty', async () => {
const role = createRole()
const user = await renderExpandedRow(role)
await user.click(getLoginSwitch())
submit(role)
await waitFor(() => expect(getUpdateQuery()).toBeDefined())
expect(getUpdateQuery()).toMatch(/\blogin\b/)
expect(getUpdateQuery()).not.toContain('password')
})
test('does not send a password with other changes to a role that can already log in', async () => {
const role = createRole({ canLogin: true })
const user = await renderExpandedRow(role)
await user.click(screen.getByLabelText('User can create databases'))
submit(role)
await waitFor(() => expect(getUpdateQuery()).toBeDefined())
expect(getUpdateQuery()).toContain('createdb')
expect(getUpdateQuery()).not.toContain('password')
})
describe('reset password', () => {
const openMenu = async (role: PgRole) => {
customRender(
<ProjectContextProvider projectRef="default">
<RoleRow role={role} onSelectDelete={vi.fn()} />
</ProjectContextProvider>
)
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: `${role.name} actions` }))
return user
}
test('is available for a custom role that can log in', async () => {
await openMenu(createRole({ canLogin: true }))
expect(await screen.findByRole('menuitem', { name: 'Reset password' })).not.toHaveAttribute(
'data-disabled'
)
})
test.each([
['a system role', createRole({ name: 'postgres', canLogin: true })],
['a role that cannot log in', createRole({ canLogin: false })],
])('is disabled for %s', async (_, role) => {
await openMenu(role)
expect(await screen.findByRole('menuitem', { name: 'Reset password' })).toHaveAttribute(
'data-disabled'
)
})
test('requires a password', async () => {
const user = await openMenu(createRole({ canLogin: true }))
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
fireEvent.submit(document.getElementById('reset-role-password-form')!)
expect(await screen.findByText('You must provide a password')).toBeInTheDocument()
expect(getUpdateQuery()).toBeUndefined()
})
test('sets the new password and closes the dialog', async () => {
const user = await openMenu(createRole({ canLogin: true }))
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
await user.click(await screen.findByLabelText('Password'))
await user.paste('n3w-s3cret')
fireEvent.submit(document.getElementById('reset-role-password-form')!)
await waitFor(() => expect(getUpdateQuery()).toBeDefined())
expect(getUpdateQuery()).toContain(`'SCRAM-SHA-256$`)
expect(getUpdateQuery()).not.toContain('n3w-s3cret')
await waitFor(() => expect(screen.queryByLabelText('Password')).not.toBeInTheDocument())
})
test('closes on cancel without asking when nothing was entered', async () => {
const user = await openMenu(createRole({ canLogin: true }))
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByLabelText('Password')).not.toBeInTheDocument())
expect(screen.queryByText('Unsaved changes')).not.toBeInTheDocument()
})
test('asks before discarding an entered password, and starts empty when reopened', async () => {
const role = createRole({ canLogin: true })
const user = await openMenu(role)
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
await user.click(await screen.findByLabelText('Password'))
await user.paste('n3w-s3cret')
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
expect(await screen.findByText('Unsaved changes')).toBeInTheDocument()
expect(screen.getByLabelText('Password')).toHaveValue('n3w-s3cret')
await user.click(await screen.findByRole('button', { name: 'Discard changes' }))
await waitFor(() => expect(screen.queryByLabelText('Password')).not.toBeInTheDocument())
await user.click(await screen.findByRole('button', { name: `${role.name} actions` }))
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
expect(await screen.findByLabelText('Password')).toHaveValue('')
expect(getUpdateQuery()).toBeUndefined()
})
test('ignores dismissal while the password is being saved', async () => {
let finishUpdate = () => {}
const updateFinished = new Promise<void>((resolve) => (finishUpdate = resolve))
addAPIMock({
method: 'post',
path: '/platform/pg-meta/:ref/query',
response: async ({ request }) => {
queries.push(QueryBodySchema.parse(await request.json()).query)
await updateFinished
return HttpResponse.json<Record<string, unknown>[]>([])
},
})
const user = await openMenu(createRole({ canLogin: true }))
await user.click(await screen.findByRole('menuitem', { name: 'Reset password' }))
await user.click(await screen.findByLabelText('Password'))
await user.paste('n3w-s3cret')
fireEvent.submit(document.getElementById('reset-role-password-form')!)
await waitFor(() => expect(getUpdateQuery()).toBeDefined())
await user.keyboard('{Escape}')
expect(screen.queryByText('Unsaved changes')).not.toBeInTheDocument()
expect(screen.getByLabelText('Password')).toBeInTheDocument()
finishUpdate()
await waitFor(() => expect(screen.queryByLabelText('Password')).not.toBeInTheDocument())
})
})
})