feat(supabase): @faunosteo/supabase package with PGlite harness and typed client

- tests/db: PGlite (PostgreSQL 17 WASM) applies the Supabase shim + migrations and
  runs supabase/tests/*.sql through pgTAP without Docker
- schema-types test pins tables, columns, enums, RPC args, RLS-on, no using(true)
- database.types.ts in supabase gen types format; createBrowserClient (PKCE)
- Supabase CLI pinned as root devDependency; db:* root scripts
This commit is contained in:
bchanot committed 2026-10-08 22:20:54 +02:00
1 parent 2d5ff0c33e
commit ce76c6597a
15 files changed
+1020 -2

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
/**
* PGlite harness: a real PostgreSQL (WASM) that applies the Supabase shim,
* then every migration under supabase/migrations, in filename order.
* Lets the pgTAP suite and the schema checks run without Docker. The same
* SQL runs unchanged under `supabase test db` on the real stack.
*/
import { readdir, readFile } from 'node:fs/promises'
import { resolve, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PGlite } from '@electric-sql/pglite'
import { pgtap } from '@electric-sql/pglite/pgtap'
const here = fileURLToPath(new URL('.', import.meta.url))
export const repoRoot = resolve(here, '../../../..')
export const supabaseDir = join(repoRoot, 'supabase')
export const migrationsDir = join(supabaseDir, 'migrations')
export const pgTapTestsDir = join(supabaseDir, 'tests')
async function listSqlFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir)
return entries.filter((f) => f.endsWith('.sql')).sort()
}
export async function listMigrations(): Promise<string[]> {
return listSqlFiles(migrationsDir)
}
export async function listPgTapTests(): Promise<string[]> {
return listSqlFiles(pgTapTestsDir)
}
/** Boots PGlite, installs the shim and applies all migrations. */
export async function createMigratedDatabase(): Promise<PGlite> {
const db = await PGlite.create({ extensions: { pgtap } })
await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8'))
// Same placement as `supabase test db`: pgTAP lives in extensions, out of public.
await db.exec('create extension if not exists pgtap with schema extensions;')
await db.exec('set search_path to public, extensions;')
for (const file of await listMigrations()) {
await db.exec(await readFile(join(migrationsDir, file), 'utf8'))
}
return db
}
export interface TapReport {
lines: string[]
failures: string[]
}
function collectTapLines(results: Array<{ rows: unknown[] }>): string[] {
const lines: string[] = []
for (const result of results) {
for (const row of result.rows) {
const values = Object.values(row as Record<string, unknown>)
for (const value of values) {
if (typeof value === 'string') lines.push(...value.split('\n'))
}
}
}
return lines
}
/**
* Runs one pgTAP file (which must wrap itself in begin/rollback) and reports
* every `not ok` line plus plan mismatches announced by finish().
*/
export async function runPgTapFile(db: PGlite, file: string): Promise<TapReport> {
const sql = await readFile(join(pgTapTestsDir, file), 'utf8')
let lines: string[]
try {
lines = collectTapLines(await db.exec(sql))
} finally {
// A failing statement leaves the transaction aborted: always clean up.
await db.exec('rollback;').catch(() => undefined)
}
const failures = lines.filter(
(line) => /^not ok\b/.test(line) || /^# Looks like/.test(line),
)
return { lines, failures }
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Runs every pgTAP file under supabase/tests against a migrated PGlite
* database. One vitest case per SQL file: the failing TAP lines are the
* assertion message, so a red test names the exact pgTAP check.
*/
import type { PGlite } from '@electric-sql/pglite'
import {
createMigratedDatabase,
listPgTapTests,
runPgTapFile,
} from './harness'
const files = await listPgTapTests()
describe('pgTAP suite (supabase/tests) on PGlite', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('finds at least one pgTAP file', () => {
expect(files.length).toBeGreaterThan(0)
})
it.each(files)('%s passes', async (file) => {
const report = await runPgTapFile(db, file)
const okCount = report.lines.filter((l) => /^ok\b/.test(l)).length
expect(report.failures, report.lines.join('\n')).toEqual([])
expect(okCount).toBeGreaterThan(0)
})
})
@@ -0,0 +1,157 @@
/**
* database.types.ts must describe the migrated schema: same tables, same
* columns, same enum labels, same RPC names and arguments. The column map
* below is checked twice: by the compiler (every listed name exists in the
* type, and the type has no column missing from the list) and at runtime
* against information_schema in PGlite.
*
* Also pins two invariants for every future table in public: RLS enabled, and
* no `using (true)` policy for authenticated.
*/
import type { PGlite } from '@electric-sql/pglite'
import { Constants, type Database } from '../../src/database.types'
import { createMigratedDatabase } from './harness'
type Tables = Database['public']['Tables']
type Functions = Database['public']['Functions']
type ColumnMap = { readonly [T in keyof Tables]: readonly (keyof Tables[T]['Row'] & string)[] }
const expectedColumns = {
profile_roles: [
'granted_at',
'granted_by',
'id',
'revoke_reason',
'revoked_at',
'revoked_by',
'role',
'user_id',
],
profiles: [
'active',
'created_at',
'display_name',
'first_name',
'id',
'last_name',
'locale',
'phone',
'phone_verified_at',
'timezone',
'updated_at',
],
} as const satisfies ColumnMap
// Compile-time: a column present in the type but absent from the list is an error.
type MissingColumns = {
[T in keyof Tables]: Exclude<keyof Tables[T]['Row'], (typeof expectedColumns)[T][number]>
}[keyof Tables]
const noMissingColumn: MissingColumns extends never ? true : never = true
type FunctionArgs = { readonly [F in keyof Functions]: readonly (keyof Functions[F]['Args'] & string)[] }
const expectedFunctionArgs = {
grant_platform_role: ['role', 'target_user_id'],
revoke_platform_role: ['reason', 'role', 'target_user_id'],
} as const satisfies FunctionArgs
type MissingArgs = {
[F in keyof Functions]: Exclude<keyof Functions[F]['Args'], (typeof expectedFunctionArgs)[F][number]>
}[keyof Functions]
const noMissingArg: MissingArgs extends never ? true : never = true
interface ColumnRow {
table_name: string
column_name: string
}
interface NameRow {
name: string
}
interface FunctionRow {
name: string
args: string[]
}
interface PolicyRow {
tablename: string
policyname: string
}
describe('database.types.ts matches the migrated schema', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('has the compile-time exhaustiveness witnesses', () => {
expect(noMissingColumn).toBe(true)
expect(noMissingArg).toBe(true)
})
it('lists exactly the public tables and their columns', async () => {
const { rows } = await db.query<ColumnRow>(
`select table_name, column_name
from information_schema.columns
where table_schema = 'public'
order by table_name, column_name`,
)
const actual: Record<string, string[]> = {}
for (const row of rows) (actual[row.table_name] ??= []).push(row.column_name)
const expected = Object.fromEntries(
Object.entries(expectedColumns).map(([table, cols]) => [table, [...cols].sort()]),
)
expect(actual).toEqual(expected)
})
it('lists the enum labels in order', async () => {
const { rows } = await db.query<NameRow>(
`select e.enumlabel as name
from pg_enum e join pg_type t on t.oid = e.enumtypid
join pg_namespace n on n.oid = t.typnamespace
where n.nspname = 'public' and t.typname = 'platform_role'
order by e.enumsortorder`,
)
expect(rows.map((r) => r.name)).toEqual([...Constants.public.Enums.platform_role])
})
it('lists exactly the public functions and their argument names', async () => {
const { rows } = await db.query<FunctionRow>(
`select p.proname as name, coalesce(p.proargnames, '{}') as args
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'public' and p.prokind = 'f'
and not exists (
select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e'
)
order by p.proname`,
)
const actual = Object.fromEntries(rows.map((r) => [r.name, [...r.args].sort()]))
const expected = Object.fromEntries(
Object.entries(expectedFunctionArgs).map(([fn, args]) => [fn, [...args].sort()]),
)
expect(actual).toEqual(expected)
})
it('keeps RLS enabled on every public table', async () => {
const { rows } = await db.query<NameRow>(
`select c.relname as name
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity`,
)
expect(rows).toEqual([])
})
it('has no unconditional policy for API roles', async () => {
const { rows } = await db.query<PolicyRow>(
`select tablename, policyname
from pg_policies
where schemaname = 'public'
and (qual = 'true' or with_check = 'true')
and roles && array['authenticated', 'anon']::name[]`,
)
expect(rows).toEqual([])
})
})
@@ -0,0 +1,75 @@
-- Minimal stand-in for the Supabase base schema, applied to a bare PGlite
-- database before the project migrations. Mirrors what the hosted/local stack
-- provides: API roles, auth schema with users table + JWT claim helpers, and
-- the permissive default privileges on public (ALL to the API roles), so a
-- migration that forgets to revoke is caught by the tests.
-- Test-only file: never applied to a real Supabase database.
create role anon nologin noinherit;
create role authenticated nologin noinherit;
create role service_role nologin noinherit bypassrls;
create schema auth;
create schema extensions;
create table auth.users (
instance_id uuid,
id uuid primary key default gen_random_uuid(),
aud varchar(255),
role varchar(255),
email varchar(255),
encrypted_password varchar(255),
email_confirmed_at timestamptz,
raw_app_meta_data jsonb,
raw_user_meta_data jsonb,
created_at timestamptz default now(),
updated_at timestamptz default now()
);
create or replace function auth.uid()
returns uuid
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.sub', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
),
''
)::uuid
$$;
create or replace function auth.role()
returns text
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.role', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role')
),
''
)::text
$$;
create or replace function auth.jwt()
returns jsonb
language sql
stable
as $$
select coalesce(
nullif(current_setting('request.jwt.claim', true), ''),
nullif(current_setting('request.jwt.claims', true), '')
)::jsonb
$$;
grant usage on schema auth to anon, authenticated, service_role;
grant execute on function auth.uid(), auth.role(), auth.jwt() to anon, authenticated, service_role;
grant usage on schema public to anon, authenticated, service_role;
grant usage on schema extensions to anon, authenticated, service_role;
alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;