Docs

Guide 03

Architecture

03. Architecture

This page covers the Avelon packages, the adapter contract, where files live in an app, and how a request moves from the router to a controller.


Packages

@avelonjs/core          contracts, config resolution, service registry, events, errands,
                      validation, console, logging, error taxonomy, testing primitives.
                      Zero imports from next/*. Zero Bun-only APIs.

@avelonjs/orm           Scrivener. Models, relations, scopes, casts, lifecycle hooks, and the
                      query IR builder. Depends on the database contract, never on a driver.

@avelonjs/supabase      Driver package. Implements database, identity, social, tokens, storage,
                      queue. Compiles wards to RLS.

@avelonjs/postgres      Driver package. Implements database with transactions and deep relations.

@avelonjs/neon          Driver package. Implements database, identity, social, tokens, S3
                      storage, queue. Neon Auth plus S3 as the Supabase-shaped stack.

@avelonjs/resend        Driver package. Implements mail.

@avelonjs/next          Adapter. Route codegen, server action dispatch, page wrapper, middleware
                      bridge, view() to RSC.

@avelonjs/bailiff       ESLint plugin plus CLI wrapper. Architecture rules.

@avelonjs/conformance   Shared test suites, one per contract. Drivers run these to prove themselves.

@avelonjs/cli           reeve. TUI, generators, stubs. Discovers adapter and driver stubs at runtime.

create-avelon         Named scaffolder. Not in this repository.

Dependencies run one way, and Bailiff enforces it:

  • core knows nothing about orm
  • orm knows nothing about drivers
  • drivers know nothing about the adapter
  • the adapter knows nothing about a specific driver

The Adapter Contract

It's small on purpose. The bigger it gets, the less true "framework agnostic" becomes.

export interface Adapter {
  readonly name: string
  readonly capabilities: {
    fileSystemRouting: boolean
    serverActions: boolean
    streaming: boolean
    edgeMiddleware: boolean
  }

  /** Codegen for file-routing adapters, runtime registration for others. */
  mount(manifest: RouteManifest, options: MountOptions): Promise<MountResult>

  toRequest(native: unknown): Promise<HttpRequest>
  toResponse(result: ActionResult | ViewResult): Promise<unknown>
}

capabilities lets the CLI and codegen pick the right strategy for the adapter, so they don't emit code that fails at runtime.

Server Actions

Revised after M0 (D26). serverActions selects the write transport. It doesn't decide whether a write route exists:

  • serverActions: true serves Route.post() as a generated server action
  • serverActions: false mounts an ordinary POST route for the same controller

The M0 Hono spike served both patterns from one unchanged controller.

Views Are Opaque

ViewResult.view is a reference core never inspects. The configured adapter accepts it and renders it:

  • under Next it's an RSC component import
  • under another adapter it's whatever that adapter's renderer resolves

A controller returning view(Show, props) is portable because nothing outside the adapter ever opens Show.

Adapters Delegate to the Kernel

These live in core's dispatch pipeline:

  • middleware
  • route-model binding
  • validation error shaping
  • exception mapping

mount() wires routes to that pipeline and doesn't reimplement it. An adapter is a translation layer at exactly 3 seams:

  • mount
  • toRequest
  • toResponse

Directory Structure

avelon-app/
├── reeve                            # CLI entry, bun shebang
├── app/
│   ├── (web)/                       # GENERATED router. Never hand-edited.
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── posts/
│   │       ├── page.tsx
│   │       ├── create/page.tsx
│   │       └── [post]/
│   │           ├── page.tsx
│   │           └── edit/page.tsx
│   ├── (api)/                       # GENERATED, only for .api() routes
│   ├── Actions/                     # single-purpose use cases
│   ├── Commands/                    # console commands
│   ├── Drivers/                     # your own thin vendor adapters, the only place raw() lives
│   ├── Errands/                     # background work
│   ├── Events/
│   ├── Http/
│   │   ├── Controllers/
│   │   ├── Middleware/
│   │   ├── Requests/                # Zod input contracts
│   │   └── Views/                   # serializers for the RSC boundary
│   ├── Listeners/
│   ├── Models/
│   ├── Notices/                     # mail and notifications
│   ├── Observers/
│   ├── Policies/                    # may this actor perform this action
│   ├── Providers/
│   └── Wards/                       # which rows may this actor reach
├── config/                          # typed, one file per concern
├── database/
│   ├── migrations/                  # driver-owned format, one history
│   ├── seeds/
│   ├── factories/
│   └── types.ts                     # GENERATED from the live schema
├── resources/
│   ├── css/app.css
│   └── views/
│       ├── components/
│       ├── layouts/
│       └── posts/
├── routes/
│   ├── web.ts
│   ├── api.ts
│   ├── console.ts
│   └── channels.ts
├── storage/logs/
├── tests/{Feature,Unit}/
├── public/
├── middleware.ts                    # adapter entry, delegates to the kernel
├── avelon.config.ts                 # adapter and driver wiring
├── vercel.json
└── package.json

Why Colocation Inside app/ Works

Next only treats these files as routable:

  • page
  • layout
  • route
  • loading
  • error
  • template
  • default

Everything else inside app/ is documented colocation. app/Models/Post.ts isn't a route. app/Models/ never becomes a URL segment, because it has no page.tsx.

Route groups keep all generated files in 2 entries. The directory reads as the application tree with 2 extra folders for the generated router.

This is assumption 1 of the M0 spike. Everything structural depends on it.


Routing

routes/web.ts is the source of truth, and reeve route:sync generates the router from it. Generated files have no logic, only a banner, imports, and exports. That keeps adapter upgrades cheap.

import { Route } from '@avelonjs/next'
import { DashboardController } from '@/app/Http/Controllers/DashboardController'
import { HomeController } from '@/app/Http/Controllers/HomeController'
import { PostController } from '@/app/Http/Controllers/PostController'
import { UserController } from '@/app/Http/Controllers/UserController'

Route.get('/', HomeController, 'index').name('home')

Route.middleware('auth').group(() => {
  Route.resource('posts', PostController).bind('post', 'Post')
  Route.get('/dashboard', DashboardController).name('dashboard')
})

Route.prefix('admin').group(() => {
  Route.middleware('auth', 'can:admin').group(() => {
    Route.resource('users', UserController).only('index', 'show')
  })
})
  • Route.resource() expands to 7 routes: index, create, store, show, edit, update, destroy
  • .bind('post', 'Post') is route-model binding
  • .api() also generates a JSON route handler
  • route('posts.show', id) resolves from a generated manifest, so it works in server and client components without importing controllers

Route-Model Binding

When the kernel's resolveBinding option loads the model, the controller gets it as a second argument. A miss is a 404 before your code runs.

Bind the model name as a string, since next build minifies class names.

Sync

Codegen is one-way and destructive:

  • the router directory is wiped and rewritten on every sync
  • 2 GET routes resolving to the same file is a hard error at sync time

An app's generate script runs sync before dev, build, check, and test. In the SaaS starter, the pre-commit hook runs it too, once bun run setup enables the hooks.

Sync doesn't watch routes/, so run bun run generate again after you edit routes/web.ts with the dev server running.


Request Lifecycle

Read

browser
  -> middleware.ts
       -> kernel: global middleware, then route middleware from the manifest
  -> app/(web)/posts/[post]/page.tsx        (generated, no logic)
       -> page(PostController, 'show', '/posts/{post}')
            -> HttpRequest.fromPage()
            -> route-model binding: Post.findOrFail(params.post)
            -> PostController.show(request, post)
                 -> Gate.authorize('view', post)
                 -> view(Show, { post: PostView.make(post) })
  -> RSC render

Write

<Form action="posts.update" params={{ post: id }}>
  -> generated server action posts_update(formData)
       -> dispatch(PostController, 'update', '/posts/{post}', formData)
            -> HttpRequest.fromFormData()      (_method spoofing, param extraction)
            -> middleware chain
            -> route-model binding
            -> PostController.update(request, post)
                 -> Gate.authorize('update', post)
                 -> UpdatePostRequest.validate(request)     throws Invalid
                 -> post.update(data)                       fires model events
                 -> Events.dispatch(new PostUpdated(post.id))
                 -> redirect(route('posts.show', post.id))
  -> Invalid caught -> { ok: false, errors } -> useActionState -> field errors
  -> success -> redirect propagates -> navigation

Exceptions

Exceptions map in one place, mapKernelException:

ExceptionResult
NotFound404
Unauthenticatedredirect to /login
Forbidden403
Conflict409
RateLimited429
Unavailable503
Invalidback to the form as a 422 with per-field errors

Controllers

export class PostController extends Controller {
  async index() {
    const posts = await Post.published().with('author').latest().paginate(15)
    return view(Index, { posts: PostView.collection(posts) })
  }

  async show(request: HttpRequest, post: Post) {
    await this.authorize('view', post)
    return view(Show, { post: PostView.make(post) })
  }

  async store(request: HttpRequest) {
    await this.authorize('create', Post)
    const data = await StorePostRequest.validate(request)

    const post = await Post.create({ ...data, user_id: (await this.userOrFail()).id })

    await Events.dispatch(new PostPublished(post.id, post.title))
    return redirect(route('posts.show', post.id))
  }
}

Controllers stay thin. Anything past a handful of statements moves to app/Actions/, and Bailiff warns when it doesn't.

Model instances are class instances, so they can't cross into client components. app/Http/Views/ holds the serializers. Passing a raw model to view() is a Bailiff error instead of a runtime surprise.