From ea5d6af6ba87a2dae51c4b78fc0b9df526fc3891 Mon Sep 17 00:00:00 2001 From: Miranda Limonczenko Date: Wed, 25 Nov 2026 11:35:58 -0800 Subject: [PATCH] feat(docs): add a generating types guide eval --- .../build-docs-036-generating-types/EVAL.ts | 113 ++++++ .../build-docs-036-generating-types/PROMPT.md | 31 ++ .../build-docs-036-generating-types/README.md | 81 ++++ .../build-docs-036-generating-types/files.ts | 48 +++ .../local/CONTRIBUTING.md | 6 + .../local/package.json | 14 + .../local/src/catalog.ts | 37 ++ .../local/src/lib/supabase.ts | 8 + .../local/src/orders.ts | 16 + .../local/supabase/config.toml | 19 + .../migrations/20250301000000_bookshop.sql | 51 +++ .../local/tsconfig.json | 12 + .../refresh.ts | 98 +++++ .../typecheck.ts | 358 ++++++++++++++++++ 14 files changed, 892 insertions(+) create mode 100644 evals/docs/build-docs-036-generating-types/EVAL.ts create mode 100644 evals/docs/build-docs-036-generating-types/PROMPT.md create mode 100644 evals/docs/build-docs-036-generating-types/README.md create mode 100644 evals/docs/build-docs-036-generating-types/files.ts create mode 100644 evals/docs/build-docs-036-generating-types/local/CONTRIBUTING.md create mode 100644 evals/docs/build-docs-036-generating-types/local/package.json create mode 100644 evals/docs/build-docs-036-generating-types/local/src/catalog.ts create mode 100644 evals/docs/build-docs-036-generating-types/local/src/lib/supabase.ts create mode 100644 evals/docs/build-docs-036-generating-types/local/src/orders.ts create mode 100644 evals/docs/build-docs-036-generating-types/local/supabase/config.toml create mode 100644 evals/docs/build-docs-036-generating-types/local/supabase/migrations/20250301000000_bookshop.sql create mode 100644 evals/docs/build-docs-036-generating-types/local/tsconfig.json create mode 100644 evals/docs/build-docs-036-generating-types/refresh.ts create mode 100644 evals/docs/build-docs-036-generating-types/typecheck.ts diff --git a/evals/docs/build-docs-036-generating-types/EVAL.ts b/evals/docs/build-docs-036-generating-types/EVAL.ts new file mode 100644 index 000000000..6d475d1de --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/EVAL.ts @@ -0,0 +1,113 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { REFRESH_SCRIPT, type Refresh, refreshAfterChange } from './refresh.js'; +import { type Analysis, analyze, PROBE } from './typecheck.js'; + +const GUIDE_PATH = 'guides/api/rest/generating-types'; +const CONTROL_NOTE = + 'a known-bad control raised no error, so the types could not be judged'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const snapshot = analyze(ctx.hostWorkspace); + const refreshed = await refreshAfterChange(ctx); + + const checks: CheckResult[] = [ + checkAppTypeChecks(snapshot), + checkTypesMatchSchema(snapshot), + checkRefreshFollowsChange(refreshed), + checkGuideWasRead(ctx), + ]; + + return { passed: checks.every((check) => check.passed), checks }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + passed: false, + checks: [ + { + name: 'scorer evaluated the database types', + passed: false, + notes: message, + }, + ], + }; + } +}; + +export default scorer; + +function checkAppTypeChecks(analysis: Analysis): CheckResult { + const name = + 'the app type-checks in strict mode with no suppression comments'; + if (!analysis.ok) return { name, passed: false, notes: analysis.reason }; + const { appDiagnostics, suppressions } = analysis; + const problems = [ + appDiagnostics.length > 0 + ? `${appDiagnostics.length} diagnostics: ${appDiagnostics.slice(0, 5).join('; ')}` + : '', + suppressions.length > 0 + ? `suppression comments at ${suppressions.slice(0, 5).join(', ')}` + : '', + ].filter((problem) => problem.length > 0); + return { + name, + passed: problems.length === 0, + notes: + problems.length === 0 + ? 'no diagnostics with strict mode forced on, and no @ts-ignore, @ts-expect-error or @ts-nocheck' + : problems.join('; '), + }; +} + +function checkTypesMatchSchema(analysis: Analysis): CheckResult { + const name = 'the types match the local tables and function the app uses'; + if (!analysis.ok) return { name, passed: false, notes: analysis.reason }; + if (analysis.failedProbes.length > 0) { + return { + name, + passed: false, + notes: `wrong or missing: ${analysis.failedProbes.join(', ')}`, + }; + } + if (!analysis.controlFired) { + return { name, passed: false, notes: CONTROL_NOTE }; + } + return { name, passed: true, notes: Object.values(PROBE).join(', ') }; +} + +function checkRefreshFollowsChange(refresh: Refresh): CheckResult { + const name = + 'the refresh command picks up a new column in the local database'; + if (!refresh.ran) return { name, passed: false, notes: refresh.reason }; + const { analysis, column } = refresh; + if (!analysis.ok) return { name, passed: false, notes: analysis.reason }; + return { + name, + passed: analysis.booksRowMatches, + notes: analysis.booksRowMatches + ? `npm run ${REFRESH_SCRIPT} added catalog.books.${column} to the types the app is created with` + : `after npm run ${REFRESH_SCRIPT}, the types the app is created with do not describe catalog.books with ${column}`, + }; +} + +function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult { + const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) => + call.pages?.some((page) => page.url.includes(GUIDE_PATH)) + ); + const withContent = calls.filter((call) => call.hasContent); + return { + name: 'the agent read the generating types guide the prompt referenced', + passed: withContent.length > 0, + notes: + withContent.length > 0 + ? withContent.map((call) => call.source).join(', ') + : calls.length > 0 + ? `reached the guide via ${calls.map((call) => call.source).join(', ')} but retrieved no page content` + : 'no docs call reached the guide', + }; +} diff --git a/evals/docs/build-docs-036-generating-types/PROMPT.md b/evals/docs/build-docs-036-generating-types/PROMPT.md new file mode 100644 index 000000000..ca5b71f8c --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/PROMPT.md @@ -0,0 +1,31 @@ +--- +stage: build +interface: cli +product: + - database + - data-api +topic: + - sdk +services: [] +motivation: >- + Typed Supabase apps break when their types miss part of the database. + Customers report a second schema missing from the generated types + (supabase/supabase#54000), a schema silently left out of a types file + (supabase/cli#7625), and database functions typed as never until types are + generated. This checks that an agent reading the Generating Types guide gives + an app types that match the local database, including a second schema and a + function, and a refresh command that picks up a database change. The prompt + omits the guide's vocabulary on purpose, so read README.md before editing it. +--- + +The TypeScript in src/ for our bookshop app talks to the local Supabase +database, but `npm run typecheck` fails and nothing tells us when the code and +the database drift apart. Get the app's types in line with the local database +so the check passes, and make the refresh command in CONTRIBUTING.md work so we +can keep them current after each database change. + +Read the guide below before you start and rely on it for how to set this up, +rather than on what you already know. + +REFERENCE +https://supabase.com/docs/guides/api/rest/generating-types.md diff --git a/evals/docs/build-docs-036-generating-types/README.md b/evals/docs/build-docs-036-generating-types/README.md new file mode 100644 index 000000000..545122df7 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/README.md @@ -0,0 +1,81 @@ +# build-docs-036-generating-types + +## What this eval measures + +The subject is [Generating TypeScript Types](https://supabase.com/docs/guides/api/rest/generating-types), not the agent. +The prompt is a product request plus the page's url, and the checks say whether an agent that read the page gives an app +types that match the local database. + +One claim: the types the app is created with match the live local schema, including a second exposed schema and a +database function, and the team's refresh command regenerates them after the schema changes. + +## How it differs from build-database-006-regenerate-types + +`evals/cli/build-database-006-regenerate-types` measures the agent across CLI versions and Docker setups. It hands over a +migration, and scores regenerating stale types and fixing app code that no longer compiles. This eval measures a docs +page on one CLI. The app code is already correct, the types do not exist yet, part of the schema sits outside `public`, +and the refresh command is run again by the scorer after it changes the database. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +generate, gen types, CLI, `supabase gen`, `--local`, `--schema`, schema, catalog, introspection, `database.types.ts`, +`Database`, `createClient`, type definitions, rpc, function, migration. + +## The seed carries the contract + +- `src/lib/supabase.ts` already calls `createClient` with `Database` from `./database.types`, which does not + exist. The answer has a place to land. The checks find every `createClient<...>` call under `src/` and use its type + argument and that file's imports, so a moved client, a namespace import or types kept under `supabase/` all pass. +- `CONTRIBUTING.md` names `npm run db:types` and says it refreshes the app's types from the local database. + `package.json` has no such script. The refresh check needs a fixed command to run, so the name is given rather than + discovered. The command behind it is the agent's choice. +- The migration puts `books`, the `book_format` enum and the `search_books` function in a `catalog` schema that + `config.toml` exposes, and `orders` in `public`. A types file limited to `public` cannot compile the app. +- `config.toml` is minimal and has no `[inbucket]` section, so a newer CLI can read it too. +- `services: []` starts only the database. On CLI 2.117.0, `gen types --local` runs a one-off `postgres-meta` container + of its own, so it works without that service started. + +## Do not drop the positive controls + +The probe holds two controls: `Equals<1, 2>` and a wrong row shape for `catalog.books`. Both must raise an error. The +second one catches a types module that did not resolve, because TypeScript stays silent about assertions on an +unresolved import. Without it an empty workspace scores green. + +## How the checks read the end state + +- The type checks run host-side on a copy of every `.ts` file outside `node_modules`, `.git` and `supabase/functions`, + with the repo's TypeScript and `@supabase/supabase-js`. The workspace's `node_modules` is linked in for any other + import, such as `type-fest`. The scorer and the read-back of the sandbox share one file filter. +- The whole strict family is removed from the agent's `tsconfig.json` and `strict` is forced on. Any `@ts-ignore`, + `@ts-expect-error` or `@ts-nocheck` in a compiled file outside `node_modules` fails the first check. The seed has none. +- The probe compares, by type identity after flattening intersections, the `Row` of `catalog.books`, the `Args` and + `Returns` of `catalog.search_books`, and the `Row` and `Insert` of `public.orders`. An `any` or `string` column fails. + Output from CLI 2.117.0 and 3.4.0 both pass. +- `the refresh command picks up a new column in the local database` adds a column with a run-scoped name to + `catalog.books`, links the sandbox's pinned CLI to `node_modules/.bin/supabase` when nothing is there, runs + `npm run db:types`, reads the workspace back, and asserts the column is in the `catalog.books` row. The link means + `supabase` and `npx supabase` in the script both run the pinned CLI with no download. It runs last because it changes + the database. Score once per stack. + +## The guide has to actually be read + +`the agent read the generating types guide the prompt referenced` requires a docs call that reached the page with +content. Read `docs.calls` before reading a score. + +## Checks expected to saturate + +`the app type-checks in strict mode with no suppression comments`, because the agent can run `npm run typecheck` and see +the failure. The signal is expected in the probe check, for a types file limited to `public`, and in the refresh check, +for hand-written types, a script that writes somewhere the app does not import, or a script that targets a hosted +project. + +## What this eval does not score + +- **Whether the app code changed.** The seed's code is correct against the schema. The probe does not read it. +- **Generating types from a hosted project.** None is reachable locally. +- **Generating types for other languages.** +- **Overriding generated types.** An override that keeps the shapes above passes. +- **Keeping types current on a schedule.** Only the refresh command is run. +- **A stopped stack.** If the agent stops the database, the refresh check cannot add its column and fails. diff --git a/evals/docs/build-docs-036-generating-types/files.ts b/evals/docs/build-docs-036-generating-types/files.ts new file mode 100644 index 000000000..3eb0efe9a --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/files.ts @@ -0,0 +1,48 @@ +import type { Dirent } from 'node:fs'; + +type ReadDir = (path: string) => Dirent[]; + +export function isSourcePath(path: string): boolean { + const segments = path + .split(/[\\/]/) + .filter((segment) => segment !== '' && segment !== '.'); + if ( + segments.some((segment) => segment === 'node_modules' || segment === '.git') + ) { + return false; + } + if (segments[0] === 'supabase' && segments[1] === 'functions') { + return false; + } + return /\.(ts|tsx|mts|cts)$/.test(segments[segments.length - 1] ?? ''); +} + +export function listSources(root: string, readDir: ReadDir): string[] { + const found: string[] = []; + const pending = ['']; + while (pending.length > 0) { + const relative = pending.pop() ?? ''; + for (const entry of readDir(relative ? `${root}/${relative}` : root)) { + const child = relative ? `${relative}/${entry.name}` : entry.name; + if (entry.isDirectory()) { + if (isSourcePath(`${child}/index.ts`)) pending.push(child); + } else if (entry.isFile() && isSourcePath(child)) { + found.push(child); + } + } + } + return found.sort(); +} + +export function collectSourcesScript(): string { + return [ + 'const __name = (target) => target;', + "const fs = require('fs');", + isSourcePath.toString(), + listSources.toString(), + 'const readDir = (path) => fs.readdirSync(path, { withFileTypes: true });', + 'const out = {};', + "for (const file of listSources('.', readDir)) out[file] = fs.readFileSync(file, 'utf8');", + 'process.stdout.write(JSON.stringify(out));', + ].join('\n'); +} diff --git a/evals/docs/build-docs-036-generating-types/local/CONTRIBUTING.md b/evals/docs/build-docs-036-generating-types/local/CONTRIBUTING.md new file mode 100644 index 000000000..72ebd98c8 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/CONTRIBUTING.md @@ -0,0 +1,6 @@ +# Contributing + +Database changes go in `supabase/migrations`. + +After a database change, run `npm run db:types` to bring the app's types up to date with the local database. Then run +`npm run typecheck`. Both have to pass before a change is merged. diff --git a/evals/docs/build-docs-036-generating-types/local/package.json b/evals/docs/build-docs-036-generating-types/local/package.json new file mode 100644 index 000000000..6a4be39eb --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/package.json @@ -0,0 +1,14 @@ +{ + "name": "bookshop", + "private": true, + "type": "module", + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@supabase/supabase-js": "^2.105.1" + }, + "devDependencies": { + "typescript": "^5.9.3" + } +} diff --git a/evals/docs/build-docs-036-generating-types/local/src/catalog.ts b/evals/docs/build-docs-036-generating-types/local/src/catalog.ts new file mode 100644 index 000000000..7566d50be --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/src/catalog.ts @@ -0,0 +1,37 @@ +import type { Client } from './lib/supabase'; + +export type BookFormat = 'paperback' | 'hardcover' | 'ebook'; + +export type BookCard = { + id: number; + title: string; + author: string; + price_cents: number; + format: BookFormat; +}; + +export async function listBooks(db: Client): Promise { + const { data, error } = await db + .schema('catalog') + .from('books') + .select('id, title, author, price_cents, format') + .order('title'); + if (error) throw error; + return data; +} + +export async function searchBooks(db: Client, term: string) { + const { data, error } = await db + .schema('catalog') + .rpc('search_books', { term }); + if (error) throw error; + return data.map((book) => ({ + id: book.id, + title: book.title, + blurb: book.blurb ?? '', + })); +} + +export function priceLabel(book: BookCard): string { + return `$${(book.price_cents / 100).toFixed(2)}`; +} diff --git a/evals/docs/build-docs-036-generating-types/local/src/lib/supabase.ts b/evals/docs/build-docs-036-generating-types/local/src/lib/supabase.ts new file mode 100644 index 000000000..63eb1c616 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/src/lib/supabase.ts @@ -0,0 +1,8 @@ +import { createClient } from '@supabase/supabase-js'; +import type { Database } from './database.types'; + +export function connect(url: string, key: string) { + return createClient(url, key); +} + +export type Client = ReturnType; diff --git a/evals/docs/build-docs-036-generating-types/local/src/orders.ts b/evals/docs/build-docs-036-generating-types/local/src/orders.ts new file mode 100644 index 000000000..dd67463e5 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/src/orders.ts @@ -0,0 +1,16 @@ +import type { Client } from './lib/supabase'; + +export async function placeOrder( + db: Client, + bookId: number, + quantity: number, + giftNote?: string +) { + const { data, error } = await db + .from('orders') + .insert({ book_id: bookId, quantity, gift_note: giftNote ?? null }) + .select('id, placed_at') + .single(); + if (error) throw error; + return { orderId: data.id, placedAt: new Date(data.placed_at) }; +} diff --git a/evals/docs/build-docs-036-generating-types/local/supabase/config.toml b/evals/docs/build-docs-036-generating-types/local/supabase/config.toml new file mode 100644 index 000000000..65414334a --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/supabase/config.toml @@ -0,0 +1,19 @@ +project_id = "sandbox-generating-types" + +[api] +enabled = true +port = 54321 +schemas = ["public", "graphql_public", "catalog"] +extra_search_path = ["public", "extensions"] +max_rows = 1000 + +[db] +port = 54322 +shadow_port = 54320 +major_version = 17 + +[db.migrations] +enabled = true + +[db.seed] +enabled = false diff --git a/evals/docs/build-docs-036-generating-types/local/supabase/migrations/20250301000000_bookshop.sql b/evals/docs/build-docs-036-generating-types/local/supabase/migrations/20250301000000_bookshop.sql new file mode 100644 index 000000000..4f934becf --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/supabase/migrations/20250301000000_bookshop.sql @@ -0,0 +1,51 @@ +create schema catalog; + +grant usage on schema catalog to anon, authenticated, service_role; + +create type catalog.book_format as enum ('paperback', 'hardcover', 'ebook'); + +create table catalog.books ( + id bigint generated always as identity primary key, + title text not null, + author text not null, + price_cents integer not null, + format catalog.book_format not null default 'paperback', + blurb text +); + +create function catalog.search_books(term text) +returns setof catalog.books +language sql +stable +set search_path = '' +as $$ + select * + from catalog.books + where title ilike '%' || term || '%' + or author ilike '%' || term || '%' + order by title; +$$; + +grant select on catalog.books to anon, authenticated, service_role; +grant execute on function catalog.search_books(text) to anon, authenticated, service_role; + +create table public.orders ( + id bigint generated always as identity primary key, + book_id bigint not null references catalog.books (id), + quantity integer not null default 1, + gift_note text, + placed_at timestamptz not null default now() +); + +alter table public.orders enable row level security; +alter table catalog.books enable row level security; + +create policy "Anyone can browse books" +on catalog.books for select +to anon, authenticated +using (true); + +insert into catalog.books (title, author, price_cents, format, blurb) values + ('The Quiet Orchard', 'Mara Ellison', 1899, 'hardcover', 'A family keeps an apple farm alive through one hard winter.'), + ('Salt and Signal', 'Tomas Reyes', 1299, 'paperback', null), + ('Night Ferry', 'Ada Okafor', 899, 'ebook', 'Strangers share a crossing and a secret.'); diff --git a/evals/docs/build-docs-036-generating-types/local/tsconfig.json b/evals/docs/build-docs-036-generating-types/local/tsconfig.json new file mode 100644 index 000000000..f55e9b364 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/local/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": [] + }, + "include": ["src"] +} diff --git a/evals/docs/build-docs-036-generating-types/refresh.ts b/evals/docs/build-docs-036-generating-types/refresh.ts new file mode 100644 index 000000000..4ac422ba5 --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/refresh.ts @@ -0,0 +1,98 @@ +import { randomBytes } from 'node:crypto'; +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { LocalStackEvalContext } from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; +import { collectSourcesScript } from './files.js'; +import { type Analysis, analyze } from './typecheck.js'; + +export const REFRESH_SCRIPT = 'db:types'; + +export type Refresh = + | { ran: true; column: string; analysis: Analysis } + | { ran: false; reason: string }; + +const PIN_CLI = + '[ -e node_modules/.bin/supabase ] || { mkdir -p node_modules/.bin && ln -s "$(command -v supabase)" node_modules/.bin/supabase; }'; + +export async function refreshAfterChange( + ctx: LocalStackEvalContext +): Promise { + if (!hasScript(ctx.hostWorkspace)) { + return { + ran: false, + reason: `package.json has no "${REFRESH_SCRIPT}" script`, + }; + } + + const column = `shelf_${randomBytes(3).toString('hex')}`; + const altered = await execSql( + ctx, + `alter table catalog.books add column ${column} text;` + ); + if (!altered.ok) { + return { + ran: false, + reason: `the scorer could not add a column to catalog.books: ${altered.message}`, + }; + } + + try { + const result = await ctx.exec( + `${PIN_CLI}; npm run ${REFRESH_SCRIPT} 2>&1`, + { timeoutMs: 300_000 } + ); + if (result.exitCode !== 0) { + return { + ran: false, + reason: `npm run ${REFRESH_SCRIPT} exited ${result.exitCode}: ${lastLines(result.stdout ?? '')}`, + }; + } + const encoded = Buffer.from(collectSourcesScript(), 'utf8').toString( + 'base64' + ); + const collected = await ctx.exec( + `node -e "$(echo ${encoded} | base64 -d)"`, + { timeoutMs: 60_000 } + ); + if (collected.exitCode !== 0) { + return { + ran: false, + reason: `the scorer could not read the workspace back: ${lastLines(collected.stderr ?? '')}`, + }; + } + const overlay = JSON.parse(collected.stdout ?? '{}') as Record< + string, + string + >; + return { + ran: true, + column, + analysis: analyze(ctx.hostWorkspace, overlay, column), + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { ran: false, reason: message.slice(0, 300) }; + } +} + +function hasScript(hostWorkspace: string): boolean { + const manifest = join(hostWorkspace, 'package.json'); + if (!existsSync(manifest)) return false; + try { + const scripts = JSON.parse(readFileSync(manifest, 'utf8')).scripts ?? {}; + return typeof scripts[REFRESH_SCRIPT] === 'string'; + } catch { + return false; + } +} + +function lastLines(output: string): string { + return output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0) + .slice(-3) + .join(' | ') + .slice(0, 300); +} diff --git a/evals/docs/build-docs-036-generating-types/typecheck.ts b/evals/docs/build-docs-036-generating-types/typecheck.ts new file mode 100644 index 000000000..ba3aa3aef --- /dev/null +++ b/evals/docs/build-docs-036-generating-types/typecheck.ts @@ -0,0 +1,358 @@ +import { + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative } from 'node:path'; +import ts from 'typescript'; +import { listSources } from './files.js'; + +const SUPABASE_JS = '@supabase/supabase-js'; +const STRICT_FAMILY = [ + 'strictNullChecks', + 'noImplicitAny', + 'strictFunctionTypes', + 'strictBindCallApply', + 'strictPropertyInitialization', + 'strictBuiltinIteratorReturn', + 'noImplicitThis', + 'useUnknownInCatchVariables', + 'alwaysStrict', +] as const; +const SUPPRESSION = + /(?:\/\/\/?|\/\*+|^\s*\*)\s*@ts-(?:nocheck|ignore|expect-error)\b/; + +export const PROBE = { + books: 'catalog.books Row', + searchArgs: 'catalog.search_books Args', + searchReturns: 'catalog.search_books Returns', + ordersRow: 'public.orders Row', + ordersInsert: 'public.orders Insert', +} as const; +const IMPORT = 'the Database type the client is created with'; +const CONTROLS = ['checker control', 'wrong shape control']; + +export type Analysis = + | { + ok: true; + appDiagnostics: string[]; + suppressions: string[]; + failedProbes: string[]; + controlFired: boolean; + booksRowMatches: boolean; + } + | { ok: false; reason: string }; + +type ClientSite = { file: string; imports: string[]; database: string }; + +type Probe = { + path: string; + text: string; + labels: Map; + controlLines: number[]; +}; + +const readDir = (path: string) => readdirSync(path, { withFileTypes: true }); + +export function analyze( + hostWorkspace: string, + overlay: Record = {}, + extraColumn?: string +): Analysis { + let root: string | undefined; + try { + root = stage(hostWorkspace, overlay); + return typecheck(root, extraColumn); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { ok: false, reason: message.slice(0, 300) }; + } finally { + if (root) rmSync(root, { recursive: true, force: true }); + } +} + +function stage(hostWorkspace: string, overlay: Record) { + const root = mkdtempSync(join(tmpdir(), 'generating-types-')); + const configs = readDir(hostWorkspace) + .filter((entry) => entry.isFile() && /^tsconfig.*\.json$/.test(entry.name)) + .map((entry) => entry.name); + for (const file of [...listSources(hostWorkspace, readDir), ...configs]) { + const target = join(root, file); + mkdirSync(dirname(target), { recursive: true }); + copyFileSync(join(hostWorkspace, file), target); + } + for (const [file, content] of Object.entries(overlay)) { + const target = join(root, file); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, content); + } + const modules = join(hostWorkspace, 'node_modules'); + if (existsSync(modules)) { + symlinkSync(modules, join(root, 'node_modules'), 'dir'); + } + return root; +} + +function typecheck(root: string, extraColumn?: string): Analysis { + const appFiles = listSources(root, readDir) + .filter((file) => file.startsWith('src/')) + .map((file) => join(root, file)); + const sites = appFiles.flatMap((file) => clientSites(file)); + if (sites.length === 0) { + return { + ok: false, + reason: 'no file under src/ calls createClient with a database type', + }; + } + + const probes = sites.map((site, index) => + buildProbe(site, index, extraColumn) + ); + for (const probe of probes) writeFileSync(probe.path, probe.text); + const probeByFile = new Map( + probes.map((probe) => [toPosix(probe.path), probe]) + ); + + const program = ts.createProgram( + [...appFiles, ...probes.map((probe) => probe.path)], + compilerOptions(root) + ); + + const appDiagnostics: string[] = []; + const firedLines = new Map>( + probes.map((probe) => [probe, new Set()]) + ); + for (const diagnostic of ts.getPreEmitDiagnostics(program)) { + const text = ts + .flattenDiagnosticMessageText(diagnostic.messageText, ' ') + .slice(0, 160); + if (!diagnostic.file) { + appDiagnostics.push(text); + continue; + } + const line = diagnostic.file.getLineAndCharacterOfPosition( + diagnostic.start ?? 0 + ).line; + const probe = probeByFile.get(toPosix(diagnostic.file.fileName)); + if (probe) { + firedLines.get(probe)?.add(line); + } else { + appDiagnostics.push( + `${relative(root, diagnostic.file.fileName)}:${line + 1} ${text}` + ); + } + } + + const failed = new Set(); + let controlFired = true; + for (const probe of probes) { + const lines = firedLines.get(probe) ?? new Set(); + for (const line of lines) { + const label = probe.labels.get(line); + if (label && !CONTROLS.includes(label)) failed.add(label); + } + controlFired &&= probe.controlLines.every((line) => lines.has(line)); + } + const failedProbes = [...failed]; + + return { + ok: true, + appDiagnostics, + suppressions: findSuppressions(program, root, probeByFile), + failedProbes, + controlFired, + booksRowMatches: + controlFired && !failed.has(PROBE.books) && !failed.has(IMPORT), + }; +} + +function clientSites(file: string): ClientSite[] { + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true + ); + const imports = source.statements + .filter((statement) => ts.isImportDeclaration(statement)) + .map((statement) => statement.getText(source)); + const sites: ClientSite[] = []; + const visit = (node: ts.Node) => { + if ( + ts.isCallExpression(node) && + calleeName(node.expression) === 'createClient' && + node.typeArguments?.[0] + ) { + sites.push({ + file, + imports, + database: node.typeArguments[0].getText(source), + }); + } + ts.forEachChild(node, (child) => visit(child)); + }; + visit(source); + return sites; +} + +function calleeName(expression: ts.Expression): string | undefined { + if (ts.isIdentifier(expression)) return expression.text; + if (ts.isPropertyAccessExpression(expression)) return expression.name.text; + return undefined; +} + +function findSuppressions( + program: ts.Program, + root: string, + probes: Map +): string[] { + const rootPrefix = `${toPosix(root)}/`; + return program.getSourceFiles().flatMap((source) => { + const name = toPosix(source.fileName); + if ( + !name.startsWith(rootPrefix) || + name.includes('/node_modules/') || + probes.has(name) + ) { + return []; + } + return source.text + .split('\n') + .flatMap((line, index) => + SUPPRESSION.test(line) + ? [`${relative(root, source.fileName)}:${index + 1}`] + : [] + ); + }); +} + +function compilerOptions(root: string): ts.CompilerOptions { + let options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2022 }; + const configPath = join(root, 'tsconfig.json'); + if (existsSync(configPath)) { + const config = ts.readConfigFile(configPath, (path) => + ts.sys.readFile(path) + ); + if (!config.error && config.config) { + options = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + root + ).options; + } + } + const loosened = { ...options }; + for (const key of STRICT_FAMILY) delete loosened[key]; + return { + ...loosened, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + allowImportingTsExtensions: true, + strict: true, + noCheck: false, + noEmit: true, + noUnusedLocals: false, + noUnusedParameters: false, + skipLibCheck: true, + paths: { ...options.paths, [SUPABASE_JS]: [supabaseJsDir()] }, + }; +} + +function supabaseJsDir(): string { + const entry = createRequire(import.meta.url).resolve(SUPABASE_JS); + let dir = dirname(entry); + for (;;) { + const manifest = join(dir, 'package.json'); + if ( + existsSync(manifest) && + JSON.parse(readFileSync(manifest, 'utf8')).name === SUPABASE_JS + ) { + return dir; + } + const parent = dirname(dir); + if (parent === dir) throw new Error(`${SUPABASE_JS} is not installed`); + dir = parent; + } +} + +function buildProbe( + site: ClientSite, + index: number, + extraColumn?: string +): Probe { + const extra = extraColumn ? ` ${extraColumn}: string | null;` : ''; + const db = 'ProbeDatabase'; + const rows: [label: string, line: string][] = [ + ...site.imports.map((line): [string, string] => [ + IMPORT, + line.replace(/\s*\n\s*/g, ' '), + ]), + [IMPORT, `type ${db} = ${site.database.replace(/\s*\n\s*/g, ' ')};`], + [ + '', + 'type ProbeEquals = (() => T extends X ? 1 : 2) extends (() => T extends Y ? 1 : 2) ? true : false;', + ], + ['', 'type ProbeSimplify = { [K in keyof T]: T[K] };'], + [ + '', + `type ProbeBook = { id: number; title: string; author: string; price_cents: number; format: 'paperback' | 'hardcover' | 'ebook'; blurb: string | null;${extra} };`, + ], + [ + '', + 'type ProbeOrder = { id: number; book_id: number; quantity: number; gift_note: string | null; placed_at: string };', + ], + [ + '', + 'type ProbeOrderInsert = { id?: never; book_id: number; quantity?: number; gift_note?: string | null; placed_at?: string };', + ], + [ + PROBE.books, + `export const booksRow: ProbeEquals, ProbeBook> = true;`, + ], + [ + PROBE.searchArgs, + `export const searchArgs: ProbeEquals, { term: string }> = true;`, + ], + [ + PROBE.searchReturns, + `export const searchReturns: ProbeEquals, ProbeBook> = true;`, + ], + [ + PROBE.ordersRow, + `export const ordersRow: ProbeEquals, ProbeOrder> = true;`, + ], + [ + PROBE.ordersInsert, + `export const ordersInsert: ProbeEquals, ProbeOrderInsert> = true;`, + ], + [CONTROLS[0], 'export const checker: ProbeEquals<1, 2> = true;'], + [ + CONTROLS[1], + `export const wrongShape: ProbeEquals, { id: string }> = true;`, + ], + ]; + const labels = new Map(); + rows.forEach(([label], line) => { + if (label) labels.set(line, label); + }); + return { + path: join(dirname(site.file), `scorer-types-probe-${index}.ts`), + text: `${rows.map(([, line]) => line).join('\n')}\n`, + labels, + controlLines: CONTROLS.map((control) => + rows.findIndex(([label]) => label === control) + ), + }; +} + +function toPosix(path: string): string { + return path.split('\\').join('/'); +}