Changelog
O histórico de versões é mantido em inglês.
All notable changes to accessnexus are documented here. The format follows Keep a Changelog and the project uses Semantic Versioning.
[0.4.4-next] - 2026-11-10
Fixed
migration discard:stalelists only the derived files that changed together with the discarded migration, not every derived file. The snapshot of each new migration records them asderivedChanged. Older snapshots still list every derived file.
[0.4.3-next] - 2026-11-10
Third round of the field report.
Fixed
migration discardno longer leaves the SDK ahead of the database. When the schema already matches the restored state, it rewrites the derived files (types, client, React Query, SQL), listed inrefreshed. Otherwise it writes nothing and lists them instale, with a hint to revert the schema and rungenerate.- Releases: the
latestdist-tag is decided from the published versions, not from the currentlatest. When a stable version exists,latestis its highest stable version, and it is restored if it drifted to a pre-release. With only pre-releases published,latestfollows the newest one, because npm always needs alatest.
[0.4.2-next] - 2026-11-10
Second round of the field report: what validating 0.4.1-next in the multi-tenant app found.
Changed
migration discardonly discards: it drops the newest migration that no database applied, restores the snapshot, and returnsregenerated: null. The newmigration amenddoes discard +generateand returns the file it wrote inregenerated, ornullwhen the schema matches the restored state.--no-generateis gone.test-dbdefaults to port 55433, so it no longer collides with the repository's test container on 55439. A port already in use fails withTEST_DB_PORT_IN_USE.- The examples import
'accessnexus'like a real project. In this repository vitest and the examples typecheck alias it tosrc/, and the CLI resolves it from where the bundled schema runs.
Added
- Live plan:
- An index renamed in place (
ALTER INDEX ... RENAME) shows as onerenamedchange withbefore.name/after.name, not as removed + added.summarygainsrenamed. - New risky change
function_result_changed: an RPC's result type changes, so callers break.
- An index renamed in place (
tenantInvitations({ tenantNameAlias }): the column name of the tenant name inmy_invitations, e.g.'org_name'to keep the shape of a hand-written RPC.
Fixed
test-db upon a cold container could fail withConnection terminated unexpectedly, because the image restarts Postgres after its init. It now waits for 3 consecutive host connections (up to 90 s) before preparing the database.- Warnings and plans named a not-yet-generated migration with a timestamp computed on each run. It is now
<pending>__changes.sql. - Releases: pre-releases are published with the
nextdist-tag, andlatestfollows them only while no stable version exists.
[0.4.1-next] - 2026-11-10
Fixes and features from a field report (a multi-tenant SaaS built on 0.4.0). Its schema and RLS suite now ship as examples/saas-teams/ and saas-teams.integration.test.ts.
Changed (SDK behaviour)
- No more silent denials.
update(id),delete(id),updateOneanddeleteOnereturnerror.code === 'ACCESSNEXUS_NOT_FOUND_OR_DENIED'(details: { table, method, id | filter }) when no row was changed, whether the row is missing or RLS hides it or denies the write.- Before,
deletereported success,updatereturned a rawPGRST116, andupdateOne/deleteOnereturneddata: null. delete(id)now asks for the affected-row count. On soft-delete tables it checks the live row before and after, anddeleteOnereturns the row as it was.- React Query mutations throw this error.
- New exports of
client.ts:isNotFoundOrDenied,isAccessDenied(that, or SQLSTATE 42501),isLockedColumnandNOT_FOUND_OR_DENIED.
- Before,
- React Query: the query and mutation of a
RETURNS TABLE/SETOFRPC resolve toRow[], nevernull. trigger.lockColumnsraises one error per column: message<table>.<column> cannot be changed, HINTaccessnexus:locked_column:<table>.<column>. It is still SQLSTATE 42501.- Index names come from their content (
idx_<table>_<columns>[_uniq]) instead of their position. Reorderingindexesgenerates no DDL, and existing snapshots get a one-time migration that renames the indexes (ALTER INDEX ... RENAME, never drop and create). - The foreign-key index (
idx_<t>_<col>_fk, and the policy-column index) is skipped when a declared index starts with that column.
Added
- Migrations with data:
generateanddiffwarnNOT_NULL_COLUMN_ADDEDwhen a new migration adds a NOT NULL column without default to an existing table.- The live plan and
pushstop withNOT_NULL_ON_NON_EMPTY_TABLEand the row count, instead of the raw 23502 error. riskyChangesgainscolumn_nullability_tightened.PUSH_WOULD_FAILreturns the partial plan (wouldApply,changesup to the failure) andfailed.line/failed.statement. When Postgres reports no position, the rehearsal finds the statement by replaying the file statement by statement.migration discard: drops the newest migration when the database never applied it (MIGRATION_ALREADY_APPLIED,MIGRATION_DISCARD_NEEDS_DB,--force), restores the snapshot and regenerates. The snapshot now keeps ahistoryof earlier states (MIGRATION_HISTORY_MISSINGfor older snapshots).migration data <name>: creates a data migrationmigrations/data/<timestamp>__<name>.sql. Push applies it once, in timestamp order with the schema migrations; push now orders all migration files by file name.
- Multi-tenant builders:
tenantInvitations(): invitations table, policies,accept_invitation,my_invitations.defineEnum()+defineSchema(..., { enums }): shared Postgres enums ('enum:<name>'), usable in RPC args and results.- RPC types may also be
'table.column'. trigger.keepAtLeastOne,trigger.sameTenant,trigger.memberOfTenantandtrigger.onAuthUserCreated.trigger.custom({ writes }): React Query mutations then invalidate those tables too.policy.sharesTenant, with a SECURITY DEFINER STABLE helper.definePermissionslevels{ all: [...] }.validate:UNKNOWN_ENUMand checks for every new builder; theTENANT_PARENT_UNCHECKEDhint now suggeststrigger.sameTenant.
- RLS testing:
accessnexus/testingexportsasUser,asAnon,sqlState,affectedRows,expectDenied(an error or 0 rows) andTEST_DB_STANDINS_SQL.test-db up | downstarts a disposable Supabase Postgres in Docker (--pushalso pushes the schema).- New error codes:
DOCKER_NOT_FOUNDandTEST_DB_START_FAILED.
validate --against-dbcompiles the generated SQL, including raw policy, trigger and RPC bodies, in a rolled-back transaction. A rejection becomesSQL_REJECTED, withpathset to the schema item.llms.txt:- An index at the top, with what to read per task.
- "How a denial shows" (error vs 0 rows) and "Testing RLS".
- Recipes: a required column on a table with data, the workspace list via memberships, the invitee seeing the org name.
Fixed
- A schema outside the project (
--schema /tmp/x.schema.ts) could not importaccessnexus. It now falls back to the package the CLI runs from.
[0.4.0] - 2026-11-10
Added
- Supabase Edge Functions, from the schema:
edgeFunction({ auth, input, output })anddefineSchema(tables, { functions })declare each function by name ('invite-member').authis'user'(default),'publishable','secret','none'or an array of them (thewithSupabasemodes of@supabase/server).input/outputuse column types ('uuid','text?',"enum('a','b')",'varchar(20)', ...).generatewritessupabase/functions/_shared/accessnexus.ts, which is derived. Each function gets a<camelName>(handler)wrapper onwithSupabase. The wrapper rejects callers without the required credential and answers CORS. It requires POST and validates the JSON body field by field (400 invalid_inputwithissues) before callinghandler(input, ctx, req), wherectx.supabaseruns as the caller under RLS. It maps the return value to JSON (204when nothing is returned),FunctionErrorto its status, and any other exception to a generic500. Withoutinput, the raw body is left to the handler, for webhook signatures.generatealso scaffoldssupabase/functions/<name>/index.tsonce, when the file is missing. Generated files may now be markedoverwrite: false: created when missing, never compared or replaced after.supabase/config.toml, when it exists, gets a managed block of[functions.<name>] verify_jwt = .... It isfalseonly whenauthaccepts'none'. Tables the user already set outside the block are left alone, with a note in the block.- New config option
output.functions(default./supabase/functions) and new output categoryfunctions. - SDK:
client.functions.<camelName>(input, { headers?, region? })callssupabase.functions.invokewith POST, with typed input and output. New exported types<Name>Input,<Name>OutputandFunctionInvokeOptions. React Query addsq.functions.<name>.query(input)/.mutation(). validate:INVALID_EDGE_FUNCTIONandTABLE_NAME_CLASH(errors), andEDGE_FUNCTION_PUBLIC(warning).validate --jsonaddsfunctions.
- Exported types
EdgeFunctionAuth,EdgeFunctionDefandEdgeFunctionFields.
[0.3.0] - 2026-11-10
Added
- Supabase Realtime, from the schema:
- Table option
realtime: trueadds the table to thesupabase_realtimepublication,realtime: falseremoves it, and leaving it out leaves the publication alone. It works in manual and Database mode.{ replicaIdentity: 'full' }also setsREPLICA IDENTITY FULL. Push applies the new idempotentgenerated/policies/realtime.sql. A database without the publication gets a warning, not an error. channel()anddefineSchema(tables, { channels })declare private Broadcast / Presence channels. Eachreceive/sendrule becomes an RLS policy onrealtime.messages(<prefix>_rt_<channel>_<broadcast|presence>_<receive|send>). The policy is scoped to the extension and the topic ('lobby'or'project:{id}'). Withtable, every rule also requires that the user can SELECT the row the topic names, checked as the user, so the table's RLS decides; malformed keys are denied without errors. Rules:true,false,policy.isAuthenticated / public / none / hasRole / custom({param}placeholder) andany/all. Push drops<prefix>_rt_*policies that are no longer declared and never touches other policies onrealtime.messages.- SDK:
client.<table>.subscribe(listener, { event?, filter?, onStatus? })on realtime tables returns an unsubscribe function. Changes are typed from the row and narrowed byevent. Filters (one column, as Realtime allows) are typed: value, array (in) or{ eq | neq | lt | lte | gt | gte | in }.client.channels.<name>(param)returns the provider's privateRealtimeChannel. New exported types:RealtimeEvent,RealtimeChange,RealtimeChangeOf,RealtimeFilter,RealtimeSubscribeOptions,ChannelOf. Schemas without Realtime generate the same client as before. - React Query:
q.<table>.invalidateOnChange({ event?, filter? })invalidates a realtime table's queries, and those of the tables that embed it, on every change. validate:INVALID_REALTIME,INVALID_CHANNELandCHANNEL_RULE_NOT_SUPPORTED(errors);REALTIME_NOT_READABLE,REALTIME_RLS_DISABLED,REALTIME_REPLICA_FULL_WITH_RLS,CHANNEL_TABLE_NOT_READABLE,CHANNEL_PUBLIC_SENDandCHANNEL_CLOSED(warnings).validate --jsonaddsrealtimeper table andchannels.init --db-urlimports published tables asrealtime: true(withreplicaIdentity: 'full'when set). It lists the existingrealtime.messagespolicies in the schema and the output without importing them.
- Table option
- Exported types
ChannelDef,ChannelAccess,ChannelRuleandTableRealtime.
[0.2.1] - 2026-11-10
Security
- Bump
esbuildto^0.28.2(GHSA foresbuild >=0.27.3 <0.28.1: arbitrary file read through the development server on Windows). AccessNexus only callsesbuild.buildSyncto load the schema and never starts the server, so it was not exploitable through the CLI; the bump clears thenpm auditwarning in projects that installaccessnexus.
[0.2.0] - 2026-11-10
Added
- TanStack Query (React Query) support:
adapterOptions: { reactQuery: true }makesgeneratealso write<sdk>/react-query.ts(same file in manual and Database mode; needs@tanstack/react-queryv5 in the app, AccessNexus does not depend on it).createAccessNexusQueries(client, { queryClient? })returnsqueryOptionsforfindMany/findOne/findByIdon every table (same arguments and generics as the client, socolumns/includenarrowdata), mutation options forcreate,update,delete,updateOne,updateMany,deleteOne,deleteMany, andrpc.<name>.query(args)/rpc.<name>.mutation()for every RPC.queryFn/mutationFnthrow the Supabase error as-is; lists resolve to[]. WithqueryClient, a write invalidates its table and the tables that embed it throughinclude, and an RPC mutation invalidates every AccessNexus query. Keys come from the exportedaccessNexusKeys(['accessnexus', <table>, ...]). SupabaseAdapterOptions.reactQuery(defaultfalse).
Changed
- Generated
client.tsnow exports the<Table>Includetypes (additive).
[0.1.6] - 2026-10-30
Added
rpc({ returns: { table: { booking_id: 'uuid', date_time: 'timestamptz', ... } } })emitsRETURNS TABLE(...)and types the SDK result as rows ({ booking_id: string; ... }[], thesupabase gen typesshape; column types map like table columns,json/jsonb→Json).returns: { setof: 'bookings' }emitsRETURNS SETOF bookingsand typesRow[]of that table;{ setof: 'uuid' }givesstring[].validatereports bad shapes asINVALID_RPC_RETURNS.- SDK:
updateOne(filter, patch, { columns? })/updateMany(...)anddeleteOne(filter, { columns? })/deleteMany(...)on every table: one round trip (.update(patch).match(filter).select(columns),.maybeSingle()for the *One variants), returning the written rows (Row | null/Row[], narrowed bycolumns). The filter is required: unknown columns and{}do not compile (new exportedRowFiltertype), and an empty filter throws before any request, so a mistake never writes the whole table. On a softDelete table they only touch live rows, and the delete variants returnnull/[](the trigger turns the DELETE into an UPDATE). policies: { all: rule }applies one rule to select, insert, update and delete; explicit per-operation keys override it ({ all: policy.isOwner('user_id'), delete: policy.none() }). It expands into the usual one policy per operation (neverFOR ALL), so USING / WITH CHECK, policy names, removed-operation drops and everyvalidatewarning (PUBLIC_WRITE,USER_ROW_INSERT_OPEN, ...) behave as if the keys were written out. Unrelated to thepolicy.all([...])combinator, which is unchanged.definePermissionsresources acceptall: <level>the same way (write pins still apply).
Fixed
init --db-urlimported functions returningTABLE(...)/SETOF ...as an emptyrpc(), so the SDK typed themArgs: Record<string, never>; Returns: unknownand correct calls such asrpc.get_client_bookings({ p_client_id })did not compile. They are now imported fully (args,returns: { table }/{ setof }, body). A function whose result or an argument typerpc()still cannot express (record, composite types, OUT parameters) is imported signature-only with its realargs(a composite argument typed'json'), never as an argument-lessrpc().- Changing an RPC's result type (scalar, TABLE columns, SETOF) or an argument name made
pushfail with "cannot change return type of existing function". Each generated function is now preceded by a guard that drops it (no CASCADE) when its result or argument names differ, inside the push transaction; an unchanged function is never dropped. If a policy, view or function depends on it the push fails and applies nothing — change the dependent first. The live plan shows it as a changed function, not a dropped one.rpcs.sqlchanges for every RPC with a body (the guard block); regenerate.
[0.1.5] - 2026-10-30
Fixed
- The client wrappers
initwrites for Next.js, Vite, CRA and other bundler projects import./clientinstead of./client.js. Turbopack (next build) could not resolve./client.jstoclient.ts, so the build broke as soon as app code imported a wrapper. Plain Node keeps./client.jsunless its tsconfig usesmoduleResolution: "bundler". Wrappers written by an earlierinitare yours: change the import by hand (generatenever overwrites them).
[0.1.4] - 2026-10-30
Added
- SDK:
findOne(filter, options?)on every table:.match(filter).maybeSingle(), returningRow | nullwithout an error when nothing matches (lookups byslug,email, ...). - SDK:
columnsoption onfindMany/findOne/findById:{ columns: ['id', 'name'] }sendsselect('id, name')and narrows the result toPick<Row, 'id' | 'name'>. Unknown column names are compile errors; it combines withinclude. New exported helper typesColumnsOfandSelectedRow;AccessNexusProvideris now exported. - SDK (manual mode):
types.tsexportsJson, identical to theJsonofsupabase gen types(also re-exported fromclient.ts).
Changed
- SDK:
authkeeps the provider's type (TClient['auth']) instead ofunknown, sodb.auth.signInWithOAuth(...)typechecks withcreateClient/createBrowserClient/createServerClient.AccessNexusClienttakes the provider type:AccessNexusClient<SupabaseClient<Database>>(the argument is optional). - SDK:
json/jsonbcolumns (and RPC args/returns) are typedJsoninstead ofRecord<string, unknown>, so rows are compatible with Supabase's generated types (jsonb can be an array, string, number, boolean or null). Code that read properties straight off a jsonb value now needs a narrowing check. - SDK: manual-mode row types are type aliases instead of interfaces, so they satisfy supabase-js'
GenericTableand the generatedDatabasecan be passed tocreateClient<Database>(). Interface declaration merging on them no longer works. - SDK:
findByIdusesmaybeSingle()instead ofsingle(): a missing (or RLS-hidden) row is now{ data: null, error: null }instead of a PGRST116 error. Code that relied onerrorto detect "not found" should checkdata === null. - SDK:
delete(id)is typedQueryResult<null>(supabase-js returnsdata: nullfor a delete without.select()).
[0.1.3] - 2026-10-29
Fixed
pushapplies RPCs before policies and triggers (migrations → rpcs → policies → triggers). On a fresh database a policy calling anrpc()helper failed because the function did not exist yet.init --db-urlno longer takesanonaway from definer functions. It emittedrpc({ security: 'definer' })withoutallowAnon, sopushrevokedanonfrom every SECURITY DEFINER function anon could execute (directly or viaPUBLIC):TO publicpolicies calling such a helper made anonymous SELECTs fail with "permission denied for function" instead of returning 0 rows. init now reads the effective privilege (has_function_privilegeforanonandauthenticated) and emitsallowAnon: truewith a// NOTE:comment where anon could execute the function;init --jsonlists them inanonExecutableFunctions(and the human output prints them) so maintenance/admin functions exposed to anon get a deliberate decision. A definer function authenticated could not execute gets a// NOTE:andauthenticatedGrantedFunctions(rpc()always grantsauthenticated). Invoker functions keep their grants as before.diff --against-dbjudges grants on effective access, not on the ACL's literal shape:grant_widenedis no longer reported when anon already hadEXECUTEviaPUBLIC. The grant snapshot carrieseffective(PUBLIC / anon / authenticated, viahas_function_privilege/has_table_privilege) next to the literalprivileges, and grant changes carrynotessuch asanon EXECUTE: via PUBLIC → direct grant (no change in access).diff --against-dbwith--replace-foreign-triggersreported the original trigger functions asfunction_dropped. They were never dropped (the plan stopped looking at them once their trigger was gone); the after-snapshot now covers the same functions.- Generated SDK passes typescript-eslint
recommended:Record<string, never>for RPCs without arguments (no-empty-object-type),unknowninstead of{}in the include helpers, and noanyin the provider type. RPCs without arguments can be called asclient.rpc.name().
Added
grant_narrowedrisk code:PUBLIC,anonorauthenticatedlose effective access to an existing function or table (PUBLIClosing a privilege anon and authenticated both keep is not flagged).push --replace-foreign-triggers(and the live plan) returnkeptTriggerFunctions: the functions of the dropped triggers, which are never dropped, with what still depends on them (pg_depend: triggers in any schema, other objects) andorphaned.ForeignTriggergainsfunction.
[0.1.2] - 2026-10-29
Added
rpc({ volatility: 'volatile' | 'stable' | 'immutable' }).immutable: truestill works as an alias; a contradicting pair is reported asRPC_VOLATILITY_CONFLICT. Declare read-only helpers used in RLS policies'stable'so Postgres can evaluate them once per query.rpc({ set })andtrigger.custom({ set }): function configuration such as{ row_security: 'off' }, emitted asSET key = 'value'(keys validated as GUC names, values quoted;INVALID_FUNCTION_SETotherwise).search_pathstays pinned topg_catalog, public; a differentset.search_pathis ignored with aSEARCH_PATH_PINNEDwarning.init --jsonreturnshardenedFunctions: every imported RPC or trigger function whosesearch_pathgeneratechanges (from another value, or none, topg_catalog, public).diff --against-db: a live-database change plan.diffcompared the schema with the generated files, so an agent could not see what a push would really change (and found regressions such as STABLE → VOLATILE functions or a lostSET search_pathonly after pushing). The new mode rehearses the push: it takes the push lock without waiting (PUSH_LOCKED), BEGINs, snapshots the catalog of the managed tables (columns, defaults, constraints, indexes, RLS, policies, triggers, grants) and of the functions the SQL defines or the triggers call (volatility, security definer,proconfig, body hash), runs the push code path, snapshots again and ROLLs BACK — nothing persists, not evenaccessnexus_migrationsrows. The result listschanges(kind,object,change,before,after,fields),riskyChanges(function volatility/config/security changes, widened policy roles, dropped policies/triggers/functions/tables/columns, lost defaults, type changes, relaxedNOT NULL, RLS disabled, grants widened toanon/PUBLIC) and theblockersa real push would stop at. Takes the same--url/--db-url/env/--targetresolution aspushand its--replace-foreign-*/--allow-destructiveflags.--checkexits 1 withLIVE_DB_CHANGES; a push Postgres would reject exits 1 withPUSH_WOULD_FAIL(failed: { file, message, sqlState }).push --dry-runruns the same rehearsal on the files on disk when a database URL is set and returns it aslivePlan(wouldRefusealso covers its blockers and failures).Plain
diffadds ahintpointing to--against-dbwhen a database URL is configured. TheAGENTS.mdblockinitwrites andllms.txttell agents to rundiff --against-db --json(orpush --dry-run --json) before any push and reviewriskyChangeswith the user.
Fixed
init --db-urlno longer loses function volatility:STABLE/IMMUTABLEfunctions were re-created asVOLATILE(an issue for helpers used inside RLS policies). They are imported asvolatility.init --db-urlkeeps everySEToption of a function or trigger function (pg_proc.proconfig, e.g.row_security = off) instead of onlysearch_path.- The
search_pathrewrite on import is no longer silent: each affected function gets a// NOTE:comment in the generated schema and is listed in the init output.
[0.1.1] - 2026-10-29
Security
pushno longer leaves foreign RLS policies in place silently. It readspg_policiesfor every table the schema manages and refuses with the newFOREIGN_POLICIESerror (exit 1, nothing applied) while any policy there is not named<prefix>_<table>_<op>: Postgres ORs permissive policies, so an imported project's original policies kept granting access next to the generated ones. The new--replace-foreign-policiesflag drops them in the push transaction (droppedPoliciesin--json);push --dry-runlists them (foreignPolicies,wouldRefuse) when a database URL is set.- Same for triggers: after
init --db-url, an imported trigger and the original would both fire (an audit insert or a counter running twice).pushrefuses withFOREIGN_TRIGGERSwhile a managed table has a trigger not named<prefix>_<table>_...;--replace-foreign-triggersdrops them in the push transaction (droppedTriggers). pushno longer createspublic.uuid_generate_v7(), which returned a random v4 UUID and was callable byanonthrough PostgREST. The only UUIDv7 helper ispublic.accessnexus_uuidv7()(a real RFC 9562 v7), now with EXECUTE revoked fromPUBLICandanon(granted toauthenticatedandservice_role, and toanononly when a v7 table accepts anonymous inserts). Databases pushed with 0.1.0 may still have the old function: check that no column default uses it, thenDROP FUNCTION public.uuid_generate_v7();. Already-applied migrations are immutable, so an existingaccessnexus_uuidv7()keeps its grants: runREVOKE EXECUTE ON FUNCTION public.accessnexus_uuidv7() FROM PUBLIC, anon; GRANT EXECUTE ON FUNCTION public.accessnexus_uuidv7() TO authenticated, service_role;.
Fixed
pushis atomic: migrations, policies, triggers, RPCs, theaccessnexus_migrationsbookkeeping and foreign-policy drops run in one transaction (still under the advisory lock). A failure anywhere rolls back the whole push;PUSH_FAILEDnow reportsapplied: [],rolledBack(the files that had run) andfailed(the file Postgres rejected). Failed attempts are no longer recorded assuccess = falserows. Limit: a migration cannot use an enum value added earlier in the same push (Postgres forbids it in a transaction).uuidGeneration: 'v7'now also applies to tables added in a__changesmigration (they gotgen_random_uuid()), and that migration defines the helper before the table.pushandseedaccept--db-urlas an alias of--url(the flaginituses); passing both with different values isINVALID_FLAG_VALUE.
Fixed (init --db-url)
init --db-urlimports user triggers astrigger.custom(timing, events,FOR EACH,WHEN,SECURITY DEFINERand the function body kept;UPDATE OFbecomes aWHEN). Triggers it cannot express (arguments, disabled,INSTEAD OF,TRUNCATE-only, non-plpgsql) are left as// WARNING:comments instead of being dropped silently.validateaccepts names with one leading underscore (_pix_crc16) for RPCs, tables and columns (INVALID_IDENTIFIERrejected functions thatinithad imported).- RPC parameter defaults are imported and emitted:
args: { p_limit: { type: 'int', default: '20' } }→p_limit INTEGER DEFAULT 20(optional in the client types), soCREATE OR REPLACEworks on functions that have defaults.validatereportsINVALID_DEFAULTfor an argument without default after one with a default. - Column defaults are imported (
now(),0,gen_random_uuid(), ...);nextvalbecomesserial. numeric/numeric(p,s)are kept instead of becomingdouble precision(new column typesnumeric,numeric(p),numeric(p,s)); enums are imported asenum(...),text[]/int[]/uuid[]arrays keep their type, and unknown types are flagged.- Foreign keys to other schemas (
auth.users) are imported, with theirON DELETE. - Composite primary keys are imported as the new
compositePrimaryKey: ['a', 'b']table option (emitsPRIMARY KEY (a, b);validatereportsINVALID_PRIMARY_KEYfor misuse), and composite UNIQUE constraints as uniqueindexesinstead of per-columnunique. init --db-urlno longer printsDeprecationWarning: Calling client.query() when the client is already executing a query: catalog queries run one at a time.- A
trigger.custombody that has its ownDECLARE/BEGIN ... ENDblock is emitted as is.
Docs
- Existing project guide: a safe first push that reviews and replaces the foreign policies.
- Limits:
diffcompares against the snapshot, not the live database (diff --against-dbis planned).
0.1.0 - 2026-10-29
First public release.
Schema engine
defineSchema/tablein two modes: manual (explicitcolumns) and Database mode (columns from a Supabase-generatedDatabasetype).- Generates versioned migrations (
<timestamp>__init.sql/__changes.sqlwith a.snapshot.json), RLS policies, triggers, RPCs and a typed SDK (createAccessNexusClient). policy.*builders:isAuthenticated,public,none,isOwner,hasRole,belongsTo,matchesField,custom,any,all,withCheck.definePermissions: centralized RBAC with multi-tenant scoping ({ scope: 'tenant', roles }).trigger.*:updatedAt,softDelete,auditLog,lockColumns(RLS is row-level; this freezes columns or limits which ones a user may change),custom(invoker or definer);rpc();defineSeed;defineConfig(includingtargetsfor--target).- Foreign keys accept
onDelete('cascade' | 'set null' | 'restrict' | 'no action'), per column or as a table map; the default staysNO ACTION. definePermissionsis typed by its resources:policiesFor('taks')is a type error.
Secure by default (RLS)
- Removing a rule revokes it: each policy file drops the policies of operations that are no longer in the schema (or of tables with no
policies), so the nextpushremoves them. (SELECT auth.uid())initPlan wrapping,ENABLE+FORCE ROW LEVEL SECURITY, separateUSING/WITH CHECK; UPDATE policies always carry an explicitWITH CHECK.- Fail closed: every table gets
ENABLE+FORCE ROW LEVEL SECURITY; a table withoutpoliciesis deny-all for the API (NO_POLICIESwarning). Only an explicitenableRLS: falseleaves a table open (RLS_DISABLEDwarning);init --db-urlwrites it for tables whose RLS is off in the database, so adopting a project changes nothing silently. policy.belongsTo(col)withoutthrough(lookup inprofiles.<col>) is rejected byvalidate(BELONGS_TO_PROFILE_WRITABLE) while users can write that profile column.policy.withCheck(using, check)requires the written row to pass both rules ({ mode: 'replace' }to check only the second).definePermissionspins writes:createrequiresownerColumn = auth.uid()(pinOwnerOnCreate), andcreate/updatekeep rows inside a tenant the user belongs to (pinTenant).policy.hasRoleand permission role arrays read the server-controlled JWTapp_metadata.roleclaim, never the Postgresroleclaim.- Membership checks compile to
SECURITY DEFINERhelpers withSET search_path = pg_catalog, public(no RLS recursion) and EXECUTE revoked fromPUBLIC/anon. - Audit-log and soft-delete trigger functions run as
SECURITY DEFINERwith schema-qualified targets, so audit tables stay closed to API inserts. A guard rejects plain UPDATEs of the soft-delete column by API users, so only DELETE (and its policy) can soft-delete a row; the SDK'sdelete()issues a real DELETE. - A
selectpolicy is grantedTO publicwhen a branch can pass without a user (public-read tables really are readable by anonymous visitors); writes areTO publiconly for an explicitpolicy.public(). security: 'definer'RPCs getREVOKE EXECUTE ... FROM PUBLIC, anon(opt back in withallowAnon: true).init --db-urlimports policies fail-closed: it keeps each policy's roles (aTO service_rolepolicy is not opened to everyone), AND-s RESTRICTIVE policies, skips anon-only policies with a TODO and maps "RLS on, no policy" topolicy.none().- Every interpolated string literal is quoted; reserved SQL keywords are rejected as names.
Built for AI coding agents
llms.txtships in the package: full API with typechecked examples, the agent workflow, recipes (owner-only, public read, multi-tenant with roles, child of a tenant resource, column-scoped updates, audit log), RLS rules and troubleshooting by error code.accessnexus initwrites an idempotent<!-- accessnexus:start -->block into the project'sAGENTS.md(and a pointer inCLAUDE.md);--no-agentsskips it.- Every command is non-interactive without a TTY;
init --yesplus flags (--src,--sdk,--prefix,--db-url,--no-introspect,--install,--force) for full automation.initworks in any Node project (Next.js, Vite, CRA, or plain Node), andinit --yesin an empty folder creates a minimalpackage.json. Its next steps print real import specifiers, and the client wrapper it writes is marked as the user's file to edit. - The documented agent workflow is
validate → diff → generate → push --dry-run → push. --jsonon every command prints exactly one JSON object; exit codes0ok,1user-fixable,2internal. Colors are off when not a TTY or withNO_COLOR.- Errors carry a stable
code, a message and aFix:hint; stack traces only with--verbose/DEBUG=accessnexus. Unknown commands and flags fail with a did-you-mean. validateruns static checks (unknown tables/columns in policies, triggers, references and indexes; wrong column types; reserved names; non-uuid owner columns; audit table mismatches; global roles mixed with tenant checks; tables without RLS; bareauth.uid()in custom SQL and RPC bodies; bare-word defaultsINVALID_DEFAULT;INVALID_ON_DELETE;CASCADE_INTO_SOFT_DELETE;DUPLICATE_TRIGGER; misspelled table options or tables nested undertables:UNKNOWN_TABLE_KEY; role typos inbelongsTowhereINVALID_ENUM_VALUE; writes open to anonPUBLIC_WRITE; user-keyed tables anyone can insert intoUSER_ROW_INSERT_OPEN; tenant lookups through a user-writable profile columnBELONGS_TO_PROFILE_WRITABLE; child rows that can point into another tenantTENANT_PARENT_UNCHECKED; tables without policiesNO_POLICIES).help --jsonand<command> --help --jsonprint the help as one JSON object.- Database connections (
push,seed,init --db-url) time out after 10 s withDB_CONNECTION_FAILEDinstead of hanging (ACCESSNEXUS_DB_CONNECT_TIMEOUT=<seconds>). --output <dir>puts every output folder under<dir>, even whenaccessnexus.config.tssets per-folder paths.
CLI safety
pushrefuses generated SQL that is out of date with the schema, refuses pending migrations that drop tables/columns or change column types without--allow-destructive, re-applies changed policy/trigger/RPC files safely, refuses a role withoutBYPASSRLS(PUSH_ROLE_NO_BYPASSRLS, needed by the SECURITY DEFINER helpers), and reports when it waits for another push's lock.init --db-urlwithout thepgdriver reportsPG_DRIVER_MISSING(npm install -D pg).- The seed never runs implicitly (
push --seedoraccessnexus seed); seededauth.usersget a random password (ACCESSNEXUS_SEED_PASSWORDto choose one); seeding hosted Supabase requires--allow-remote-seed. diff --checkfor CI;diffprints only changed hunks and ignores theGenerated at:line.- Schema, config and seed files are bundled with esbuild (a dependency), so Node >= 20, TypeScript-only syntax and extensionless imports all work.
Reference example
examples/fullstack-saas.schema.tscloses the holes found in review: managers cannot take over an org throughowner_id(admin-only update, column locked, first admin added by a definer trigger instead of a replayable bootstrap rule), profiles are insert-own and visible to org mates only, tasks/comments cannot point at another org's rows, reporters/authors are frozen, assignees change only status/position, andaccept_invitationwraps auth calls and rejects anon. Joining an org needs consent: memberships are created only by the owner trigger andaccept_invitation(which also requires a confirmed email), so nobody can add a stranger to their org to read their profile; orgs are visible to their members only. Every attack is replayed by the integration test.