The Create core
How better-supabase/create holds the design model, previews and Supabase deploy client that /create and other apps share.
better-supabase/create is the headless code behind
Create. It runs on every runtime,
including the browser, and has no dependency beyond the Supabase packages.
Designs stay in the URL or in your own storage, as ADR 0040 requires.
import { previewFiles, diffDesigns } from "better-supabase/create";
import { defaultPreset } from "better-supabase/preset";
const base = { preset: defaultPreset() };
const files = previewFiles(base);
console.log(files.map((file) => file.path));diffDesigns(base, next) classifies each change as safe or breaking, so an
app can block a breaking change before it deploys.
Load and check a project
getProject(input, { preset }) reads a design object, a design code or a
/create URL into a Project: the preset, the design and the files upgrade
would write. Pass ownTables (and ownColumns) to render the files over the
tables the project already has, as the CLI does. checkProject(project)
returns every problem as one list of Issue. Its sql option adds what
Postgres rejects, for example checkProject(project, { sql: sqlIssues }) with
sqlIssues from better-supabase/create/lite.
import { checkProject, getProject } from "better-supabase/create";
const loaded = await getProject(body.design, { preset: body.preset });
if (!loaded.ok) {
return reply(loaded.issues);
}
const issues = await checkProject(loaded.project);The instance rules the canvas needs are exported from better-supabase/preset
too: canAddInstance, blockRequires, instanceNameProblem,
withInstance, withoutInstance, withEntityName, installedBlocks,
presetKey, and createQuery with presetArgumentOf for the links and
commands.
Check a design
checkDesign(input, preset) runs every rule the canvas and upgrade apply
to a design, so a server route, an MCP tool and the canvas give the same
answer. input is a design object, a design code or a /create URL with
?design=; preset is a preset name or object.
import { checkDesign } from "better-supabase/create";
const check = await checkDesign(body.design, body.preset);
if (check.ok) {
if (check.fitsUrl) {
save(check.design, check.code);
} else {
offerDesignFile(check.design);
}
} else {
console.log(check.issues);
// [{ code: "table_name_taken", severity: "error", source: "rules",
// path: "/appTables/profiles", table: "profiles",
// message: "A block already creates a profiles table. Rename this one." }]
}It never throws for a bad design or preset. Each problem is an Issue, the one
type every surface reports (the canvas, the chat tools, the API and the CLI),
with a stable code, a severity, a source (design, rules, sql,
verifier or plan), a path, the table it is on (or design or preset for one
outside a table) and a message: a design that doesn't parse, a preset that
can't install, extra columns on a block the preset doesn't install, a table
name a block already uses, or a reference to a block table the preset doesn't
install. path is a JSON Pointer
into the design, such as /appTables/tasks/columns/title, so a form can mark
the field; it is "" for an issue with the preset. A design that doesn't
parse carries a DesignErrorCode; the
rules that need the preset add these codes:
| Code | What it means |
|---|---|
table_name_taken | a block already creates a table with this name |
name_too_long | a table name too long for the names Postgres derives from it |
subject_type_taken | another app table already has this subject type |
invalid_default | a column default its type doesn't accept |
default_required | a required column signed-in users can't write, with no default |
column_clash | a column that clashes with one its record features add |
unknown_column | a unique key or index naming a column the table doesn't have |
missing_reference | a reference to a table the preset doesn't install |
set_null_required | a set-null delete on a required column |
preset_conflict | a conflict in the preset itself, such as a block that needs tenants |
invalid_preset | a preset that isn't a preset name or object |
On success, design has its empty parts dropped and fitsUrl says whether
its code fits in a /create URL. code is its encodeDesign code, and
null only when fitsUrl is false; offer the
design file then.
To check only the shape of an untrusted payload, without a preset, use
parseDesign from better-supabase/preset.
Supabase deploy
better-supabase/create/supabase signs a user in with Supabase OAuth and
PKCE, seals the session in a cookie value, and wraps the Management API.
import { managementClient } from "better-supabase/create/supabase";
const client = managementClient(accessToken, fetch);
const projects = await client.projects();Pass your own fetch to trace or stub the calls in tests.
Deploy records
Give every deploy an id so a project can be matched to the preset it came
from. newDeployId() returns a random UUID, and deployQuery(files, { id })
writes it as -- better-supabase deploy <id> on the first line of the
migration. DeployResponse carries the id, the preset (a name or an object, as the
config's preset key takes it) and the design code (or null), and the host
app stores them as a DeployRecord:
import {
deployQuery,
MIGRATION_NAME,
newDeployId,
type DeployRecord,
} from "better-supabase/create";
const id = newDeployId();
const migration = deployQuery(files, { id });
// After the migration applies:
const record: DeployRecord = {
id,
ref: project.ref,
preset: presetSpec(resolved.preset),
design: designCode,
migration: MIGRATION_NAME,
deployedAt: Temporal.Now.instant().toString(),
};Keep the record in your own table, keyed by the user who deployed. A visitor
who deploys before signing in to your app can keep the records in a sealed
cookie, and you move them to the table once they sign in. To find the record
for a project later, search the statements of the better_supabase_blocks
row in supabase_migrations.schema_migrations for the comment and look up its
id.
OAuth for other providers
better-supabase/create/oauth holds the parts of the Supabase sign-in that
don't depend on Supabase, so a second provider (a deploy target or a Git host)
can reuse them. It runs on WebCrypto only, on every runtime.
| Export | What it does |
|---|---|
OAuthSession, isOAuthSession | An access token, an optional refresh token and expiresAt in ms |
OAuthFlow, isFlow | The state, PKCE verifier and return path kept between redirects |
pkcePair(), randomToken() | A PKCE verifier with its S256 challenge, and random base64url tokens |
seal(value, secret, info?) | Encrypts a value with AES-GCM under a key derived through HKDF |
unseal(sealed, secret, guard, info) | Opens a sealed value, or returns undefined when it doesn't verify |
needsRefresh(session, now) | Whether the access token expires within a minute |
OAuthError, DEFAULT_SEAL_INFO | The error the flows throw, and the HKDF info used when none is given |
Give each cookie its own info, so a cookie sealed for one provider can't be
replayed as another:
import { isOAuthSession, seal, unseal } from "better-supabase/create/oauth";
const cookie = await seal(session, secret, "my-app vercel session");
const back = await unseal(
cookie,
secret,
isOAuthSession,
"my-app vercel session",
);better-supabase/create/supabase re-exports these helpers. SupabaseSession
and isSession stay as aliases of OAuthSession and isOAuthSession, and
cookies sealed before this subpath existed open with the default info.
Migrate between versions
migrationBetween(preset, base, next) writes the migration that takes a project
deployed from one design to the next. It covers added tables and added
columns, which the app-table SQL applies idempotently.
import { migrationBetween } from "better-supabase/create";
const plan = migrationBetween("saas", deployed, edited);
if (plan.ok) {
await client.applyMigration(ref, "better_supabase_design", plan.sql);
} else {
console.log(
plan.reason,
plan.changes.map((change) => change.steps),
);
}A breaking refusal lists the expand and contract steps for each change. An
unsupported refusal covers any other change, such as a new default or a
change outside tables, so a deploy never guesses.
Import an existing project
importProject in better-supabase/create/lite reads a project that already
exists and returns a Design plus a report, so Create can open it.
import { importProject } from "better-supabase/create/lite";
const { design, report } = await importProject({
source: { kind: "supabase", projectRef, accessToken },
});There are three sources:
| Source | Reads |
|---|---|
{ kind: "files", files } | A declarative schema folder or a migrations folder, as { path, contents }. The files run in path order against an in-memory PGlite database. |
{ kind: "queryable", queryable } | Any object with query(sql) that returns { rows }, such as a pg pool. |
{ kind: "supabase", projectRef, accessToken } | A hosted project, through the Management API's read-only query endpoint. |
The design models each public table that has a single uuid or bigint
id key: its columns, references to other modeled tables or auth.users,
unique keys and plain btree indexes. Tables come in with scope: "none",
because their columns are already explicit. Anything the design cannot express
is listed in report.preserved and is never dropped, because a deploy applies
only what the design adds. That covers views, functions, triggers, policies,
composite keys, generated columns and types such as interval. Tables named
bsb_* are listed in report.blockOwned.
report.tables gives each table an adoption rung: open (row level security
off), locked (on, no policies) or protected (on, with policies).
report.issues holds SQL errors from a files source and the security
findings, which have source: "verifier": verify_rls_disabled and
verify_no_policies. Pass design to getProject with a preset to check and
render it.
Try a design in a sandbox
openSandbox applies a project's files to an in-memory PGlite database, with
the Supabase roles in place and the API roles granted what Supabase grants
them by default. Queries run as the database owner, or as a persona with row
level security applied.
import { getProject } from "better-supabase/create";
import { openSandbox } from "better-supabase/create/lite";
const loaded = await getProject(design, { preset: "saas" });
if (loaded.ok) {
const sandbox = await openSandbox(loaded.project);
const ada = sandbox.as({ sub: "00000000-0000-4000-8000-00000000000a" });
const result = await ada.query("select * from public.tasks");
// { ok: true, rows: [...] } or { ok: false, error: { code, message } }
const response = await ada.rest(
new Request("http://localhost/rest/v1/tasks?select=title&order=title"),
);
await sandbox.close();
}as({ sub, role, claims }) sets request.jwt.claims and the role for one
transaction. A failed statement rolls back. sandbox.rest(request) also takes
the persona from the bearer token's payload, which the sandbox decodes and
does not verify.
The REST handler is a subset of PostgREST. It answers GET, POST, PATCH
and DELETE on /rest/v1/<table> with select, the filters eq, neq,
gt, gte, lt, lte, like, ilike, is and in (with not.),
order, limit and offset, Prefer: return=representation, the single
object Accept header, and POST /rest/v1/rpc/<function>. Embedding, or,
and and range headers return 400. A write that a policy rejects answers
403, or 401 for an anonymous caller.
The Data API document of a design
designDataApi(preset, design, options) renders the design in a sandbox and
returns the OpenAPI 3.1 document of the Data API it produces: /rest/v1
paths for each table, with row, insert and update schemas.
import { designDataApi } from "better-supabase/create/lite";
const result = await designDataApi("saas", design, {
title: "Acme Data API",
supabaseUrl: "https://abcdefgh.supabase.co",
});
if (result.ok) {
console.log(result.tables, result.document);
} else {
console.log(result.issues);
}A design checkProject rejects returns its issues instead. Functions are
not part of the document yet.
Validate in Postgres
better-supabase/create/lite applies the generated files to an in-memory
PGlite database through the optional @supabase/lite peer, and reports what
Postgres rejects before anything reaches a project.
import { previewFiles } from "better-supabase/create";
import { validateDesign } from "better-supabase/create/lite";
import { defaultPreset } from "better-supabase/preset";
const files = previewFiles(defaultPreset());
const { ok, issues, skipped } = await validateDesign(files);
// issues are `Issue` values with `source: "sql"`, the module in `table`
// and the file in `file`.PGlite starts without a Supabase project's roles and auth schema, so the
function creates a minimal copy first. A module that needs an extension PGlite
doesn't ship (pgmq for jobs, btree_gist for time tracking) lands in
skipped instead of failing. pgTAP is not available through
@supabase/lite, so database tests still run with supabase test db.
To check security instead of syntax, verifyFiles applies the same files, reads the
catalog and returns Issue values with source: "verifier" plus an access matrix. A file
Postgres rejects comes first as a sql_error issue with source: "sql", because its tables
are missing from the catalog, and skipped lists the modules PGlite can't run, as in
validateDesign:
import { verifyFiles } from "better-supabase/create/lite";
const { issues, matrix, skipped } = await verifyFiles(files, {
tenantScoped: ["public.projects"],
});
// issue codes: verify_rls_off, verify_policy_true, verify_anon_write,
// verify_anon_reads_all, verify_public_grant, verify_definer_search_path,
// verify_force_off, verify_scope_missing.
// matrix cells: table, role (anon or authenticated), command and reach
// (denied, policy or open).verifyQuery, getSecurityCatalog and verifyCatalog do the same over a live database:
run the query, read the row, then verify it.
On /create, the Migrations tab of Get code has a Validate in Postgres button that runs the same check on the server for the current selection and design.
Gate a migration plan
gatePlan applies the rename and data loss rules to a migration plan from pg-delta (ADR 0106). A
rename becomes a rename only when a -- bsb: rename old -> new line confirms it, an ambiguous
candidate never does, and a destructive action blocks the plan unless you allow data loss.
import { gatePlan, parseRenameHints } from "better-supabase/create";
const gate = gatePlan(plan, {
hints: parseRenameHints(editLog),
allowDataLoss: false,
});
// gate.accepted, gate.questions, gate.unresolved, gate.destructive, gate.blocked
// gate.issues are `Issue` values with `source: "plan"`.Last updated on