Docs

Guide 04

Drivers

04. Drivers

This page covers the vendor rule, the contracts drivers implement, capability narrowing, and how to write, configure, and fake a driver.


The Rule

Application code never names a vendor. Not in a controller, a model, a view, or a test. Write Auth.user(), never supabase.auth.getUser().

Vendor names appear in exactly 2 places:

  • avelon.config.ts
  • driver packages

Bailiff enforces it. A stray import { createClient } from '@supabase/supabase-js' anywhere under app/ fails the build.

Everything below exists to make that rule survivable. The usual way it fails is a lowest-common-denominator abstraction nobody can ship real work on.


Capability Map

A driver package implements one or more contracts. @avelonjs/supabase and @avelonjs/neon each cover 6. That's why "install the Neon driver" stays a one-line setup even though the architecture is pluggable.

ContractOwnsv1Later
databasequeries, writes, migrations, ward compilationSupabase, Postgres, NeonMySQL, SQLite, Turso, PlanetScale
identitywho the actor is, sessions, sign in and out, registrationSupabase, NeonClerk, WorkOS, Auth.js
socialOAuth redirect and callbackSupabase, NeonClerk, Auth.js, standalone providers
tokensAPI tokens, abilities, revocationSupabase, NeonClerk, custom JWT
storagefiles, signed URLs, transformsSupabase, Neon (S3)R2, GCS, UploadThing
queueenqueue, drain, retry, dead letterSupabase, NeonQStash, SQS, Redis, Inngest
mailtransactional send, templatesResendPostmark, SES, SendGrid, SMTP
cacheget, put, tags, lockscontract plus fakeRedis, Upstash, Vercel KV
realtimechannels, presence, broadcastcontract plus fakeSupabase, Pusher, Ably, PartyKit
searchindex, query, facetscontract plus fakeTypesense, Meilisearch, Algolia
paymentscustomers, subscriptions, checkout, webhookscontract plus fakeStripe, Paddle, Lemon Squeezy
notificationspush, SMS, in-appcontract plus fakeTwilio, Expo, Knock
flagsfeature flags, targetingcontract plus fakePostHog, LaunchDarkly, Vercel
logsstructured logs, tracesconsoleAxiom, Sentry, Baselime
ratelimittoken bucket, sliding windowmemoryUpstash, Postgres
aicompletion, embedding, streamingcontract plus fakeOpenAI, Anthropic, Bedrock, Ollama

v1 implements 7 contracts and ships fakes for all 16. The rest publish as contracts with a fake. You can write application code against them today, and nothing gets rewritten when a real driver lands.

That split is on purpose. A published contract is a promise, and a contract changed in v1.1 breaks every third-party driver written against it. Ship few, and ship them slowly.


Capability Negotiation

The hard part of a driver system is that drivers differ:

  • Supabase has no client-side transactions
  • Clerk has organizations and Supabase doesn't
  • Auth.js has no API token issuance

There are 2 bad answers:

  • a lowest-common-denominator contract nobody can ship on
  • a maximal contract where half the methods throw at runtime

Avelon's answer: a driver declares its capabilities as literal types, and the facade narrows to what the configured driver can actually do. Verified against tsc in strict mode.

type Database<D extends DatabaseDriver> = DatabaseSurface<D> &
  (D['capabilities']['transactions'] extends true ? TransactionSurface : object) &
  (D['capabilities']['rowSecurity'] extends true ? RowSecuritySurface : object)

With @avelonjs/supabase configured:

const database = createSupabaseDatabase()
await database.transaction(async (tx) => { ... })
//             ^^^^^^^^^^^ Property 'transaction' does not exist on type 'SupabaseDatabase'.
// The driver declares transactions: false. Use database.rpc() instead.

Swap the driver to createPostgresDatabase() and the same line compiles. Nothing else in the application changes.

The DB facade returns the base DatabaseDriver contract. Code that needs a capability method keeps a reference to the configured driver, as 05-database.md shows.

Auth works the same way:

const identity = createSupabaseIdentity()(cookies)
await identity.organizations()
//             ^^^^^^^^^^^^^ Property 'organizations' does not exist on type 'SupabaseIdentity'.

Three Enforcement Layers

Configuration can be environment-driven, and types can't see environment variables. So narrowing alone isn't enough.

  1. Compile time. Facade narrowing. Covers a driver chosen statically in avelon.config.ts, which is the overwhelming majority.
  2. Boot time. reeve doctor prints the capability matrix for the config it resolves. Run it in each environment and compare, so "it worked locally" has a named cause.
  3. Runtime. supports(driver, 'transactions'), typed against the capability key set so a typo is a compile error.

NotSupportedError Is Banned

If a driver can't do something, the method is absent from the type. A runtime "this driver does not support that" is a design failure. If you want to throw one, the capability map is wrong. Escalate.


Contract Rules

Every contract, without exception:

  • Is an interface, never a class. Drivers compose, they don't inherit
  • Declares capabilities as a literal-typed const
  • Exposes raw() returning the vendor client, typed to that vendor
  • Ships a fake that passes the same conformance suite
  • Supports named instances with one default
  • Normalizes errors into the framework taxonomy

Named instances look like this:

  • Storage.disk('archive')
  • Mail.mailer('marketing')
  • DB.connection('analytics')

Error Normalization

This is the one people get wrong, and it quietly destroys the abstraction.

Say a unique constraint violation arrives as a Supabase error with code 23505. Application code then catches 23505, and the vendor has leaked through the error channel while the happy path looks clean. Swapping drivers then breaks every catch block in the codebase.

Every driver maps into a fixed taxonomy:

NotFound  Conflict  Unauthenticated  Forbidden  RateLimited  Invalid  Unavailable  DriverFault

Each one carries the original as .cause.

Conformance tests assert the mapping by provoking real failures against a live instance. They don't check that a mock returns what the driver author expected.


Writing a Driver

reeve make:driver storage r2

This scaffolds a package with:

  • every contract method stubbed to throw <method> is unimplemented
  • a capability block with everything false
  • a wired-up conformance suite
  • a README in the house style

The full authoring and certification path is in 15-driver-authoring.md.

@avelonjs/conformance

The load-bearing artifact: a shared test suite per contract. A driver either passes a capability's tests or declares that capability false. Both directions are checked:

  • Declares true and fails the tests: build error
  • Declares false but implements the method: build error, because someone will call it
  • Declares true and passes, but the error taxonomy has an unmapped member: build error

Fakes run the same suite, so a fake can't drift from the contract. That's what makes Mail.fake() trustworthy in a test instead of decorative.

A third-party driver that passes conformance is listable. That one mechanism is the difference between an ecosystem and a pile of half-working packages. It costs roughly an afternoon per contract to write.


Configuration

// avelon.config.ts
import { defineConfig } from '@avelonjs/core'
import { createResendMail } from '@avelonjs/resend'
import {
  createSupabaseDatabase,
  createSupabaseIdentity,
  createSupabaseQueue,
  createSupabaseStorage,
} from '@avelonjs/supabase'

export default defineConfig({
  name: 'my-app',
  drivers: {
    database: createSupabaseDatabase({
      restUrl: process.env.SUPABASE_REST_URL,
      serviceRoleKey: process.env.SUPABASE_SERVICE_ROLE_KEY,
    }),
    identity: createSupabaseIdentity({
      authUrl: process.env.SUPABASE_AUTH_URL,
      apiKey: process.env.SUPABASE_ANON_KEY,
    }),
    storage: {
      default: 'uploads',
      disks: {
        uploads: createSupabaseStorage({ instance: 'uploads', url: process.env.DATABASE_URL }),
      },
    },
    queue: createSupabaseQueue({ url: process.env.DATABASE_URL }),
    mail: createResendMail({
      apiKey: process.env.RESEND_API_KEY,
      defaultFrom: 'noreply@example.com',
    }),
  },
} as const)

Imports are explicit, with no auto-discovery. The config is tree-shakeable and statically typed, and the as const is what makes capability narrowing work.

A second argument to defineConfig merges per-environment overrides on top.

Social sign-in and API tokens have no defineConfig key. Create those drivers in avelon.config.ts and export them, for example:

  • createSupabaseSocial()
  • createSupabaseTokens()

reeve config:show and reeve capabilities print what this file configures.


The Escape Hatch

Every driver exposes raw(). On the driver's own type it returns the vendor handle. Through the DB facade it's unknown.

const sql = createPostgresDatabase().raw() // Bun's SQL client

Without this the abstraction is a prison and people reject it, correctly. Left unguarded, vendor calls spread and the abstraction becomes decorative.

So Bailiff scopes it. raw() is allowed:

  • in app/Drivers/
  • in avelon.config.ts
  • behind an explicit disable comment stating why

Both leave a searchable trail, which is all you actually need.


Fakes

Every contract ships a fake in @avelonjs/conformance, and it's not an afterthought. Wire fakes with the same defineConfig call a real app uses:

import { defineConfig } from '@avelonjs/core'
import { FakeDatabase, FakeMail, FakeQueue, FakeStorage } from '@avelonjs/conformance'

const mail = new FakeMail()
defineConfig({
  drivers: {
    database: new FakeDatabase(),
    mail,
    queue: new FakeQueue(),
    storage: new FakeStorage(),
  },
})

// ...run the code under test, then:
expect(mail.sent.map((message) => message.to)).toContain('ada@example.com')
  • assay({ kernel, routes }).actingAs(user) sends requests as an actor
  • FakeDatabase serves the tables the conformance suites use, such as users and posts

Fakes pass the same conformance suite as real drivers, so a test that passes against a fake means something.