# Zerotal documentation The full guide from https://zerotal.dev/docs, one page after another. Release notes are left out; they are at https://zerotal.dev/docs/changelog.md. --- Source: https://zerotal.dev/docs/about # About Zerotal Zerotal is a **Bun-native, full-stack TypeScript web framework** for building full-stack apps — from classic server-rendered pages to reactive live components and Inertia.js SPAs. This page is the **whole framework on one screen**: read it top to bottom and you'll know what Zerotal is, how it's put together, and how to do the everyday things — routing, models, validation, auth, background jobs, and picking a frontend — with copy-pasteable code. Every section links to the deep-dive doc if you want more, but you shouldn't _need_ to open them to get productive. When you're ready to scaffold, skip to [Install and run](#install-and-run). ## The one-paragraph version You write plain TypeScript classes — controllers, models, jobs, providers — and drop them into convention-named folders (`app/controllers/`, `app/models/`, …). At boot, Zerotal discovers them, wires their dependencies through a typed IoC container, and runs everything on [Bun](https://bun.sh). There is **no build step**: Bun executes `.ts` files directly, so what you write is what runs. If you've used a classic full-stack MVC framework, the mental model transfers almost one-to-one — facades, service providers, Active Record models, FormRequests, queues, policies — but the language is TypeScript and the runtime is Bun. ## Who Zerotal is for - **Full-stack MVC developers** who want the same ergonomics with end-to-end type safety. - **TypeScript teams** who want a batteries-included backend without stitching a dozen libraries together. - **Full-stack builders** who want to pick their frontend style per project — server-rendered JSX, reactive server components, or a React/Vue SPA — without changing frameworks. ## Four ideas hold it together Everything else is detail. Internalize these four and the rest reads as variations on a theme. ### 1. Bun-native, source-only Zerotal runs **only on Bun** (≥ 1.3.14) and leans on Bun's APIs throughout — `Bun.sql` for the database, `Bun.CryptoHasher` for hashing, `Bun.build` for bundling. Because Bun runs and type-strips TypeScript natively, packages ship as **`.ts` source with no compiled `dist/`**. You always read real source and get accurate types; there's nothing to compile and no source-map indirection. > **Note** — Node.js is not supported. Importing `@zerotal/*` from a plain Node > process will fail — it expects Bun's runtime APIs. ### 2. Convention over configuration Drop a file in the right folder and it's wired up. Models in `app/models/`, providers in `app/providers/`, policies, observers, and event listeners are all **auto-discovered at boot** — no manual registration. Table names, route model bindings, and more are derived by convention (`Post` → the `posts` table). You edit `bootstrap/app.ts` only when you need to control ordering. ### 3. The container wires everything A typed **IoC (inversion-of-control) container** builds your objects for you. You declare _how_ to build something once (usually in a provider), then ask for it by type and the container resolves its dependencies. Controllers, services, and framework internals are all resolved this way, which is what makes them easy to swap and test. ### 4. Providers are the on-switches A **service provider** is a feature's setup script. Registering a provider in `bootstrap/providers.ts` is what "turns on" a package — it binds services into the container, registers middleware, subscribes to events, and cleans up on shutdown, each in a defined [lifecycle](/docs/lifecycle) phase (`onRegister` → `onBooting` → `onBooted` → `onStopping`). Want Inertia? Add `InertiaProvider`. Want reactive SSR? Add `FlowProvider`. The provider list is the feature manifest for your app. ## Install and run ```bash # in your project's parent directory bun create zerotal my-app # choose: API, Flow, React, Vue, or Minimal cd my-app bun zt migrate # create the database schema (API template) bun zt dev # dev server + hot reload at http://localhost:3000 ``` The scaffolder writes a fresh `APP_KEY` into `.env` and installs dependencies. Pick a template at the prompt: - **API** — JSON REST API (core + ORM + auth + validation + testing). The default. - **Flow** — server-driven reactive UI (see [Flow](#flow-reactive-ssr)). - **React** / **Vue** — Inertia SPA (see [Inertia](#inertia-react-vue-spa)). - **Minimal** — one page with JSX views on the bare framework. There's **no build step**: `bun zt dev` starts the server, `bun test` runs the suite, `bun run typecheck` type-checks. More in [Getting Started](/docs/getting-started). ## The shape of an app The folders are conventions the framework reads, not wiring you maintain: ``` # my-app/ my-app/ ├── app/ │ ├── controllers/ # HTTP controllers (plain classes) │ ├── models/ # ORM models — auto-discovered │ ├── middleware/ # Custom middleware │ ├── policies/ # Authorization policies │ ├── providers/ # Your service providers — auto-discovered │ ├── jobs/ # Queue jobs │ ├── mail/ # Mailable classes │ └── flow/ # Reactive SSR components (*.tsx) ├── bootstrap/ │ ├── app.ts # Builds the Application (providers + routing) │ └── providers.ts # Which packages are active ├── config/ # Typed config files — auto-loaded ├── database/ │ └── migrations/ # Schema-builder migration classes ├── routes/ │ └── index.ts # Route definitions ├── public/ # Static assets ├── storage/ # Uploads, logs, SQLite file ├── zt.ts # The CLI entry point — do not edit └── .env ``` `zt.ts` is the entry point for **everything** — `bun zt serve`, `migrate`, `test`, and every `make:*` generator run through it. It boots `bootstrap/app.ts`: ```ts fragment // bootstrap/app.ts import { Application } from "zerotal"; import { Handler } from "../app/exceptions/Handler.ts"; import { User } from "../app/models/User.ts"; import providers from "./providers.ts"; export default Application.create({ providers }) .withExceptionHandler(Handler) .withUserResolver((id) => User.find(id)); ``` See [Directory Structure](/docs/structure) for the full tour. ## How a request flows Most of what you write plugs into one of these steps: 1. **Boot** — `bun zt serve` loads `bootstrap/app.ts`, registers providers, auto-discovers `app/` and `config/`, and loads `routes/`. 2. **Match** — the request is matched to a route → a controller action or a closure. 3. **Pipeline** — it passes through the [middleware](/docs/middleware) stack (session, auth, CSRF, …) before reaching your handler. 4. **Handle** — your controller runs. It receives an [`HttpContext`](/docs/context) for request input and the response, and resolves dependencies from the container. 5. **Respond** — you return JSON, a [view](/docs/view), a [Flow](#flow-reactive-ssr) page, an [Inertia](#inertia-react-vue-spa) page, or a redirect. Read [Request Lifecycle](/docs/lifecycle) for the exact sequence. ## Routing Routes are registered by calling static `Router` methods at module load — map a path to a controller + action, or to an inline closure: ```ts fragment // routes/index.ts import { Router, view, type HttpContext } from "zerotal"; import HomeController from "../app/controllers/HomeController.ts"; import PostController from "../app/controllers/PostController.ts"; import AdminController from "../app/controllers/AdminController.ts"; import { CounterPage } from "../app/flow/CounterPage.tsx"; // Controller + action Router.get("/", HomeController, "index").name("home"); // Inline closure handler Router.get("/health", (http: HttpContext) => http.json({ ok: true })); // RESTful resource (index/create/store/show/edit/update/destroy) Router.resource("posts", PostController); // Reactive SSR page (Flow) Router.flow("/counter", CounterPage); // Route groups with shared prefix + middleware Router.group({ prefix: "/admin", middleware: ["auth", "admin"] }, () => { Router.get("/dashboard", AdminController, "index"); }); ``` Apps that prefer file-based routing add `.fileBasedRouting(basePath("app/pages"))` to the app builder. Full details in [Routing](/docs/routing). ## Controllers Controllers are plain classes; the action receives the request `HttpContext` and dependencies resolve from the container: ```ts fragment // app/controllers/PostController.ts import type { HttpContext } from "zerotal"; import Post from "../models/Post.ts"; import { StorePostRequest } from "../requests/StorePostRequest.ts"; export default class PostController { async index(ctx: HttpContext) { const posts = await Post.query() .where("published", true) .with(["author", "tags"]) .orderBy("created_at", "desc") .paginate(1, 20); // (page, perPage) return ctx.json(posts); } async store(ctx: HttpContext) { const data = await StorePostRequest.validate(); // reads the current HttpContext const post = await Post.create(data); return ctx.json(post, 201); } } ``` Read route params and model bindings from `ctx.params`; type them with the generic, e.g. `ctx: HttpContext<{ post: Post }>`. More in [Controllers](/docs/controllers) and [Context](/docs/context). ## Models, queries, and migrations Active Record–style models backed by `Bun.sql`. Columns and relationships are decorators; the table name is derived by convention (so `@table` is optional): ```ts fragment // app/models/Post.ts import { Model, table, column, hasMany, belongsTo } from "@zerotal/orm"; import type { Carbon } from "@zerotal/core/carbon"; @table("posts") export default class Post extends Model { @column() declare id: number; @column() declare title: string; @column("text") declare body: string; @column("boolean") declare published: boolean; @column("datetime") declare createdAt: Carbon; @hasMany(() => Comment) declare comments: Comment[]; @belongsTo(() => User) declare author: User; // Reusable query scope static published = Model.scope((q) => q.where("published", true)); } ``` The fluent query builder and relationship loading: ```ts fragment // in a controller or service const posts = await Post.query() .withScopes((s) => s.published()) .with(["author", "comments"]) .orderBy("created_at", "desc") .limit(20) .get(); const post = await Post.find(1); await post.load(["comments"]); const created = await Post.create({ title: "Hello", body: "..." }); created.fill({ published: true }); await created.save(); ``` Schema changes are TypeScript migration classes under `database/migrations/`, run with `bun zt migrate`: ```ts // database/migrations/001_create_posts_table.ts import { Migration, Schema } from "@zerotal/orm"; export default class CreatePostsTable extends Migration { async up() { await Schema.create("posts", (table) => { table.increments("id"); table.integer("user_id").index(); table.string("title"); table.text("body"); table.boolean("published").default(false); table.timestamps(); }); } async down() { await Schema.drop("posts"); } } ``` Go deeper: [ORM](/docs/orm), [Query Builder](/docs/query-builder), [Relationships](/docs/orm/relationships), [Migrations](/docs/migrations). ## Validation Validation is class-based via `FormRequest` with a fluent `RuleBuilder`, so a controller trusts its data by the time it runs: ```ts // app/requests/StorePostRequest.ts import { FormRequest, type RuleBuilder } from "@zerotal/validator"; export class StorePostRequest extends FormRequest { // Don't annotate the return type — it's inferred, which types the result of validate() rules(r: RuleBuilder) { return { title: r.string().min(3).max(255), body: r.string().min(10), tags: r.array(r.string()).optional(), }; } } ``` ```ts fragment // in a controller — reads the current HttpContext, returns typed data, // throws a 422 (JSON) or a redirect-back on failure. const data = await StorePostRequest.validate(); ``` More rules and patterns in [Validation](/docs/validator). ## Authentication and authorization Session auth, bearer tokens, and policy-based authorization ship together: ```ts fragment // in a controller / service import { Auth, Gate, createToken } from "@zerotal/auth"; // Login await Auth.attempt({ email, password }); // Current user (guest-safe; undefined when not logged in) const user = Auth.userOrNull(); if (!user) return ctx.redirect("/login"); // Bearer token (API) — `plaintext` is shown once const { plaintext, row } = await createToken({ tokenableId: user.id, name: "mobile-app" }); // Authorization is policy-based Gate.authorize("update", post); // throws 403 unless the policy allows it // Gate.via(PostPolicy).allows("update", post); // check without throwing ``` Password reset, email verification, roles, 2FA (TOTP/WebAuthn), and OAuth are all included. See [Authentication](/docs/authentication), [Authorization](/docs/authorization), and [Two-Factor Auth](/docs/roles-and-2fa). ## Pick your frontend Zerotal ships three rendering models; choose per route, or mix them in one app. ### Server-rendered JSX views Plain server-side JSX — the simplest option for content pages. See [Views](/docs/view). ### Flow — reactive SSR Flow is Zerotal's reactive layer. `Component` classes run **entirely on the server**; you write plain JSX and bind handlers directly. On each interaction the server re-runs the method, re-renders, and streams only the changed HTML back, which Alpine.js morphs into the DOM — no client state management, no separate API. ```tsx import { Component, expose, validate } from "@zerotal/flow"; export class CounterPage extends Component { @expose count = 0; @expose @validate((rule) => rule.required().min(2)) name = ""; @expose increment() { this.count++; } override async render() { return (

Count: {this.count}

{/* Server action — round-trips and re-renders */} {/* Client expression — instant, no round-trip */}
); } } ``` A named method reference (`onClick={this.increment}`) is a **server action** — it round-trips. An arrow function (`onClick={() => this.count--}`) is a **client expression** — instant, no round-trip. Register `FlowProvider`, route with `Router.flow("/counter", CounterPage)`, and read [Flow](/docs/flow) for the full decorator and directive set. ### Inertia — React / Vue SPA Build a React or Vue SPA with no separate API layer. Controllers return page responses; the Inertia client renders the matching component: ```ts fragment // app/controllers/DashboardController.ts import { inertia } from "@zerotal/inertia"; import { Post } from "../models/Post.ts"; export class DashboardController { async index(): Promise { const posts = await Post.query().latest().limit(5).get(); return inertia("Dashboard", { posts }); // → resources/js/pages/Dashboard.tsx } } ``` ```tsx fragment // resources/js/pages/Dashboard.tsx (React) import { Link } from "@inertiajs/react"; export default function Dashboard({ posts }: { posts: { id: number; title: string }[] }) { return ( ); } ``` Register `InertiaProvider` and you get full Inertia v3 support — shared props, partial reloads, deferred props, SSR, and precognition. See [Inertia](/docs/inertia). > **Tip** — Server views for static content, **Flow** when you want rich > interactivity but want to stay in TypeScript on the server, and **Inertia** when > your team already lives in React/Vue. ## Background work: queue and jobs Push slow work off the request. Jobs serialize to a plain payload so they survive the queue: ```ts fragment // app/jobs/SendWelcomeEmail.ts import { Job, JobRegistry } from "@zerotal/queue"; import { User } from "../models/User.ts"; import { WelcomeNotification } from "../notifications/WelcomeNotification.ts"; export class SendWelcomeEmail extends Job { override readonly maxAttempts = 3; override readonly retryDelay = 5000; // ms constructor(public readonly userId: number) { super(); } payload(): Record { return { userId: this.userId }; } static fromPayload(p: Record) { return new SendWelcomeEmail(p.userId as number); } async handle() { const user = await User.find(this.userId); await user.notify(new WelcomeNotification()); } } JobRegistry.register(SendWelcomeEmail); ``` ```ts fragment // dispatch from anywhere import { Queue, Bus } from "@zerotal/queue"; await Queue.dispatch(new SendWelcomeEmail(user.id)); // Batch — run in parallel, then a completion job await Bus.batch([new ProcessImage(id), new GenerateThumbnail(id)]) .then(new NotifyUploadComplete(id)) .dispatch(); ``` Run a worker with `bun zt queue:work`. There's also a [scheduler](/docs/scheduler) for cron-style tasks. More in [Queue](/docs/queue). ## Cache ```ts fragment // in a controller or service import { Cache } from "@zerotal/cache"; const posts = await Cache.remember("posts.recent", 60, () => Post.query().orderBy("created_at", "desc").limit(10).get(), ); await Cache.set("key", value, 300); await Cache.forget("key"); // Tag-based invalidation await Cache.tags(["posts"]).put("post:1", post, 600); await Cache.tags(["posts"]).flush(); ``` In-memory and Redis drivers, plus idempotency helpers. See [Cache](/docs/cache). ## Notifications and mail One `Notification` class fans out across channels — mail, database, broadcast, Slack, SMS: ```ts fragment // app/notifications/InvoicePaid.ts import { Notification, MailMessage } from "@zerotal/notifications"; export class InvoicePaid extends Notification { constructor(private invoice: Invoice) { super(); } via(user: User) { return ["mail", "database"]; } toMail(user: User) { return new MailMessage() .subject("Invoice paid") .line(`Your invoice #${this.invoice.id} has been paid.`); } } ``` ```ts fragment // The User model mixes in Notifiable, which provides .notify() await user.notify(new InvoicePaid(invoice)); ``` See [Notifications](/docs/notifications) (mail lives here too). ## Configuration and environment Config lives in typed files under `config/` (auto-loaded), reading from `.env`: ```ini # .env APP_ENV=development APP_KEY=base64:… # signs Flow snapshots, encrypts sessions DATABASE_URL=./storage/db.sqlite # or postgres://… / mysql://… SESSION_DRIVER=cookie # or redis ``` | Variable | Required | Description | | ---------------- | -------- | ------------------------------------------------------------ | | `APP_KEY` | Yes | 32-byte secret — signs Flow snapshots, encrypts sessions | | `DATABASE_URL` | Yes | `postgres://…`, `mysql://…`, or `sqlite:./storage/db.sqlite` | | `APP_ENV` | No | `development` (default) or `production` | | `APP_URL` | No | Full base URL (used in mail links, etc.) | | `SESSION_DRIVER` | No | `cookie` (default) or `redis` | | `MAIL_DRIVER` | No | `smtp`, `resend`, or `log` | | `PORT` | No | HTTP server port (default `3000`) | Generate or rotate the key with `bun zt key:generate`. Full system in [Configuration](/docs/config-system). ## Testing First-class HTTP, database, and fake helpers: ```ts fragment // tests/posts.test.ts import { createTestApp, Factory, assertDatabaseHas } from "@zerotal/testing"; import { NotificationFake } from "@zerotal/notifications"; import app from "../bootstrap/app.ts"; import { User } from "../app/models/User.ts"; const UserFactory = Factory.define(User, (f) => ({ name: f.string(10), email: f.email(), password: "password", })); const testApp = await createTestApp(() => app); const user = await UserFactory.create(); const res = await testApp.actingAs(user).get("/posts"); res.assertOk(); // Fake notifications (mail is a channel) const fake = NotificationFake.install(); await testApp.post("/register", { email: "alice@example.com" }); await assertDatabaseHas("users", { email: "alice@example.com" }); fake.assertSentTo(user, WelcomeNotification); fake.restore(); await testApp.close(); ``` Run with `bun test`. More in [Testing](/docs/testing). ## The zt CLI Everything runs through `zt.ts`. The essentials: ```bash # in your project root bun zt make:model Post --migration # model + migration bun zt make:controller PostController bun zt make:provider AppServiceProvider bun zt make:job SendWelcomeEmail bun zt make:page Dashboard # Inertia page bun zt migrate # run pending migrations bun zt migrate:rollback # roll back last batch bun zt migrate:fresh # drop all + re-migrate bun zt key:generate # fresh APP_KEY bun zt queue:work # start the queue worker bun zt dev # dev server, hot reload (also `bun run dev`) bun zt list # every available command ``` More in [Commands](/docs/commands). ## What's in the box Zerotal is a monorepo of composable `@zerotal/*` packages — register only what you need: | Area | Packages / features | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **HTTP core** | Container, router, middleware, events, config, facades, JSX views (`@zerotal/core`) | | **Data** | ORM, migrations, query builder, [validation](/docs/validator) | | **Auth & security** | [Sessions](/docs/session), [auth](/docs/authentication), tokens, [roles and policies](/docs/authorization), [2FA](/docs/roles-and-2fa), [passkeys](/docs/authentication#passkeys), OAuth, [CSRF](/docs/csrf) | | **Frontend** | Flow, flow-ui component library, Inertia | | **Services** | [Cache](/docs/cache), [queue](/docs/queue), [scheduler](/docs/scheduler), [storage](/docs/storage), [broadcasting](/docs/broadcasting), [notifications & mail](/docs/notifications) | | **Cross-cutting** | [Telemetry](/docs/telemetry), [HTTP client](/docs/client), [i18n](/docs/i18n), [tenancy](/docs/tenancy), [audit](/docs/audit), [monitor](/docs/monitor) | | **Tooling** | Admin panel, devtools, [testing](/docs/testing) helpers, `create-zerotal` scaffolder | The [README](https://github.com/zerotaldev/zerotal#packages) has a package-by-package table with links. ## Working in the codebase - **The `zt` CLI is your control panel.** `bun zt list` shows everything — scaffolding, migrations, the dev server, the worker, and tests all run through it. - **No build, ever.** `bun zt dev` / `bun test` / `bun run typecheck`. No compile step to remember. - **Starters are the fastest way in.** `bun create zerotal my-app` scaffolds a working app from one of six starters — `api`, `admin`, `flow`, `react`, `vue`, or `minimal`. Read the generated code alongside the docs. - **Conventions are documented, not magic.** When something "just works" (a model you never registered, a policy suddenly enforced), [Conventions](/docs/conventions) explains exactly what the framework discovered and why. ## Next steps - [Getting Started](/docs/getting-started) — scaffold and run your first app. - [Directory Structure](/docs/structure) & [Conventions](/docs/conventions) — where things go and why they wire up. - [Request Lifecycle](/docs/lifecycle), [Container](/docs/container), [Providers](/docs/providers) — how boot and wiring work. - [ORM](/docs/orm) & [Query Builder](/docs/query-builder) — the data layer in depth. - [Flow](/docs/flow) / [Inertia](/docs/inertia) — pick and learn your frontend model. --- Source: https://zerotal.dev/docs/upgrade # Upgrade Guide This guide explains how to move a Zerotal app to a newer release. For the list of what changed in each version, see the [Release Notes](/docs/changelog). ## Versioning Zerotal's `@zerotal/*` packages share one version line, and what each number means is set by how much the framework still moves in a year rather than by the letter of semver: - **Patch** (`x.y.Z`) — anything that does not break. Fixes, and features too. Safe to take at any time. - **Minor** (`x.Y.z`) — a breaking change. Always labelled **BREAKING** in the [Release Notes](/docs/changelog), with the reason and the migration steps, and given its own section on this page. - **Major** (`X.y.z`) — an annual consolidation, cut each July. The next is 2.0, in July 2027. Why not strict semver: a framework this young corrects itself often, and under strict semver every correction is a major. A version line that reaches 9.0 in its first year tells a reader nothing about how much has changed — only that the project is willing to break things, which the release notes already say far more precisely. Keeping the major for a yearly line in the sand leaves it meaning something, and puts the work where it is useful: reading the notes for each minor. > **Warning** — **a caret range crosses a minor.** `"zerotal": "^1.10.0"` will > install 1.11.0, and its breaking change, without asking. Read the notes for every > minor you cross, or pin with a tilde (`~1.10.0`) and cross them deliberately. > **Warning** — **a tilde still crosses a patch**, and under this scheme a patch carries > features. `~1.13.2` means `>=1.13.2 <1.14.0`, so it takes 1.13.3 without asking. That is > the right default for most apps and it is weaker protection than the same range gives > under strict semver, where a patch is only ever a bug fix. If you need the version to > hold exactly where you put it — a release you have certified, a machine you cannot > re-test quickly — pin the exact version with no range operator at all. > **Note** — `bun create zerotal` writes a tilde range into new apps for this reason. An app scaffolded earlier has a caret: change `^` to `~` in its `package.json` to get the same protection. > **Warning** — always upgrade the `@zerotal/*` packages together. Mixing versions across core, ORM, and feature packages leads to type and runtime mismatches. ## Upgrade steps 1. **Bump the packages.** Update every `@zerotal/*` dependency to the target version, then reinstall: ```bash bun update # within the ranges in package.json # or pin exact versions, then: bun install ``` 2. **Review the breaking changes.** For each minor you cross, work through its section below, newest first. The [Release Notes](/docs/changelog) give each change its reason. 3. **Run migrations.** A release may add framework tables or columns: ```bash bun zt migrate ``` 4. **Type-check and test.** The fastest way to surface breaking API changes: ```bash bun run typecheck bun test ``` 5. **Boot it.** Start the dev server and exercise the main flows: ```bash bun dev ``` ## 1.18.0 A minor, with one type-level break and two changes that refuse what used to pass silently. Most apps need no change. ### The queue driver setting gains `"database"` `QueueConfigShape["driver"]` is now `"database" | "sqlite" | "redis" | "sync"`, and `QueueConfig()` fills in `"database"` where it filled in `"sqlite"`. Both names select the same driver, which now also runs on PostgreSQL and MySQL 8. **What to change.** Nothing in config files. Code that reads the setting needs a look in two cases: an exhaustive `switch` over it stops compiling until it has a `"database"` case, and a check of `config.get("queue.driver") === "sqlite"` that meant "jobs are in the database" no longer matches the default. Test for `"database"` as well. ### `zt migrate` refuses a half-run migration-number clash Two different migrations under one number, such as `0042_add_invoices` and `0042_add_refunds` from two branches, are now refused by `migrate` on a database that has run one of them and not the other. `zt doctor` fails on any clash, so CI catches one before merge. **What to change.** Run `bun zt doctor` once. If it reports a clash, its message gives the fix: renumber the later file if it has not run anywhere yet, or, if it has, keep it in place with a letter after the number (`0042b_add_refunds`) and pin its recorded name with `static override id = "0042_add_refunds"`. A new database runs a clash in name order with a warning, so nothing blocks a fresh environment. Migrations named by date are not numbered and never clash. ### A route name that two paths share is withheld A generated route name leaves out `[param]` segments, so `applications/act.ts` and `applications/[id]/act.ts` both came out as `applications.act.store`, and the route registered last kept the name. Such a name now names neither: it is left out of the generated route types, `route()` on it throws an error naming both paths, and `bun zt route:list` lists it. **What to change.** Run `bun zt route:list`. If it lists a shared name, give one of the routes its own name in the route file's `meta` (or with `.name()` in a routes file), and use that name where you linked to it. Both routes keep answering requests either way. ### Also worth knowing (not breaking) - **`database.backupBeforeMigrate: true`** takes a SQLite snapshot before `migrate`, `migrate:fresh` and `migrate:refresh` in production. Off unless you turn it on. - **`queue.visibilityTimeout`** can now be set. Raise it above your slowest job if you run more than one worker. - **New test helpers:** `withConfig()`, `withEnv()`, `Queue.settle()`, `Notify.settle()`. Any hand-written settle loop or env restore in your tests can go. - **An app created before this release** can add the bare-`bun test` guard with two lines in `bunfig.toml`; see [Testing](/docs/testing#a-bare-bun-test-stops-before-it-reaches-your-database). - **Run `bun zt arch:update`** if the app has `@zerotal/arch`: `AGENTS.md` now lists the settings registry, and two skills were corrected. ## 1.17.4 A patch. No app needs a code change. One fix can change what an existing app sees. ### `bun zt serve` listens on `PORT` `serve` used to listen on 3000 unless given `--port`, whatever `PORT` or `app.port` said. It now uses `--port` when given, else `app.port`, which defaults to `PORT`, else 3000. A `PORT` that is not a port, such as `80800`, stops `serve` with an error naming it. **What to change.** Nothing, unless the host sets `PORT` and your proxy forwards to 3000 because that is where the app always ended up. Point the proxy at `PORT`, or unset `PORT`. ### Also worth knowing (not breaking) - **`bun zt arch:update` adds the new `AGENTS.md` index and skills** in an app with `@zerotal/arch`. An app on the `zerotal` bundle also gets the package sections it was missing. - **A new app ships with the coding-agent files.** An existing app adds them with `bun add @zerotal/arch` and `bun zt arch:install`; see [Agent Surface](/docs/arch). ## 1.17.3 A patch. No app needs a code change. Two fixes can change what an existing app sees. ### `Carbon`'s ISO strings have three fraction digits `toISOString()`, `toJSON()` and `toDatabase()` used to trim trailing zeros, so a whole second printed as `2026-11-25T10:00:00Z` and `.940` as `.94Z`. They now always print three digits, as `Date.prototype.toISOString()` does: `2026-11-25T10:00:00.000Z`. Stored values now sort in time order as strings, and match what the ORM writes. **What to change.** Nothing in application code. A test that compares one of these strings against a literal without the fraction needs `.000` added to the literal. ### A security header a route sets itself is kept The security headers from `app.secureHeaders` are now defaults: a response that already carries one keeps its own value, and the rest are still added. Before, the global value replaced it. **What to change.** Nothing, unless a route sets one of these headers and you relied on the global value replacing it. Remove the route's header in that case. ### Also worth knowing (not breaking) - **`http.files()` and `http.file()` read `name[]` and `name[0]` fields**, so files posted by the Inertia adapter as `attachments[]` arrive. If you read `attachments[]` by hand to work around this, the workaround still works and can go. - **Routes under `app/routes/.well-known/` are served.** Remove any route you registered by hand to stand in for one. - **A malformed URL is a 400 under a storage mount**, and passes to your app elsewhere, instead of a 500. ## 1.17.2 A patch. No app needs a code change. Two fixes can change what an existing app sees. ### Route types gain the verb of `.name()` routes `bun zt route:types` used to leave a route named with `.name()` (`Router.get(…).name("login")`, and likewise after `Router.post`, `Router.flow` or `Router.view`) out of `METHODS` in `types/routes.generated.ts`. It now writes its verb, as it does for routes named by a file route's `meta`. **What to change.** Run `bun zt route:types` once and commit the file. Until then, a CI step running `bun zt route:types --check` reports the file as out of date. `route()` is unaffected. ### `/health` answers outside production An app that never configured health checks now serves `/health` outside production, as [Health checks](/docs/health) always said it would. Production is unchanged: the endpoint stays off there unless you turn it on. **What to change.** Nothing, unless you don't want the endpoint in development or staging: set `health: { enabled: false }` in `config/app.ts`. ### Also worth knowing (not breaking) - **More Flow pages compile ahead of time**: pages registered with `Router.flow()`, pages that extend a base class of your own, and pages with attribute values worked out on the server. They render the same HTML as before, and now also work under `cspSafe`, where the runtime fallback is refused. A page that still can't compile says why when you set `ZT_FLOW_COMPILE_LOG=1`. - **A missing route-bound record is no longer logged** as an unhandled error. It still answers 404. - **The React, Vue and Flow starters are full first apps.** This changes only what `bun create zerotal` scaffolds; existing apps are not touched. ## 1.17.1 A patch. One of its fixes changes what an app on SQLite can see. No app needs a code change. ### On SQLite, other requests wait for an open transaction Bun keeps one connection to a SQLite database. While a request had a `DB.transaction()` open, a statement from any other request ran inside it: a write reported success and was lost if the transaction rolled back. Now an open transaction holds the connection, and other requests' statements wait until it commits or rolls back. A statement that waits longer than `database.sqlite.busyTimeout` (5000 ms by default) fails with `database is locked`. A request that used to finish while a long transaction ran elsewhere can now wait for it, or fail after the timeout. **What to change.** Usually nothing. If you see `database is locked`: - keep transactions short, and don't await outside work, such as an HTTP call or another request's result, inside one; - pass `attempts` to `DB.transaction(cb, attempts)` to retry; - or raise `busyTimeout` in `config/database.ts`. [Transactions on SQLite](/docs/database#transactions-on-sqlite) has the details. PostgreSQL and MySQL are unchanged. ### Also worth knowing (not breaking) - **A binary built by `bun zt compile` now serves the app.** If you deploy with Bun and an installed `node_modules`, nothing changes. To deploy a binary instead, build assets first, then compile, and ship the binary with `.env` and `public/`: [Compile to a single binary](/docs/deployment#compile-to-a-single-binary). - **Admin apps scaffolded before 1.17.1** build their `users`, `products` and `settings` tables with `synchronize`, which is off in production. For a new database, copy `0002` to `0004` from the starter's `database/migrations/` and set `synchronize: false`. Leave a database that `synchronize` already built as it is, since those migrations would fail on `table users already exists`. ## 1.16 to 1.17 A minor that installs less into an app. The packages it stops installing for you are the ones only some apps use, so most of the steps below apply only to apps that use the feature. After upgrading, run `bun zt doctor`. It names a missing passkey library, image driver, AI provider SDK, Inertia framework package, and the admin panel's audit and notifications packages, each with the command to install it. The other optional packages below are not checked: read their steps. ### Passkeys need their library installed `@zerotal/auth` no longer installs `@simplewebauthn/server` or `reflect-metadata`. An app that never uses passkeys no longer carries them. **What to change.** If your app constructs `PasskeyService`, run: ```bash bun add @simplewebauthn/server reflect-metadata ``` Without them the app still boots and serves. The first ceremony throws `OptionalPeerMissingError` with that command in its message, and `zt doctor` and `zt deploy` fail until the packages are installed. `PasskeyService` now takes and returns Zerotal's own types, exported from `zerotal/auth`: `PasskeyRegistrationOptionsJSON`, `PasskeyRegistrationResponseJSON`, `PasskeyAuthenticationOptionsJSON` and `PasskeyAuthenticationResponseJSON`. Code typed with the library's types still compiles. Code that reads `attestationFormats`, or `extensions` other than `credProps`, from the returned options must drop the read. ### Passkey registration accepts any authenticator Registration no longer asks only for a platform authenticator, so a USB or NFC security key, or a phone reached by QR code, can now enrol. Sign-in is unchanged. **What to change.** Nothing, if you want this. To keep 1.16's behaviour, pass `authenticatorAttachment: "platform"` in the `PasskeyService` options. See [Authentication](/docs/authentication#passkeys). ### The panels run Tailwind v4 `flowUiHead()`, and so the admin panel and `/monitor`, loads Tailwind v4's browser build from `https://cdn.jsdelivr.net` with an integrity hash, in place of the v3 script from `cdn.tailwindcss.com`. **What to change.** 1. **Content-Security-Policy.** If yours allows `https://cdn.tailwindcss.com` in `script-src`, replace it with `https://cdn.jsdelivr.net`. These pages also run two small inline scripts (dark mode and the copy buttons), so their `script-src` needs `'unsafe-inline'`, and outside CSP-safe mode `'unsafe-eval'` as on every Flow page. [Recommended CSP header](/docs/flow/components#pages-rendered-with-flowuihead) has the policy. 2. **Your own markup under `flowUiHead()`**: custom admin pages, widgets, infolist entries and Flow pages are now compiled by v4. Rename the v3 classes whose meaning changed: | v3 | v4 | | ---------------------------------------- | ------------------------------------ | | `shadow-sm`, `blur-sm` | `shadow-xs`, `blur-xs` | | `drop-shadow-sm`, `backdrop-blur-sm` | `drop-shadow-xs`, `backdrop-blur-xs` | | bare `ring` | `ring-3` | | `outline-none` | `outline-hidden` | | `bg-opacity-50` (and `text-`, `border-`) | an opacity modifier, `bg-black/50` | | `bg-gradient-to-r` | `bg-linear-to-r` | | `hover:file:…` | `file:hover:…` | `hover:` now applies only on devices that can hover, and the default palette is v4's. 3. **Your own stylesheet** (`theme.stylesheet`). - **With your own v4 build:** put `flowTailwindCss()` (or `adminTailwindCss()`) and `flowTokensCss()` (or `adminTokensCss()`) in your entry, after `@import "tailwindcss";`. - **With your own v3 build:** move it to v4. The components now use class names that v3 does not generate (`outline-hidden`, `shadow-xs`, `bg-linear-to-*`), so under a v3 stylesheet focused buttons show the browser's outline, inputs lose their shadow and scroll areas their fade. Until you move, add `borderColor: { DEFAULT: "hsl(var(--border))" }` under `theme.extend` in a hand-written config, or default borders turn light grey in dark mode; `flowTailwindConfig()` and `adminTailwindConfig()` already do this. 4. **Your own `body` or `*` rules.** The token border and page colours now sit in `@layer base`. An unlayered `body { background }` or `* { border-color }` rule of your own now wins over them. See [Components](/docs/components). ### Flow no longer installs Alpine Flow's client runtime ships prebuilt in `@zerotal/flow`, so `alpinejs` and the `@alpinejs/*` plugins are no longer installed into your app. **What to change.** Nothing, unless your own code imports `alpinejs` or an `@alpinejs/*` plugin. Until now that import resolved through Flow. Add it to your app: ```bash bun add alpinejs ``` Add any plugins you import as well. ### Flow's route table has its own URL Pages now load the app's route table from `/__flow/routes/.js`. In 1.16 it came inside `/__flow/runtime.js`. Like that script, it passes through your app's global middleware, so it is refused wherever a page would be. **What to change.** If your own middleware turns away everything outside an allowlist of public paths, add `/__flow/*` to the allowlist. Otherwise `route()` and `navigate` links stop working on public pages, without an error on the page itself. Keep `/__flow/*` open at the proxy, as before. A proxy rule or layout that names `/__flow/runtime.js` or `/__flow/enhance.js` keeps working; the other scripts now load from content-hashed URLs. Those hashed scripts and `/__flow/enhance.js` are answered before your global middleware runs, so headers it adds, such as CORS or security headers, no longer reach them; set those at the proxy if you need them on every response. ### A missing optional package throws Zerotal packages now declare what they load from one another. An optional package that is missing raises `OptionalPeerMissingError`, exported from `zerotal/runtime`. Its message includes the command that installs the package. Before, the admin panel's options quietly did nothing, and tenancy and notifications threw an error of their own. **What to change.** - **Admin.** A resource with `static history = true` needs `@zerotal/audit`. `Panel.notifications(databaseNotifications())` needs `@zerotal/notifications`. `importAction({ queue: true })` and `dispatchImport()` need `@zerotal/queue`. Install each one, or remove the option. - **Tenancy.** If you catch `TenancyConfigError` around `tenantCache()` to detect a missing cache, catch `OptionalPeerMissingError` instead, or install `@zerotal/cache`. - **Notifications.** If you catch `NotificationChannelUnavailableError` from the broadcast channel to detect missing broadcasting, catch `OptionalPeerMissingError` instead, or install `@zerotal/broadcasting`. - **ORM without `zerotal`.** If your app installs `@zerotal/orm` on its own and uses the validator, run `bun add @zerotal/validator`. Apps on the `zerotal` package need nothing. ### A missing sharp fails conversions With `driver: "sharp"` in `config/media.ts`, a missing or unloadable sharp used to produce no conversions, without an error. Now `addMedia()` into a collection with conversions throws `OptionalPeerMissingError` once the original is stored, and queued conversions fail. **What to change.** Run `bun add sharp` (0.33, 0.34 or 0.35 are supported), or set `driver: "bun"`. Code that caught `MediaError` for a missing sharp should catch `OptionalPeerMissingError`. See [Media](/docs/media). ### `.vue` pages need `@vue/compiler-sfc` 3.3 or later **What to change.** Install the compiler at the same version as `vue`: ```bash bun add vue@^3.5 @vue/compiler-sfc@^3.5 ``` New starters already have it. A Vue app with `inertia.ssr: true` and no compiler now fails at boot instead of rendering the page's file path. React apps need nothing. Code that matched the old React SSR error message should catch `OptionalPeerMissingError` instead. ### On Bun 1.4, Carbon hands out Bun's own `Temporal` values Carbon now uses the runtime's `Temporal` when there is one, and loads `@js-temporal/polyfill` only on Bun 1.3. **What to change.** Nothing on Bun 1.3. On Bun 1.4, an app that imports `Temporal` from `@js-temporal/polyfill` and passes a Carbon `ZonedDateTime` to that import's `ZonedDateTime` methods (`compare`, `from`, `until`, `since`, `equals`), or checks Carbon's values with `instanceof` against it, must use the global `Temporal`. An app that runs on both Buns can define its own: ```ts import { Temporal as Polyfill } from "@js-temporal/polyfill"; export const Temporal = (globalThis as { Temporal?: typeof Polyfill }).Temporal ?? Polyfill; ``` That is always the implementation Carbon runs on. See [Carbon](/docs/carbon). ### The ORM reads dates back as the instant saved The ORM writes every date as UTC. It now reads them back that way too, whatever the server's `TZ`: zone-less date-time text, such as MySQL's `YYYY-MM-DD HH:MM:SS` or SQLite's `CURRENT_TIMESTAMP`, is read as UTC, and MySQL `DATE`, `DATETIME` and `TIMESTAMP` columns read the same on Bun 1.3 and 1.4. In 1.16, under a `TZ` other than UTC, a MySQL date moved by the zone's offset between a save and the next load. A value that something else wrote as local time is now read as UTC as well, so under a `TZ` other than UTC it reads differently from 1.16. That covers a MySQL column that `NOW()` or `CURRENT_TIMESTAMP` filled on a server outside UTC, and text written as local time by another program or by hand-written SQL. Nothing stored changes. **What to change.** 1. If `TZ` is unset or UTC and your MySQL server runs in UTC, nothing. 2. Otherwise run `bun zt doctor`. If it warns about MySQL's time zone, run the server in UTC (`default-time-zone = '+00:00'` under `[mysqld]`, or `SET GLOBAL time_zone = '+00:00'`), then restart the app so its connections reopen. Bun 1.4.1 and later open every connection in UTC; Bun 1.3 and 1.4.0 keep the server's zone and cannot set one per connection. 3. Convert rows written in the old zone with `CONVERT_TZ`, or read such a column through a custom cast. [The MySQL server's time zone](/docs/orm/casts#the-mysql-servers-time-zone) shows which rows move and the statement for each. 4. Remove any code that added the zone offset back to dates the ORM read. It now corrects twice. 5. On Bun 1.3, prefer `TZ=UTC`. Bun 1.3 cannot read back a MySQL time in the zone's daylight-saving gap, and it reads a PostgreSQL `timestamp without time zone` column queried with no bound values shifted the first time that query runs on a connection. Bun 1.4 reads both correctly. A `Carbon` in `where()` now binds the way a save stores it, so a query that compared against a `Carbon` can return different rows: on MySQL it now finds rows it used to miss, and on SQLite and PostgreSQL an equality keeps its milliseconds. ### Also worth knowing (not breaking) - **`NotificationFake` moves.** Change `import { NotificationFake } from "zerotal/testing"` to `from "@zerotal/notifications"`, and run `bun add -d @zerotal/notifications` if your `package.json` does not list it. The old import is removed in 1.18. - **`@zerotal/ai` bounds the Anthropic SDK to `>=0.70.0 <2`**, so an app on SDK 2.x gets a peer warning. - **Vue and api apps scaffolded before 1.17** can apply the starters' sign-in fix. 1. In `app/models/User.ts`, import `Authenticatable` from `zerotal/auth` and extend `Model.using(Authenticatable)`. 2. Add the `remember_token` migration that `bun zt doctor` prints. 3. In a Vue app, also add `StorageProvider` after `DatabaseProvider` in `bootstrap/providers.ts`. - **`bun zt compile` with no `--entry`** now compiles `zt.ts`, so the `--entry=zt.ts` workaround can go. The binary starts and runs console commands, but cannot serve an app yet: keep deploying with Bun and an installed `node_modules`, as [Deployment](/docs/deployment#compile-to-a-single-binary) describes. - **On Bun 1.4, `bun build --outfile` fails for an app that uses Flow or devtools**, because their prebuilt scripts are written as separate files. Use `--outdir`, or `bun zt compile`. ## 1.16.4 A patch. Two of its changes can alter what an app sees; neither needs a code change in an app that configures passkeys correctly and lists what it imports. ### A misconfigured passkey setup is thrown `PasskeyService.verifyRegistration()` and `verifyAuthentication()` answered `"passkey.invalid"` for every failure, including an `origin` ending in `/` or an `rpId` written in non-ASCII letters rather than punycode. Those failed every ceremony while looking like a bad response from the browser. They are now thrown, with a message that names the fix. A response that fails verification is still `"passkey.invalid"`. **What to change.** Nothing, if passkeys work today. If they never have, the error now says why. See [Authentication](/docs/authentication). ### `@zerotal/flow-ui` no longer installs `clsx` `cn()` flattens its input itself, with the same output. The `lib/cn.ts` that `flow:add` and `flow:init` copy into an app imported `clsx`, and the commands asked you to add it only when it did not already resolve, which in an app with flow-ui installed it usually did. Such an app was using flow-ui's copy, and that copy is gone. **What to change.** If your code imports `clsx` and your `package.json` does not list it, run `bun add clsx`, or replace a copied `lib/cn.ts` with the new one, which needs only `tailwind-merge`. ## 1.16.3 A patch. Two of its fixes change what an app can see; neither needs a code change unless a test relied on the old answer. ### A thrown `ValidationError` answers the way `validate()` does A `ValidationError` from `@zerotal/core/errors` used to get the handling of any other 4xx: a styled `422` page for a browser, and for every other client a `422` whose JSON had no `errors`. It now follows `validate()`. A client whose `Accept` prefers JSON gets a `422` with your message and every message per field. Anything else, a request with no `Accept` included, is redirected back with `303`, the first message per field flashed as `errors` and the body as `old`. **What to change.** A test that throws one and expects a `422` should send `Accept: application/json`, with `asJson()`. A test that expects the redirect needs nothing. See [Errors](/docs/errors#validation-errors). ### A failing response finalizer shows in development and tests A callback registered with `ctx.onResponseReady()` that throws was logged and the response went out anyway. Where development surfaces are on, which includes `zt test`, the error's response now replaces it. The finalizer the framework registers is the session's, so the case you will meet is a session too big for the cookie driver: the request answers with `SessionCookieOverflowError`, whose message names the biggest keys, instead of sending the page without the cookie and losing every flash, error and old input on it. Production still logs and sends the response. **What to change.** Nothing, unless a test was passing over an overflowing session. Store an identifier rather than the object, or move to a server-side driver. See [Session](/docs/session#errors). ## 1.16.2 A patch, but five of its fixes change what an app can see. None needs a code change unless it relied on the old behaviour. ### Mail refuses what it cannot send as written An address that holds a control character, whitespace, `<`, `>`, `,` or `;`, or that is longer than 254 characters, throws `InvalidMailAddressError`, and so does a display name holding a line break. The check runs when the address is set on a `MailMessage`, when a notifiable's `email` becomes the recipient, and again in each driver. `"Ada "` is still accepted and split into a name and an address, and `mail.from.address` may be written that way. **What to change.** Validate addresses where users type them, with the validator's `email` rule, so a bad one is a 422 on the form and not an exception when the mail goes out. A configured sender the check would refuse now fails at boot, naming the key. See [Notifications](/docs/notifications#mail). A test that calls `MailMessage.toPayload()` itself must pass both arguments, the default sender and the fallback recipients, as its signature always said. Called with no recipients set and no fallback, it used to return a payload with `to` undefined; it now throws. ### Idempotency keys are scoped `IdempotencyMiddleware` keys a stored response by the signed-in user, or the session the client sent back, plus the method, host, path, query string and the client's key. It used the key alone, so one caller could be answered with another's response. **What to change.** Nothing, for clients that retry the same request with the same key. Responses stored before the upgrade are not replayed, so a retry that straddles the deploy runs its handler. Register the middleware after session and authentication for the default scope to see the user, or pass `scope`. See [Cache](/docs/cache#idempotency-middleware). ### A validation error answers JSON when `Accept` prefers it `validate()`, `FormRequest` and the exception handler now agree: JSON when `application/json` has a higher q-value than `text/html`, or the same and comes first, with or without `X-Inertia`. A `ValidationError` you throw yourself joined them only in [1.16.3](#1163). `text/html, application/json` used to get a 422 from the validator and now gets the redirect; `X-Inertia` with `Accept: application/json` used to get a redirect and now gets the 422. Browsers and Inertia's own visits are unchanged. **What to change.** A test that posts and expects a 422 should send `Accept: application/json`. ### String SQL counts its placeholders A `?` inside a string literal, a quoted identifier or a comment is no longer a placeholder in `DB.raw()`, `whereRaw()` and the other string-SQL paths, and `DB.raw(sql, bindings)` throws when the number of placeholders and bindings differ. A query that bound the wrong values before now binds the right ones or fails loudly. **What to change.** Nothing, if your queries worked. Write PostgreSQL's bare `?` jsonb operator in the tagged form. See [Database](/docs/database). ### A thrown 4xx is not reported An `HttpError` below 500 and an `abort(4xx)` are expected outcomes: logged as one warning, and not passed to `report()`. An error that only carries an upstream status, such as an `HttpClientError` from a 401, is still reported. **What to change.** If an error tracker counted 4xx responses through `report()`, count them from the access log or `RequestFailed` instead, which carries `expected`. ### Also worth knowing - **Queue:** a chained job and a batch's `then`, `catch` and `finally` jobs go to their own class's queue; make sure a worker polls it. `retryFailed()` throws `E_QUEUE_UNKNOWN_JOB` for a job whose class is not registered. - **`ctx.body()`** returns `{}` for a JSON body that is a number, string, boolean or `null`. - **A file-route resolver's `ctx.middleware`** no longer includes the group's middleware; the registrar adds it. ## 1.15 to 1.16 One breaking change, to what `app.throttle.trustedProxies` counts, and one place that now follows it. ### `trustedProxies` counts from the right, and the client is the last entry Each proxy appends the address it received the request from to `X-Forwarded-For`, so behind one proxy the client is the last entry. `trustedProxies: 1` used to read the entry before it, which is one the client can write. It reads the last entry now, and the same count is used everywhere the framework needs the client's address: every throttle, the sign-in lockout, the audit trail and Flow. | Your proxy | Before | After | | ---------------------------------------------------------------------------------- | ------ | -------------- | | Appends one entry (nginx `$proxy_add_x_forwarded_for`, Caddy, most load balancers) | `1` | `1`, no change | | Appends two entries, its peer and its own address | `1` | `2` | | Two proxies, one entry each | `2` | `2`, no change | **What to change.** Look at one request's `X-Forwarded-For` as your app receives it, with no header sent by the client. If it has one entry per proxy, leave the count alone. If it has more entries than you have proxies, the count goes up by the difference. Getting it wrong the other way is easy to see: every request reads as your load balancer's address, and the first throttle to fill refuses everyone. ### The audit trail stops reading `X-Forwarded-For` unless you say how many proxies there are With `captureRequest`, an audit entry's `ip_address` was the leftmost `X-Forwarded-For` entry, whatever `trustedProxies` said. It now follows the same rule as the throttles: the socket address with no `trustedProxies`, otherwise the client counted from the right. **What to change.** Nothing, if `app.throttle.trustedProxies` is already set. An app behind a proxy without it will start recording the proxy's address on new entries; set the count, as [Deployment](/docs/deployment#behind-a-reverse-proxy) describes, and `zt doctor` warns about. Entries already written keep the address they were written with. ### Also worth knowing (not breaking) - **`ctx.clientIp()`** returns the client's address by the same rule, or `null` when the request offers none. Use it where you used to read `X-Forwarded-For` yourself; `ctx.ip()` is still the socket, which behind a proxy is the proxy. - **An app scaffolded with 1.15.5 has a second Bun** in `node_modules/bun` and prints a warning about it. Add a `bunfig.toml` with an `[install]` table holding `peer = false`, delete `node_modules`, then run `bun install`. Adding the setting alone keeps the copy already installed. See [1.15.6](/docs/changelog#1156-2026-10-28). ## 1.14 to 1.15 Two breaking changes. Both replace something that was quietly wrong with something that says so. ### `createdAt`, `updatedAt` and `deletedAt` are `Carbon`, not `Date` They always hydrated as `Carbon` — every `datetime` column does — but were declared `Date`, so the type was wrong on any row loaded from the database. Worse, the runtime class depended on how you got there: a `Carbon` after a load, a raw `Date` after a `save()`, a `touch()` or a soft `delete()`. The same property on the same model, matching its declared type in neither case. ```ts fragment // before — compiled, and threw at runtime on a loaded row const ms = order.createdAt.getTime(); // after const ms = order.createdAt?.valueOf(); // epoch milliseconds const iso = order.createdAt?.toISOString(); // "2026-09-04T08:15:00.000Z" const native = order.createdAt?.toDate(); // a real Date, if something needs one ``` **What to change.** Compile and follow the errors: every one is code that would have thrown if that line had run against a loaded row. `Carbon` has `toISOString()`, `valueOf()`, `toJSON()` and `toDate()`, plus its own comparison and arithmetic — it does not have `getTime()`, `getFullYear()` or the rest of the `Date` accessors. If you were working around the old inconsistency, the workaround can go: ```ts fragment // before — needed because the class varied by path const ms = ((value as any).toDate?.() ?? value).getTime(); // after const ms = value.valueOf(); ``` A cast that hid the mismatch (`order.createdAt as unknown as string`) now hides a different one — `.slice(0, 10)` on a `Carbon` still throws. Use `.toISOString().slice(0, 10)`. ### A broken `_middleware.ts` stops the boot Two ways a `_middleware.ts` could fail to apply used to be silent, leaving the routes it was written to guard live and unguarded: - **`export default [Middleware]`** — the loader only ever read `export const middleware`. `export default` is the natural guess, because every route file in the same directory default-exports its handler. - **A file that fails to import** — a typo, a bad import path, a circular import, a `SyntaxError`. All shared a `catch` with the missing-file case, so all read as "this directory has no middleware". Both now fail the boot, naming the file and the fix. A directory with no `_middleware` file is unchanged: absence is the convention working, and stays silent. ```ts fragment // app/routes/employer/_middleware.ts // before — silently ignored, subtree served unguarded export default [EmployerMiddleware]; // after export const middleware = [EmployerMiddleware]; ``` **What to change.** Boot the app once — `bun zt route:list` is enough. If nothing changes, you had none of this. If a `_middleware.ts` file was never applying, you will be told which one, and the routes under it were open until now. Under `zt dev` a reload that hits this aborts and keeps serving the previously compiled routes, so a guard never drops mid-session. ### Also worth knowing (not breaking) - **A save or delete on a model with no primary-key value now raises an error** (1.15.1). It used to bind NULL, match no row, and resolve as though it had written. The one way to reach it is a partially hydrated instance — `Post.query().select("title").get()`, then `save()` on a result — and in that state the write was already being thrown away. What changes is that you hear about it: `E_NO_PRIMARY_KEY`, naming the model and the key. Select the key column alongside whatever else you need, and the write works as intended. - **`bun zt route:types` regenerates the Inertia page registry too.** Adding a page and getting `TS2345: … not assignable to parameter of type 'PageName'` is now fixed by the command whose name says it generates types. `--check` gates on both files. - **`bun zt test` no longer inherits `.env`'s mail, queue, session and cache drivers.** They get their in-process defaults (`log`, `sync`, `cookie`, `memory`) so a suite cannot open a real SMTP or Redis connection because of how one machine is configured. A value set in the shell still wins, `.env.test` is read and merged last, and `--keep-env` turns it off. See [Testing](/docs/testing#bun-test-vs-bun-zt-test). - **`zt doctor`'s secure-headers check probes the deployed URL** instead of inferring HSTS from config, so an app behind a TLS-terminating proxy is no longer reported as downgradeable when the header is being sent. ## 1.13 to 1.14 One breaking change, and it is small in practice. **`inertia.ssr: true` no longer registers `POST /__ssr`.** Rendering and the endpoint are separate decisions now: ```ts fragment // config/inertia.ts — before export default InertiaConfig({ ssr: true }); // rendered, and opened the route // after export default InertiaConfig({ ssr: true }); // renders, and opens nothing export default InertiaConfig({ ssrEndpoint: true }); // opens the route, for an // external renderer ``` **Most apps need no change.** If you set `ssr: true` for server rendering — which is what the option is for — you keep exactly that, and you stop exposing a route you were not using. The endpoint had no in-process caller before 1.13.5, so an app that set the flag was getting the route and nothing else. **Add `ssrEndpoint: true` only if something outside the web process calls `/__ssr`** — a separate renderer, a second host. If you are not running one, you were not using it. Why split them: turning rendering on should not open a route that renders arbitrary components from POST input, however well guarded. One switch, one thing. ## 1.12 to 1.13 Three retirements in one crossing, deliberately together: each is a small migration, and three minors each asking an app to move costs more than one that asks properly. `zt upgrade` does the mechanical half. ```bash fragment bun zt upgrade --to 1.13.0 ``` ### `Component.client(…)` is removed — use the `$` tagged template The reason this did not wait: `client()` took a **string** and queued it to be evaluated in the browser, so the caller owned the escaping. Its own docblock had to say _never interpolate unescaped user input_, which is a warning about a footgun rather than a design. `$` is a tagged template, so every `${…}` is encoded as a JS literal before it reaches the page. ```ts fragment // in a component class body — before this.client(`$refs.titleInput.focus()`); this.client(`toast(${JSON.stringify(this.search)})`); // escaping was yours to remember // after this.$`$refs.titleInput.focus()`; this.$`toast(${this.search})`; // encoded for you ``` The codemod rewrites a call whose argument is a single literal. **A call whose argument is a variable or a concatenation is reported rather than rewritten**, because those are exactly the ones the security note was about — and wrapping the finished string as `` $`${expr}` `` would encode it as a string literal and stop running it as code. Read those and interpolate through `$` instead. Removing it also frees `client` as a property name on your components, the way removing `title` did in 1.7.3. ### `LockDriver.extend()` is required Only affects a **custom lock driver**; the three built-in ones already implement it. It shipped optional in 1.5.0 with `acquire(key, owner, ttl)` as the fallback, and the fallback was correct only by coincidence: `acquire` happens to be an owner-guarded refresh on every built-in driver, and nothing in the interface said it had to be. A driver whose `acquire` takes a _free_ lock — the ordinary reading of the word — would have had `refresh()` silently take a lock another holder owned, which is the one thing a lock exists to prevent. Implement `extend(key, owner, ttlSeconds)`: push the deadline out, return `false` when the key is free or held by someone else. ### `routes:types` and `serve --dev` are retired `route:types` and `dev` are the real names. The codemod rewrites both in scripts and CI config. `serve --dev` **fails loudly** rather than being ignored. The flag is still declared for exactly that reason: flag parsing is non-strict, so deleting it would have left `serve --dev` starting a plain server with no watcher and no message — a retired flag that silently changes what a command does. ## 1.11 to 1.12 One breaking change, and it is the intended kind: a minor, announced, with the reason. **A boolean written to a text column is refused.** A bare `@column()` resolves to `{ type: "string" }`, so a boolean property decorated with one was stored as text — and a text column has text affinity, so `false` was stored as `"0"`, which is truthy in JavaScript. Every `if (model.flag)` on such a column took the wrong branch for a stored `false`, on every row, with nothing in the app or the database registering a fault. An app found it when a feature flag read as enabled for every record that had it turned off. ```ts fragment // in a model class body — before, and silently wrong @column() declare active: boolean; // after @column("boolean") declare active: boolean; ``` There is no correct coercion: `0` becomes `"0"` and `"false"` is truthy too, so the value cannot survive the round trip. The write now throws `ColumnTypeError`, naming the property and the fix. ### What to do before upgrading **Find your boolean properties whose `@column()` declares no type.** The decorator cannot find them for you — `declare active: boolean` erases the TypeScript type at runtime, so a bare `@column()` on a boolean is indistinguishable from one on a string until a value arrives. A search of your models for `@column()` with no argument, read against the property types beside them, is the reliable way. **The rows you already wrote are still text.** This release stops new bad writes; it does not migrate old ones. A column that has been holding `"0"` and `"1"` needs both the decorator fixed and the stored values converted — on SQLite, `UPDATE widgets SET active = CAST(active AS INTEGER)` after the column type is corrected. Until then those rows keep reading truthy, which is the behaviour you are upgrading to escape. **If a text column really should hold a boolean**, say so explicitly and it is honoured: `@column({ type: "string", cast: "boolean" })`. The guard is for the column that says nothing, not for every string column. ## 1.11.2 One breaking change, and it is in a release that should not have carried one. **`countTokens` returns `number | null`.** `Ai.countTokens()` and `AiDriver.countTokens()` used to return `number`, with `0` standing in for "this provider cannot count". Only Anthropic has a counting endpoint, and `0` is also a real count for an empty prompt — so the old return value could not tell you which it meant, and a budget built on it was quietly wrong for every other provider. ```ts fragment // before const tokens = await Ai.countTokens(prompt); if (tokens > 1000) shorten(); // after const tokens = await Ai.countTokens(prompt); if (tokens !== null && tokens > 1000) shorten(); ``` A custom `AiDriver` needs no change — returning `number` still satisfies `Promise`. Only callers do. **Why this is in a patch.** It was made while `@zerotal/ai` was still `experimental` and therefore outside the compatibility promise, in the same release that then promoted the package to `stable`. That ordering is real and it is not a distinction anyone installing 1.11.2 can observe: what arrives is a patch that breaks a build. The rule stands as written — a patch does not break — and this release is recorded as the exception rather than as a reinterpretation of it. See [the support policy](/docs/support-policy#releases-and-versioning). Everything else in 1.11.2 is additive. `@zerotal/ai`'s other surface change — `toSchema`, `strippedConstraints`, `resetSpend` and `resetStats` becoming `@internal` — leaves those exports working; they are no longer covered by the promise, which is different from being gone. ## 1.10 to 1.11 Two changes to how the database is treated. Both are **BREAKING** in the narrow sense that a working app can stop working on upgrade, and both refuse loudly rather than doing something quiet. 1. **SQLite enforces foreign keys.** `database.sqlite.foreignKeys` defaults to `true`, so `PRAGMA foreign_keys = ON` is set on every connection. Until now SQLite ignored them, which meant `constrained()` and `cascadeOnDelete()` in your migrations described behaviour the database would not perform — deleting a parent left its children, silently. The risk is data you already have. A child row whose parent is missing was legal without enforcement and is a constraint violation with it, so a write touching one now fails. Find them before deploying: ```bash fragment bun zt db:check-foreign-keys ``` It lists every offending row by table and rowid and exits non-zero, so a release script can gate on it. `zt doctor` reports the same thing. Delete them or repoint them at a parent that exists. To take the release without dealing with it yet: ```ts fragment // config/database.ts export default DatabaseConfig({ sqlite: { foreignKeys: false } }); ``` Take that override back off afterwards. With it in place `cascadeOnDelete()` is a comment. 2. **A renumbered migration is refused rather than re-run.** A migration is recorded under its filename, so renaming one makes an applied migration look pending — the runner tries it again and fails on `table already exists`. Renumbering `001_` to `0001_` to match the scaffold's convention is exactly the kind of tidying that causes it, and it takes every migration with it. `migrate` now recognises that shape and stops: ``` "0001_create_users" looks like "001_create_users", which has already run — the same migration renumbered rather than a new one. ``` If you meant to rename, pin the identity to what the database already holds and the filename is then free: ```ts fragment export default class CreateUsers extends Migration { static override id = "001_create_users"; } ``` If it really is a new migration, give it a name that does not collide once the leading digits are removed. ## 1.9 to 1.10 Three settings changed meaning. Each is quiet if it does not apply to you, and each is worth thirty seconds of checking if it does. 1. **`scheduler.timezone` is honoured.** It was documented as informational and read by nothing, so whatever you put there had no effect and your schedules ran in the server's zone. It is now the zone every schedule is evaluated in unless the task sets its own. Its default moved from the literal `"UTC"` to **the system zone**, so an app that never set the key keeps doing exactly what it did. The case to check is an app that _did_: ```ts fragment // config/scheduler.ts export default SchedulerConfig({ timezone: env("APP_TIMEZONE", "UTC") }); ``` On a server that is not on UTC, that line used to do nothing and now moves every schedule. Either set it to the zone you actually want your crons read in — which is the point of the setting — or delete the key to keep the server's zone. `bun zt schedule:list` prints each task's next run in its own zone, which is the quickest way to see whether anything moved. 2. **Named rate limiters need `.trustedProxies(n)` behind a proxy.** `RateLimiter`'s `.byIp()`, `.byUser()` and `.byApiKey()` ignored the proxy count entirely and read `X-Forwarded-For` unconditionally. They now follow the same rule `ThrottleMiddleware` already did — the header is consulted only when you say how many proxies sit in front: ```ts fragment RateLimiter.for("login").limit(5).every(60).byIp().trustedProxies(1).register(); ``` Without it the address used is the socket's, which behind a proxy is the _proxy's_, and every visitor shares one bucket. `bun zt doctor` reports any limiter that needs this — it could not before, because its check exempted custom key resolvers and all three of these are one. 3. **React apps using SSR need `@inertiajs/react` installed.** The same adapter your browser entry point already uses. Server-side rendering now goes through its ``, which is what makes `` produce a title and an og: card in the HTML your server actually sends. If it is missing you get a named error at render time, not a silent omission. Nothing to change if you already have it as a dependency, which every React Inertia app does. ## 1.7.2 and 1.7.3 Two patch releases that broke, each on the judgement that the old form had no meaningful use yet. Both are a find-and-replace. 1. **Rename `echo:` listeners to `socket:`** (1.7.2). `echo:`, `echo-private:` and `echo-presence:` in `@on` are now `socket:`, `socket-private:` and `socket-presence:`, and the browser global is `window.Socket`, not `window.Echo`. There is no alias, so an unrenamed listener never subscribes and nothing says so: ```diff - @on("echo-private:issues.5,CommentPosted") + @on("socket-private:issues.5,CommentPosted") ``` 2. **Replace `this.title(…)` with `static title`** (1.7.3), as a string or a function of the component. It is resolved on every render, so a title that depends on state follows it: ```ts fragment // Before override async mount(): Promise { this.title(`Search: ${this.query}`); } // After static title = (c: SearchPage) => (c.query ? `Search: ${c.query}` : "Search"); ``` The [1.7.2](/docs/changelog#172-2026-08-18) and [1.7.3](/docs/changelog#173-2026-08-20) release notes have the reasons. ## 1.4 to 1.5 1. **Move query values into `route()`'s third argument.** A param that matches no `:segment` used to be appended to the query string, so a typo'd param name produced a wrong URL instead of an error. Params are now exact, and an unknown key throws: ```ts route("search", { q: "zerotal", page: 2 }); // before route("search", {}, { q: "zerotal", page: 2 }); // now ``` The same applies anywhere params are passed on their own — `redirect().to(name, params)`, `redirectTo()`, `Url.route()`, `Uri.route()`, and Flow's `redirectRoute()`. Where those need a query string, build the URL with `route()` and redirect to it. To find them: search for `route(` calls whose second argument holds a key that is not a `:segment` of that route. `bun zt route:list` prints the patterns to check against, and after step 2 the type-checker finds the rest for you. 2. **Generate and commit the route types** — this is what turns the change above from a runtime error into a compile error, and it is the point of the release: ```bash bun zt route:types # writes types/routes.generated.ts ``` Commit the file. `zt dev` refreshes it on every restart; add `bun zt route:types --check` to CI so it cannot go stale. Skipping this step is supported — `route()` then behaves exactly as it did, minus the query-param change. 3. **Rebuild the Inertia page registry** to get typed page names and props: ```bash bun zt inertia:build ``` Then fix what it finds. Two are worth expecting: a page whose component declares a prop the controller never passes (add it, or make the prop optional), and a `defer()`/ `optional()` prop the component declares as required (make it `?` — it really is absent on first paint). Declare any `Inertia.share()` keys of your own on the `SharedProps` interface so pages that read them do not look unpassed; see [Typed props](/docs/inertia/props#typed-props). ## 1.2 to 1.3 1. **Compose mixins with `using`.** `ComponentWith(...)` and `BaseModelWith(...)` are removed; the base class composes its own mixins: ```diff - class PostsPage extends ComponentWith(Pagination) {} + class PostsPage extends Component.using(Pagination) {} - class User extends BaseModelWith(Authenticatable, Roles) {} + class User extends Model.using(Authenticatable, Roles) {} ``` A codemod in the repository, `scripts/codemod-mixin-composition.ts`, rewrites the call sites and imports. How a mixin is written is unchanged, and `BaseModel` stays exported as an alias of `Model`. The [1.3.0 release notes](/docs/changelog#130-2026-08-09) have the rest. ## Pre-release checkout to 1.0 1.0 is the first public release, so there is no earlier published version to move from. If you have been building against a pre-release checkout of the source, these are the changes that need action. Full detail is in the [1.0.0 release notes](/docs/changelog). 1. **Import storage from `@zerotal/core/storage`.** The separate `@zerotal/storage` package is gone — file storage ships inside core, as a subpath beside `core/logger` and `core/http`. Drop the dependency from `package.json` and update the imports: ```ts // before import { Storage, StorageProvider } from "@zerotal/storage"; // after import { Storage, StorageProvider } from "zerotal/storage"; ``` Nothing else changes: the same `StorageProvider`, the same `config/storage.ts`, the same disks and driver API. 1. **Move public files to `storage/public`.** The public disk's root changed from `storage/app/public` to `storage/public`, and it is served at `/storage/public` rather than `/storage`. Everything else under the storage root is private: a local disk outside `storage/public` can only be served with `serve: { signed: true }`, and serving one openly now fails at boot. ```bash mv storage/app/public storage/public ``` Any hardcoded `/storage/...` link becomes `/storage/public/...`. Better, ask for the URL instead: `await Storage.publicUrl(path, { disk: "public" })`. 1. **Expect logs on disk.** Every entry now goes to the terminal _and_ a date-rotated file under `./storage/logs`, kept 14 days. If you ship stdout to a collector and want no files, set `file: false` in `config/logging.ts`. If you had a `default: "daily"` channel to get files, you can delete it — and your terminal output comes back, since console is no longer a channel that `default` can point away from. 1. **Add a `fillable` (or `guarded`) list to every model written from user input.** Models now guard mass assignment by default — a model declaring neither rejects every attribute passed to `create()`/`fill()` with a `MassAssignmentError`. For trusted, non-user writes use `forceFill()`/`forceCreate()`, wrap a block in `Model.withoutGuard(fn)`, or set `static unguarded = true`. 1. **Ensure `APP_KEY` is set in every environment.** `local` storage `temporaryUrl()` now throws `StorageKeyMissingError` instead of falling back to a hard-coded key, and a key under 32 bytes now throws at boot in production-like environments (`APP_ENV` = `production`/`prod`/`staging`). Generate one with `bun zt key:generate`. 1. **Update merged-package imports.** `@zerotal/lock` → `@zerotal/core/lock` and `@zerotal/logger` → `@zerotal/core/logger`; remove both from `package.json`. No API changes. 1. **Re-check ops-surface gates.** The devtools inspector, the monitor panel's default open access, and the dev error page now key off `APP_ENV` and **fail closed** — an unset or `staging` `APP_ENV` no longer exposes them. The admin panel and the monitor `/metrics` endpoint are now default-deny/opt-in. Set an explicit `middleware`/`auth` in `config/admin.ts` and `config/monitor.ts`, and set `APP_ENV=development` locally if you relied on the previous open-in-dev behaviour with an unset value. 1. **Redis cache prefix moved to `zerotal:cache:`.** If you run cache and queue on the same Redis DB, `Cache.flush()` no longer deletes queued jobs. Existing cache entries under the old `zerotal:` prefix are effectively invalidated on upgrade (they are simply not read again) — no action needed beyond expecting a cold cache. ## The managed zt.ts `zt.ts` is framework-managed — the header says _do not modify_. If a release changes the CLI entry point, re-scaffold it rather than hand-editing. Because you never customized it, replacing the file is safe; your app lives in `app/`, `bootstrap/`, `config/`, and `routes/`. ## Things to check after a major upgrade - **Config shapes** — a `*Config()` factory may have new or renamed fields. Your editor's types will flag mismatches; re-check `config/*.ts` against the [Configuration](/docs/config-system) docs. - **Provider registration** — confirm any package providers you list in `bootstrap/providers.ts` still export the same names. - **Deprecations** — a minor release may log deprecation warnings for APIs removed in the next major. Resolve them before taking the major. - **Lockfile** — commit the updated `bun.lock` so deploys install the same versions. ## Next steps - [Release Notes](/docs/changelog) — per-version changes and migration notes. - [Configuration](/docs/config-system) — config factories whose shapes may change. - [Getting Started](/docs/getting-started) — the baseline project layout. --- Source: https://zerotal.dev/docs/support-policy # Support Policy This page is the compatibility contract: which runtime and database versions Zerotal stands behind, how releases and deprecations work, and what the maturity label on each package promises. If a claim is not on this page, treat it as untested. ## Runtime Zerotal runs on **Bun only**. Node.js and Deno are not supported and there is no compatibility layer planned — the framework builds directly on `Bun.serve`, `Bun.sql`, `Bun.CryptoHasher`, `Bun.RedisClient`, S3 storage, and the Bun test runner, which is where its speed and its small dependency footprint come from. The supported Bun range is what CI actually proves, not a hopeful floor: | Bun version | Status | | --------------------- | ------------------------------------------------- | | 1.3.14 | Supported — the tested floor, pinned in CI | | Latest stable release | Supported — CI tracks it alongside the floor | | Older than 1.3.14 | Not supported — core APIs Zerotal uses are absent | Every package declares this floor in its `engines.bun` field, so an install on an unsupported Bun fails at install time rather than at runtime. ### The platform-risk position Betting on one runtime deserves a stated answer to "what if Bun changes course?", so this is it: - **Which Bun APIs are load-bearing:** `Bun.serve` (HTTP), `Bun.sql` (SQLite and Postgres drivers), `Bun.RedisClient` (cache, session, queue, broadcasting), `Bun.CryptoHasher` and `Bun.password` (crypto and hashing), `Bun.S3Client` (storage), `Bun.build` (dev asset pipeline), and the `bun test` runner. A breaking change in any of these is treated as a breaking change in Zerotal and handled in a release, never silently. - **How fast Zerotal tracks Bun:** CI runs the tested floor and the latest stable Bun on every merge, so a Bun regression that affects the framework surfaces within days of the Bun release, not when users hit it. The floor moves forward deliberately — in minor releases, with the change called out in the release notes. - **Pinning guidance:** pin the Bun version in production images and move it when you upgrade Zerotal, exactly as you would any other runtime. ## Databases | Database | Status | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SQLite | Supported. The default; the full test suite runs against it on every merge. | | PostgreSQL | Supported. A smoke suite runs against a real PostgreSQL 16 on every merge — schema DDL and `ALTER`, identity columns, CRUD, type round-trips, unique and NOT NULL enforcement, row locks and transaction rollback — and the job blocks a merge when it fails. The bulk of the ORM suite still runs on SQLite, so the Postgres path is covered more narrowly than the default one. | | MySQL | Supported, hardening. The same smoke suite runs against a real MySQL 8 on every merge and blocks on failure. It is newer than the Postgres job and has found one defect already (`string()` was not indexable), so treat MySQL as verified in the paths the suite covers and less proven than PostgreSQL outside them. | Redis-backed drivers (cache, session, queue, broadcasting) build on `Bun.RedisClient` and are tested against the protocol surface it provides. ## Dependencies Zerotal keeps the third-party code it puts into your app as small as it can, and every package it does install has a stated reason. Where Bun or the web platform provides a feature, or the code is short enough to own, Zerotal writes it itself. A package that only some apps need is an optional peer and is not installed for you: you add it when you turn on the feature that needs it, and the feature's own page says which. The tables below mark the exceptions still under review. Installing `zerotal` brings in this third-party package, and what it depends on in turn: | Package | Comes with | Why every app gets it | | ----------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@js-temporal/polyfill` | `@zerotal/core` | Carbon, the date type, is built on Temporal, which Bun only ships itself from 1.4. Carbon loads it on Bun 1.3 alone, the first time it needs a date. It goes once the supported floor ships Temporal. | Flow apps also get these, through `@zerotal/flow` and `@zerotal/flow-ui`: | Package | Comes with | Why | | ---------------- | ------------------ | ------------------------------------------------------------------------------------------------------------ | | `typescript` | `@zerotal/flow` | The ahead-of-time component compiler reads TypeScript's syntax tree, which Bun's transpiler does not expose. | | `tailwind-merge` | `@zerotal/flow-ui` | Resolving conflicting Tailwind classes needs Tailwind's own class grammar, which a rewrite would let drift. | Flow's browser runtime is not on the list because nothing installs it. Alpine and the plugins Flow uses are built into the runtime when `@zerotal/flow` is published, and arrive as that one file, at the versions that release was built with — see [the client runtime](/docs/flow/performance#the-client-runtime). This list is checked: CI fails when a package gains a dependency that is not on it. The rules a package follows are in [Package Development](/docs/package-development#dependencies). How the packages are built and published — npm provenance, CI actions pinned by commit, the publish token held by one job, no install scripts — is on [Supply-Chain Security](/docs/supply-chain). ## Releases and versioning All `@zerotal/*` packages and `create-zerotal` share **one version line and publish lockstep** — a release publishes every package at the same version, in dependency order, from CI. Never mix versions across packages. - **What the numbers mean:** a **patch** is anything that does not break — a fix, and a feature too. A **minor** carries a breaking change. A **major** is an annual consolidation, cut each July. The [Upgrade Guide](/docs/upgrade#versioning) explains why the framework is versioned this way and describes the upgrade procedure; the [Release Notes](/docs/changelog) list what changed. - **What that costs you:** a caret range crosses a minor, so a project on `^1.10.0` takes 1.11.0 and its breaking change without being asked. Pin with a tilde if you would rather cross a minor deliberately. - **A break is never silent.** Every one is called out in the release notes as **BREAKING**, with the reason and the migration steps, and the version gets its own section in the Upgrade Guide. Ten have shipped so far — the `ComponentWith` / `BaseModelWith` removal in 1.3.0, Flow's `socket:` listener prefix in 1.7.2, the removal of Flow's `this.title(…)` in 1.7.3, SQLite foreign-key enforcement in 1.11.0, `countTokens` returning `number | null` in 1.11.2, the refusal to write a boolean into a text column in 1.12.0, and the removal of Flow's `Component.client(…)` alongside two retired aliases in 1.13.0, and `inertia.ssr` no longer registering `POST /__ssr` in 1.14.0, and the model timestamps `createdAt` / `updatedAt` / `deletedAt` being typed `Carbon` rather than `Date` in 1.15.0, and in 1.17.0 a group of changes to what an app must install: the passkey library and Alpine are no longer installed for you, a missing sharp or optional Zerotal package throws, and `.vue` pages need `@vue/compiler-sfc` 3.3. The same release moved the panels to Tailwind v4, gave Flow's route table its own URL, let passkey registration accept any authenticator, handed out Bun's own `Temporal` from Carbon, and changed how the ORM reads dates. - **One of those ten is in the wrong place, and it stays on the record.** 1.11.2 is a patch, and by the rule above a patch cannot carry a break. It did: the `countTokens` signature changed in the same release that promoted `@zerotal/ai` to `stable`, and the reasoning that allowed it — the package was still `experimental` when the change was made, earlier in that release — is not a distinction anyone installing 1.11.2 can observe. What they get is a patch that breaks. It is listed here rather than argued away, because a policy that quietly excuses its own exceptions is not one you can plan against. - **Provenance:** packages are published with npm provenance, so you can verify a tarball was built by this repository's release workflow rather than someone's laptop. - **Cadence:** releases ship when they are ready rather than on a calendar. Security fixes are released out of band — see the response windows in [SECURITY.md](https://github.com/zerotaldev/zerotal/blob/main/SECURITY.md). - **Supported versions:** fixes land on the latest minor of the current major. There is no long-term-support line yet; one will be declared when the project's adoption warrants maintaining two lines honestly rather than nominally. ## Maturity levels Each package declares a `maturity` field in its `package.json`, and the label is a contract, not a mood: - **stable** — the public API follows SemVer strictly. Anything importable that does not carry an `@internal` marker is covered by the compatibility promise, and its shape is snapshotted in the package's `api-surface.md`, which CI diffs on every change. - **beta** — the API is close to final and breaking changes are rare, called out in release notes with migration steps, but a minor release may still contain one. Production use is reasonable if you read release notes before upgrading. - **experimental** — no compatibility promise. The API may change or the package may be absorbed into another in any release. Build on it with your eyes open. ### A label below stable carries a review date An honest "experimental" is useful once and corrosive indefinitely: a package that has worn the label for a year is not being cautious, it is unowned. So each one below `stable` names the release by which it is reviewed, and the review has three outcomes — promote, keep with a new date and the reason, or withdraw. | Package | Level | Reviewed by | Why it is not `stable` yet | | ------------------- | ------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `@zerotal/settings` | `beta` | 1.20.0 | New. Its design comes from two production apps' hand-built versions, but no app has run this package yet. It graduates once one has. | Before `@zerotal/settings` arrived, nothing was below `stable`, and this table was empty. That is the outcome the mechanism is for: every date had been answered. `@zerotal/ai` was the last entry, `experimental` and due by 1.11.0. It was promoted in 1.11.2, and the precondition it carried was met rather than waived: it graduates in the release after its first real users, and its first production users sent a field review of the driver against Anthropic. That review is why the promotion is worth anything — five bugs came back with it, and a `stable` promise about an API nothing has pushed against is a promise nobody has tested. The order was deliberate. Its surface was narrowed **before** the label, because narrowing after `stable` is itself a breaking change: `toSchema`, `strippedConstraints`, `resetSpend` and `resetStats` are `@internal` now. `translateSchema` stayed public despite having no caller outside the package, for the same reason `AiDriver` did — the whole point of a driver contract is that someone else implements it, and implementing structured output requires translating a schema. Then its two riskiest modules were tested: the SSE parser, which reads a remote provider's framing off the network, and prompt redaction, which is the only thing between a user's prompt and a log that outlives the request. `@zerotal/arch` held `beta` with the same date, was reviewed ahead of it, and is `stable` — the release that carried the promotion is the one its [changelog](/docs/changelog) names. Its surface was narrowed first too: the writers behind `arch:install` are `@internal`, because they had no caller outside the package and freezing them would have promised the shape of `.mcp.json` writing to nobody. Neither `ai` nor `arch` is in the `zerotal` meta-package. `arch` stays out because `arch:install` writes configuration and instruction files into a project, which is an opinion about someone's toolchain. A new app from `create-zerotal` does get it, with the files already written, because an agent that is never told what the framework ships tends to write its own. One flag, `--no-agent`, declines it, and an existing app still adds it only by choice. `ai` stays out for its own reason rather than by omission: it is the only package with an optional peer on a vendor SDK, and pulling it into the meta-package would put a provider dependency in front of every app that installs `zerotal`, including the ones with no AI in them. That table used to be the whole of the commitment, which meant the version could sail past it and the only consequence would be this paragraph quietly becoming untrue. The review release now lives in each package's `package.json` as `maturityReview`, and the package-conventions gate fails once the version reaches it — so the deadline is a build failure rather than a promise. A package is never more mature than what it is built on: a stable package whose foundation can change under it is not stable, whatever its own label says. So `@zerotal/admin` and `@zerotal/monitor` cannot pass `@zerotal/flow`, and the maturity of your app is the lowest level among the packages it actually uses. ## Deprecation policy In stable packages, an API is never removed in the release that deprecates it: deprecation lands in a minor release (a `@deprecated` marker with the replacement named, and a runtime warning where one is practical), the API keeps working for the remainder of the major line, and removal happens at the next major. Release notes list every deprecation and every removal. ## Getting help - **Bugs and feature requests** — [GitHub issues](https://github.com/zerotaldev/zerotal/issues). - **Security vulnerabilities** — privately, per [SECURITY.md](https://github.com/zerotaldev/zerotal/blob/main/SECURITY.md); never in a public issue. - **Contributing** — the [Contribution Guide](/docs/contributing). --- Source: https://zerotal.dev/docs/supply-chain # Supply-Chain Security What you install when you install Zerotal, who built it, and what runs on your machine while you do. Each claim on this page names the file or command that proves it, so it can be checked rather than taken on trust. The [Support Policy](/docs/support-policy) covers runtime and database support; vulnerability reports go through [SECURITY.md](https://github.com/zerotaldev/zerotal/blob/main/SECURITY.md). ## Published with provenance Every package is published from this repository's release workflow (`.github/workflows/release.yml`) with `npm publish --provenance`, never from a maintainer's machine. npm records a signed attestation linking each tarball to the commit and the workflow run that built it. ```bash npm audit signatures # in your app: verifies the signatures and attestations npm view @zerotal/core dist.attestations # the SLSA provenance record for that version ``` Publishing authenticates with npm trusted publishing where a package is linked to the workflow: its OIDC identity is exchanged for a short-lived token scoped to that package. A long-lived `NPM_TOKEN` repository secret still exists, for two reasons: the publish step falls back to it for a package not yet linked, and `npm deprecate` cannot use trusted publishing at all. Only those two jobs reference it — one runs on a release tag, the other only when started by hand — and no workflow a pull request triggers can read it. ## CI that cannot be redirected The npm worms of 2026 spread through CI: an action's version tag was moved to a malicious commit, and every workflow that named the tag ran it on its next build — including the ones holding publish credentials. Zerotal's workflows close each step of that path, and `bun run workflows:check` fails a pull request that reopens one: - **Every action is pinned to a full commit SHA**, with its version in a comment (`uses: actions/checkout@ # v5.1.0`). A tag can be moved; a commit cannot. Dependabot proposes pin updates weekly as reviewable pull requests. - **No `pull_request_target`.** No workflow runs a fork's code with this repository's secrets or a write token. - **`id-token: write` is granted to one job**, the one that publishes. The gates that install and run the whole dependency tree before it hold a read-only token. - **Every workflow starts read-only** (`permissions: contents: read`) and widens per job. - **The release re-runs every gate** before anything is published, and pull requests run the same gates, so a release cannot be the first time a check runs. The workflows a new app gets from `create-zerotal` follow the same rules. ## First-party batteries Auth, sessions, the ORM and its migrations, queues, the scheduler, mail and notifications, caching, validation, storage, broadcasting, an admin panel, the live-component layer and the test kit are all written in this repository and released together at one version. An app built on them installs code from one source with one release process, instead of one package per feature from as many maintainers. Third-party code the framework needs at runtime, per package: | Package | Third-party `dependencies` | | ----------------------------------- | ------------------------------------------- | | `@zerotal/core` | `@js-temporal/polyfill` (which adds `jsbi`) | | `@zerotal/flow` | `typescript` (compiles component templates) | | `@zerotal/flow-ui` | `tailwind-merge` | | every other `@zerotal/*`, `zerotal` | none | | `create-zerotal` | none | Anything else is an optional peer dependency, installed only by an app that uses that feature: `sharp` for image processing in `@zerotal/media`, `@simplewebauthn/server` for passkeys in `@zerotal/auth`, the Inertia adapters, and the AI SDK in `@zerotal/ai`. The dependency rules each package follows are in [Package Development](/docs/package-development#dependencies), and `bun run deps:check` holds every package to them. To see exactly what an app has installed from the framework: ```bash bun zt about ``` ## No install scripts No Zerotal package declares a `preinstall`, `install`, `postinstall` or `prepare` script, so installing one runs no code. The same is true of the third-party packages in the table above, with one detail worth stating exactly: `@js-temporal/polyfill` has a `prepare` script, which package managers run only when building it from its git source, not when installing the published tarball. Bun also runs no dependency's lifecycle scripts unless the app lists it under `trustedDependencies`; none of the starters do. Check it yourself: ```bash for f in node_modules/zerotal/package.json node_modules/@zerotal/*/package.json; do grep -H -E '"(pre|post)?install"|"prepare"' "$f" done # prints nothing ``` ## A lockfile every supported Bun can read `bun.lock` is committed and every workflow installs with `--frozen-lockfile`, so CI and the release build install exactly the versions that were reviewed. `bun run lockfile:check` keeps the file in the format the oldest supported Bun reads, so a newer Bun cannot silently rewrite it. --- Source: https://zerotal.dev/docs/contributing # Contribution Guide Zerotal is a Bun-native monorepo of composable packages. This guide covers getting the repo running locally, the project layout, and the checks your change needs to pass. > **Warning** — Bun ≥ 1.3.14 is required. Node.js is not supported; Zerotal uses `Bun.sql`, `Bun.CryptoHasher`, `Bun.build`, and other Bun-native APIs throughout. ## Getting set up ```bash # in your project root git clone zerotal cd zerotal bun install # installs all workspaces ``` The repo is a Bun workspace (`packages/*` and `apps/*`), so a single `bun install` at the root wires every package together via `workspace:*` links. Change dependencies with Bun 1.3.x. Bun 1.4 rewrites `bun.lock` in a format Bun 1.3.14 cannot read, and CI, the release workflow and the docs server all install with 1.3.14. `bun run lockfile:check` fails on a rewritten lockfile; restore the committed one and run `bun install` again with Bun 1.3.x. ## Repository layout ```text # repo root packages/ # the framework — one directory per @zerotal/* package core/ # IoC container, Application, router, HTTP pipeline, events, config orm/ # models, migrations, query builder, relationships auth/ cache/ queue/ … # feature packages testing/ # factories, fakes, test app harness create-zerotal/ # the `bun create zerotal` scaffolder apps/ # applications in this workspace docs/ # this documentation site docs/ # the markdown documentation (what you're reading) ``` Each package owns its own `src/`, tests (`*.test.ts`), and `package.json`. ## The `@zerotal/core` public surface `@zerotal/core` is deliberately split so importing the kernel doesn't drag in heavy or rarely-used subsystems. The root barrel (`@zerotal/core`) exports **only the lean kernel** — `Application`, the container, `RequestContext`, `HttpContext`/`Pipeline`, providers, errors, events, the router, middleware, facades, `Command`, and the common helpers. Everything else lives behind an explicit subpath: ```text @zerotal/core # kernel: Application, Router, HttpContext, Container, errors, events, middleware, helpers @zerotal/core/carbon # Carbon + intervals (pulls the Temporal polyfill — kept out of the kernel) @zerotal/core/http # outbound Http client, URL building/signing, uploads, API Resource, negotiation @zerotal/core/view # server-side JSX runtime + authoring helpers (SafeHtml, definePage, …) @zerotal/core/env # typed environment schema (EnvSchema, t, Def) @zerotal/core/config # ConfigManager/Loader + app config shapes (AppConfig, AppAssetsConfig, …) @zerotal/core/security # Crypt + Hash @zerotal/core/dev # dev-only build/reload tooling (owns Bun.build — inactive outside the dev worker) @zerotal/core/assets # asset() URL helper + versioning @zerotal/core/health # health checks @zerotal/core/metrics # HTTP request metrics ``` Rule of thumb when adding a public export to core: - **Kernel** (hot, cheap, needed almost everywhere) → add it to `src/index.ts`, and add the name to the frozen list in `src/index.barrel.test.ts` (a deliberate, reviewed decision). - **Belongs to a subsystem** (a specific concern, or it pulls a heavy dependency) → export it from that subpath's `src//index.ts` and register the subpath in `package.json` `exports`. Do **not** add it to the root barrel. The `core barrel surface` guard test (`src/index.barrel.test.ts`) fails if the root barrel grows or shrinks unexpectedly — that's the signal to pick one of the two paths above on purpose, so the barrel never drifts back into a god-module. ## Everyday commands Run from the repo root — they fan out across every workspace via `bun --filter`: ```bash # in your project root bun test # run all package test suites bun run typecheck # type-check every package bun run lint # eslint bun run format # prettier --write bun run build # build every package ``` To work on a single package, run its script directly inside it: ```bash # in your project root cd packages/orm bun test # just the ORM suite bun test src/db/QueryBuilder.test.ts # a single file ``` > **Note** — tests run on Bun's built-in runner. Most database tests use SQLite (`:memory:` or a temp file), so they need no external services. ## Making a change 1. **Branch** off the default branch. 2. **Write the code and tests.** New behavior needs test coverage; bug fixes should add a regression test. Match the style of the surrounding code. 3. **Keep the public API typed.** Exported functions and classes should have accurate types — the `typecheck` task gates this. 4. **Run the checks** before pushing: ```bash # in your project root bun run typecheck && bun test && bun run lint ``` 5. **Update the docs.** If you change or add public API, update the relevant page under `docs/` (and the nav in `apps/docs/app/routes/_layout.ts` if you add a page). ### Tests restore anything process-global Bun runs a package's test files in **one process**, and the preload is evaluated once per worker, not once per file. So a global a test writes is still there for every file that runs after it: `Bun.env` keys, `globalThis.fetch` or `globalThis.document`, and framework module state set through the `_set*` helpers. Put it back. `beforeEach` captures, `afterEach` restores — and restore in a `finally` or an `afterEach`, never at the end of the test body, or a failing assertion skips the restore and takes the rest of the suite with it. ```ts fragment let saved: string | undefined; beforeEach(() => { saved = Bun.env["APP_ENV"]; Bun.env["APP_ENV"] = "production"; }); afterEach(() => { if (saved === undefined) delete Bun.env["APP_ENV"]; else Bun.env["APP_ENV"] = saved; }); ``` This is worth its own rule because **the damage never lands where the mistake is**. The file that fails is whichever ran next, and which file that is depends on directory order — alphabetical on Windows, arbitrary readdir order on Linux. So a leak passes locally for months and reddens CI on an unrelated commit. Five of these were found in one week, each written by someone who had tested their own file in isolation and seen it pass. If a CI-only failure lands in a package your change did not touch, suspect a leaked global before suspecting your diff. To reproduce the order locally, rename the file you think runs second so it sorts last — passing paths to `bun test` explicitly does not work, because Bun re-sorts them. ## Documentation changes The docs are markdown files in `docs/`, served by the docs app in `apps/docs`. A page's URL is its path: `docs/query-builder.md` → `/docs/query-builder`, and `docs/orm/casts.md` → `/docs/orm/casts` (a directory's `index.md` serves the bare slug). To add a page, create the markdown file and add an entry to the `NAV` array in `apps/docs/app/routes/_layout.ts`. When documenting an API, verify it against the package source rather than memory — accuracy is the priority. ### One page, one subject A page documents its own subject and nothing else. When a feature belongs to another area, link to the page that owns it instead of re-explaining it here — a second copy drifts out of date, and the reader who needs the detail is better served by the page that keeps it complete. - **Own it or link it.** Route-model binding is explained in [Routing](/docs/routing); every other page states that the model arrives resolved and links there. `HttpContext` members belong to [Requests & Context](/docs/context), not to whichever guide happens to show a handler. - **Show the default, not the override.** If a param binds implicitly, the example registers a plain route. Configuration that only exists for the non-default case belongs on the page that owns the mechanism. - **Prefer a pointer to a paraphrase.** One sentence naming the behaviour plus a link beats a condensed re-teaching that will disagree with the source page after the next change. - **Package-authoring material goes to [Package Development](/docs/package-development)** — macros, driver contracts, and provider internals are not app-builder documentation. The same rule governs a page's own length: a section that has grown into a second subject is a sign it wants to be its own page, or to move to the one that owns it. ### Code examples are compiled Every TypeScript block in `docs/` is compiled against the real packages by `bun run docs:examples:check`, which CI runs on every pull request. An example that names a member the API no longer has fails the build rather than waiting for a reader to find it. Plenty of blocks are not whole programs on purpose — a class body, a set of columns, a method shown without the class around it. Say so in the fence: ````text ```ts fragment @column("string") name!: string; @column("boolean") active!: boolean; ``` ```` `fragment` works on `ts`, `tsx` and `typescript`, and readers never see it: a fence's info string carries only its first word into the rendered page. It is never guessed — a block is a fragment because you wrote that it is, and a run of `bun run docs:examples` records it so a new one is a deliberate change rather than a silent exemption. Two lists back that up. `fragments` in `docs-examples-baseline.json` are the intentional ones. `drift` is the other kind: a block that resolves every import and still fails, which means the page is wrong. Neither list may grow, and `drift` is meant to reach zero. ## Changelogs Each package keeps its own `CHANGELOG.md`. Add what you changed under `## [Unreleased]` in the package you changed — that is where in-flight work belongs, and the entry travels with the code rather than being reconstructed later. Cutting a release moves those entries under the version, which is a step and not an automatic consequence: ```bash bun run changelog:release 1.7.4 ``` Skipping it is how `[Unreleased]` came to hold four releases of shipped work — `@zerotal/flow-ui`'s newest heading read `[1.5.0]` while 1.7.3 was on npm. Someone upgrading reads "Unreleased" and concludes none of it is in the version they are taking, when all of it is. ## Publishing A release is a tag. Pushing `v1.7.4` runs the release workflow (`.github/workflows/release.yml`), which re-runs every gate and then publishes each public package with `scripts/publish-packages.ts`. Nothing is published from a laptop. ### Trusted publishing npm authenticates each package with trusted publishing: it trades the release workflow's GitHub identity for a token that lasts one publish and covers one package. A package that is not linked yet falls back to the `NPM_TOKEN` repository secret, which expires. The publish log prints which path each package took, ending with a line such as `27 via trusted publishing, 0 via NODE_AUTH_TOKEN`. Link every package whose `package.json` is not `"private": true`. On npmjs.com, open the package, then **Settings**, then **Trusted publishing**, and choose **GitHub Actions**: - **Organization or user:** `zerotaldev` - **Repository:** `zerotal` - **Workflow filename:** `release.yml` (the file name only, not the path) - **Environment name:** leave it empty; the publish job uses no environment - **Allowed actions:** allow `npm publish`, because the workflow publishes directly rather than staging npm 11.15.0 or later does the same from a terminal, signed in to an account with two-factor authentication and write access to every package: ```bash # in your project root for manifest in packages/*/package.json; do name=$(bun -e "const m = require('./$manifest'); if (!m.private) console.log(m.name)") [ -n "$name" ] && npm trust github "$name" --file release.yml --repo zerotaldev/zerotal --allow-publish done ``` > **Warning** — npm checks nothing when you save. A link that has not published > within two days expires and has to be deleted and created again, so link the > packages shortly before tagging. An expired or mistyped link fails quietly: the > package publishes with the token, and the publish log says why. Delete the `NPM_TOKEN` secret only after a release reports every package via trusted publishing. Publishing no longer needs it then, but the deprecate workflow (`.github/workflows/deprecate.yml`) does, because npm has no trusted path for `npm deprecate`. Without the secret, deprecate from a terminal with the same loop, running `npm deprecate "$name@" ""` in place of `npm trust`. ## Pull requests - Keep PRs focused — one logical change per PR. - Describe what changed and why; link any related issue. - Make sure CI is green (`typecheck`, `test`, `lint`). - Note any breaking change clearly so it can be captured in the [Release Notes](/docs/changelog). ## Next steps - [Package Development](/docs/package-development) — building a `@zerotal/*`-style package. - [Testing](/docs/testing) — the test harness, factories, and fakes. - [Upgrade Guide](/docs/upgrade) — how releases are versioned. --- Source: https://zerotal.dev/docs/getting-started # Getting Started Zerotal is a full-stack framework for [Bun](https://bun.sh). This guide walks you from a blank machine to a running app with a route, a model, and a service provider. ## Requirements - **Bun** ≥ 1.3.14 — [install](https://bun.sh/docs/installation) - A database, unless you scaffold the **Minimal** template. Every other template is configured for **SQLite**, which needs nothing installed — PostgreSQL and MySQL are supported and are a `DATABASE_URL` away. ### One project, one Bun `engines.bun` is a floor, not a lock, and nothing in npm enforces it. A project can end up with two runtimes in it without anyone choosing that: the shell's `bun`, and a different one in `node_modules/bun`, put there by a transitive peer dependency nobody declared. The work then splits between them — the server served by one, the suite run by the other — and nothing says so. That is expensive because the difference is real but narrow. The SQLite bindings, `node:` compatibility and the test runner itself all change between releases, so a couple of assertions happen to be runtime-sensitive and the rest are not. When those two fail you go looking for a bug in the code they touch. And a suite that passes is not evidence either: it only means no test happened to stand on a difference. So **`zt` refuses to run when the two disagree**: ``` Two Bun runtimes are in play. This process is Bun 1.3.14, but the project installs Bun 1.4.0 (/srv/app/node_modules/bun/package.json). ``` This is not a pin. The version to agree on is whichever one the project installed, so `bun update bun` moves it and nothing needs editing — what is enforced is that there is only one. Fix it either way: ```bash bun update bun # move the installed one to match your shell node_modules/.bin/bun # or run everything through the installed one ``` Most projects never see this, because most have no `bun` in `node_modules` to disagree with. To boot anyway — mid-upgrade, say — set `ZT_ALLOW_RUNTIME_MISMATCH=1`, which downgrades the refusal to a warning. The refusal is a `RuntimeMismatchError`, which carries both versions in its `context` for anything scripting around it. `zt test` spawns the binary running it, not whatever `bun` resolves to on `PATH`, so the suite runs on the runtime the guard just checked. ## Create a new project ```bash # in your project root's parent directory bun create zerotal my-app # or: bunx create-zerotal my-app cd my-app ``` The scaffolder prompts for a project name and a template, then generates a ready-to-run project and installs dependencies. The **database** prompt only appears for the API template: | Prompt | Options | | ------------ | ---------------------------------------------------------------------------- | | Project name | Defaults to `my-zerotal-app` | | Template | **API**, **Admin**, **Flow**, **React**, **Vue**, or **Minimal** (see below) | | Database | **SQLite** (zero setup), **PostgreSQL**, or **MySQL** — asked for **API** | It writes a fresh `APP_KEY` into the generated `.env.example` for you (no manual generation needed). For Postgres/MySQL it reminds you to set `DATABASE_URL` before migrating. ### Without a terminal — CI, scripts, agents Every prompt has a flag, and the scaffolder never asks a question when there is no TTY to answer it: ```bash bunx create-zerotal my-app --template=api --db=postgres --no-install bunx create-zerotal my-app --yes # take the defaults for anything unset bunx create-zerotal --help ``` | Flag | Values / description | | ------------------------- | -------------------------------------------------- | | `-t`, `--template ` | `api`, `admin`, `flow`, `react`, `vue`, `minimal` | | `--db ` | `sqlite`, `postgres`, `mysql` — API template only | | `-y`, `--yes` | Take defaults for anything not given; never prompt | | `--no-install` | Skip `bun install` | | `--no-agent` | Leave out the coding-agent files (see below) | | `-h`, `--help` | Usage | | `-v`, `--version` | The scaffolder's own version | An answer that is missing and cannot be asked for is an error naming the flag that would supply it, and the exit code is non-zero — so a pipeline fails where it used to wait. A failed `bun install` also exits non-zero when there is no terminal: a half-built project that reports success is worse than one that stops. ### Which template should I use? - **API** — JSON REST API with core, [ORM](/docs/orm), [auth](/docs/authentication), [validation](/docs/validator), and [testing](/docs/testing). The default for a backend service. - **Admin** — an [admin panel](/docs/admin): resources, sign-in, dashboard widgets, and seeded demo data. `bun zt db:seed` gives you an account to log in with. - **React**, **Vue** or **Flow** — a full first app, the same in all three: a signed-in shell with a dashboard, [sign-in](/docs/authentication) with email verification and two-factor, a Settings section, an example `Project` resource and feature tests. React and Vue render their pages through [Inertia](/docs/inertia); Flow renders [Flow](/docs/flow) pages on the server. `bun zt db:seed` creates `demo@example.com` / `password` with sample projects. - **Minimal** — a single page with JSX views and Tailwind on the bare framework. > **Note** — every template except **Minimal** ships a database config and migrations, > configured for SQLite. Only the **API** template _asks_ which database you want; the > rest start on SQLite and switch when you set `DATABASE_URL`. ### Coding agents Every template is set up for a coding agent. `AGENTS.md` tells it how the app is built and what the framework already ships, `.mcp.json` connects it to the [agent surface](/docs/arch) for exact signatures, routes, schema and these docs, and a few skills cover common tasks step by step. Restart your agent after scaffolding so it picks up the MCP server. `--no-agent` leaves all of it out. ## Project structure The **API** template generates the following. Other templates vary (SPA templates add a `resources/` frontend, for example): ``` # my-app/ (API template) my-app/ ├── app/ │ ├── controllers/ # HTTP controllers │ ├── middleware/ # Custom middleware │ └── models/ # ORM models (auto-discovered) ├── bootstrap/ │ └── app.ts # Builds the Application (providers + routing) ├── config/ # Config files (database, session, queue…) — auto-loaded ├── database/ │ └── migrations/ # Database migrations ├── routes/ │ └── index.ts # Route definitions ├── tests/ # Test suites ├── zt.ts # Managed CLI entry point — do not edit └── .env # Environment variables (git-ignored) ``` `zt.ts` is the entry point for **everything** — `bun zt serve`, `migrate`, `test`, and every `make:*` generator run through it. It boots `bootstrap/app.ts`, which defines your [Application](/docs/application). Anything under `app/models/`, `app/providers/`, and `config/` is [auto-discovered](/docs/conventions) at boot — no manual registration. > **Tip** — `app/providers/` is auto-discovered when present. The API template > doesn't generate one; run `bun zt make:provider …` and the framework picks it > up at boot. ## Environment setup The scaffolder writes a `.env` with a freshly generated `APP_KEY`, so a new app boots straight away; there is nothing to copy. `.env` is git-ignored. `.env.example` is the copy you commit, and it holds placeholders on purpose: on another machine, copy it to `.env` and run `bun zt key:generate` to fill the key in. ```ini # .env APP_ENV=development APP_KEY=… # generated for you; rotate with `bun zt key:rotate` DATABASE_URL=./database/db.sqlite SESSION_SECRET=… # API template: generated for you; set your own before deploying ``` The database is configured with a single **`DATABASE_URL`** — SQLite uses a file path, Postgres/MySQL use a connection string: ```ini # .env — alternative DATABASE_URL forms # DATABASE_URL=postgres://user:pass@localhost:5432/my_app # DATABASE_URL=mysql://root@localhost:3306/my_app ``` > **Danger** — Change `SESSION_SECRET` before deploying. The placeholder value is > not safe for production. See [Configuration](/docs/config-system) for the full config system. ## Run migrations ```bash # in your project root bun zt migrate ``` ## Start the dev server ```bash # in your project root bun zt dev ``` Every command in these docs is written `bun zt `. The scaffold also adds a `dev` script, so `bun run dev` does the same thing — reach for whichever you prefer. Your app is now running at **http://localhost:3000** with hot reload enabled — `dev` watches your files and hot-swaps routes without dropping connections. The generated `package.json` also gives you `bun start` (production serve) and `bun test`. ## Your first route Open `routes/index.ts` and add: ```typescript fragment // routes/index.ts import { Router } from "zerotal"; import { PostController } from "../app/controllers/PostController.ts"; Router.get("/posts", PostController, "index"); Router.post("/posts", PostController, "store"); ``` Create the controller: ```typescript // app/controllers/PostController.ts import type { HttpContext } from "zerotal"; export class PostController { async index(ctx: HttpContext) { return ctx.json({ posts: [] }); } async store(ctx: HttpContext) { const body = await ctx.request.json(); return ctx.json({ created: body }, 201); } } ``` > **Note** — Every controller action receives the request > [HttpContext](/docs/context) directly. Read route params and resolved model > bindings from `ctx.params`; type them with the generic, e.g. > `ctx: HttpContext<{ post: Post }>`. ## Your first model ```bash # in your project root bun zt make:model Post --migration ``` This generates `app/models/Post.ts` and a migration for the same table, `NNN_create_posts_table.ts` in `database/migrations/`, where `NNN` is the next free number. Models in `app/models/` are auto-discovered at boot — no manual registration, and the table name is derived by convention (`Post` → `posts`), so `@table` is optional; the generated model states it anyway, and the migration creates exactly that table. The same applies to observers, policies, and event listeners; see [Conventions](/docs/conventions). Both start with a single `name` column. Open the migration and define your own: ```typescript // database/migrations/xxxx_create_posts_table.ts import { Migration, Schema } from "@zerotal/orm"; export default class CreatePostsTable extends Migration { async up(): Promise { await Schema.create("posts", (table) => { table.increments("id"); table.string("title"); table.text("body"); table.string("slug").unique(); table.timestamps(); }); } async down(): Promise { await Schema.drop("posts"); } } ``` Then update `app/models/Post.ts` to match: declare each column with `@column()` and list the ones a form may set in `fillable` (see [Models](/docs/orm)). Run it: ```bash # in your project root bun zt migrate ``` Your model is ready to use: ```typescript fragment // in a controller or service import { Post } from "../models/Post.ts"; const posts = await Post.query().latest().limit(10).get(); const post = await Post.find(1); const fresh = await Post.create({ title: "Hello", body: "...", slug: "hello" }); ``` ## Adding a service provider Providers are where you wire up your own bindings. Scaffold one: ```bash # in your project root bun zt make:provider AppServiceProvider ``` ```typescript fragment // app/providers/AppServiceProvider.ts import { ServiceProvider } from "zerotal"; import { PaymentGateway } from "../services/PaymentGateway.ts"; import { StripeGateway } from "../services/StripeGateway.ts"; export class AppServiceProvider extends ServiceProvider { onRegister(): void { this.app.container.singleton( PaymentGateway, () => new StripeGateway({ key: Bun.env.STRIPE_KEY! }), ); } } ``` Anything under `app/providers/` is **auto-discovered and registered at boot** — no manual wiring needed. You only touch `bootstrap/app.ts` when you need to control _ordering_ (e.g. one provider must register before another). See [Service Providers](/docs/providers) and [Conventions](/docs/conventions). ## Available commands Everything runs through `zt.ts`. The most common: ```bash # in your project root bun zt make:model Name --migration # model + migration bun zt make:controller Name # controller class bun zt make:middleware Name # middleware class bun zt make:provider Name # service provider bun zt make:job Name # queue job bun zt migrate # run pending migrations bun zt migrate:rollback # roll back last batch bun zt migrate:status # show migration status bun zt migrate:fresh # roll back all + re-migrate bun zt key:generate # generate a fresh APP_KEY bun zt queue:work # start the queue worker ``` There are many more (`make:policy`, `make:factory`, `make:seeder`, `make:page`, `db:seed`, `schedule:list`, …). Run `bun zt list` to see them all, or see [Commands](/docs/commands) for the full list and [Scaffolding](/docs/scaffolding) for what each generator produces. ## Next steps - [Routing](/docs/routing) — route definitions, groups, parameters, and file-based routes. - [Controllers](/docs/controllers) — move route logic into classes. - [ORM](/docs/orm) — models, queries, and relationships. - [Configuration](/docs/config-system) — how config and auto-discovery work. - [Flow](/docs/flow) — server-driven reactive UI (or [Inertia](/docs/inertia) for a React/Vue SPA). --- Source: https://zerotal.dev/docs/what-ships # What Ships Before you build something an app commonly needs, check whether the framework already does it. Each line below links to the page that covers it and says where it comes from: - **Built in** — part of the kernel every app has. - **Included with `zerotal`** — one of the packages the `zerotal` bundle installs. Every starter depends on it. - **Add `@zerotal/…`** — a separate package. Install it with `bun add`. A coding agent working in your app gets the same list in `AGENTS.md`, marked against what the app has installed. See [Agent Surface](/docs/arch). ## Accounts and access - **[Multi-tenancy](/docs/tenancy)** — tenant resolvers and tenant-scoped models. Add `@zerotal/tenancy`. - **[Roles and permissions](/docs/authorization)** — the `Roles` and `Permissions` model mixins, `Auth.can()`. Included with `zerotal`. - **[Policies](/docs/authorization)** — policy classes in `app/policies/`, discovered automatically. Included with `zerotal`. - **[Two-factor sign-in](/docs/roles-and-2fa)** — TOTP codes and recovery codes. Included with `zerotal`. - **[Passkeys, magic links, email codes](/docs/authentication)** — `PasskeyService` and passwordless login. Included with `zerotal`. - **[Sign in with GitHub, Google or Apple](/docs/social)** — OAuth drivers. Included with `zerotal`. - **[Password reset](/docs/password-reset)** — `PasswordBroker`. Included with `zerotal`. - **[Email verification](/docs/email-verification)** — signed links and `ValidateSignatureMiddleware`. Included with `zerotal`. - **[An audit trail](/docs/audit)** — the `Auditable` mixin and manual audit events. Add `@zerotal/audit`. ## Data - **[Caching](/docs/cache)** — SQLite, Redis and memory drivers with tags. Included with `zerotal`. - **[Locks across processes](/docs/lock)** — `zerotal/lock`. Built in. - **[Database backups](/docs/commands)** — `bun zt db:backup` (SQLite). Built in. - **[Seed and demo data](/docs/seeding)** — seeders and model factories. Built in. - **[Validation](/docs/validator)** — `FormRequest` classes and `validate()`. Included with `zerotal`. ## Files - **[File uploads and image conversions](/docs/media)** — media attached to models. Included with `zerotal`. - **[File storage](/docs/storage)** — local and S3-compatible disks. Built in. ## Messages and background work - **[Mail, SMS and in-app notifications](/docs/notifications)** — notification classes, one per message. Add `@zerotal/notifications`. - **[Background jobs](/docs/queue)** — job classes and a worker, on the app's own database (SQLite, PostgreSQL, MySQL) or Redis. Included with `zerotal`. - **[Scheduled tasks](/docs/scheduler)** — `Schedule` classes in `app/schedules/`. Included with `zerotal`. ## Product features - **[An admin panel](/docs/admin)** — declarative resources, tables, forms and dashboards. Add `@zerotal/admin`. - **[Per-tenant settings](/docs/settings)** — typed defaults in code with tenant and user overrides, hidden not deleted, audited, with an admin screen. Add `@zerotal/settings`. - **[Realtime updates](/docs/broadcasting)** — authorised broadcast channels. Add `@zerotal/broadcasting`. - **[Translations](/docs/i18n)** — `__()` with plurals and per-request locale. Add `@zerotal/i18n`. - **[Calls to a language model](/docs/ai)** — `Ai.text()`, `Ai.object()`, `Ai.agent()`. Add `@zerotal/ai`. ## Security and operations - **[Rate limiting](/docs/rate-limiting)** — `ThrottleMiddleware` and named limiters. Built in. - **[Encryption and hashing](/docs/encryption)** — encrypt, hash and sign helpers. Built in. - **[Maintenance mode and a pre-launch gate](/docs/site-gate)** — the site gate. Built in. - **[Health checks](/docs/health)** — a `/health` endpoint with your own checks. Built in. - **[A production dashboard](/docs/monitor)** — requests, jobs, errors and alerts. Add `@zerotal/monitor`. - **[Tracing](/docs/telemetry)** — spans with OTLP export. Add `@zerotal/telemetry`. ## Testing - **[Tests against a booted app](/docs/testing)** — `createTestApp()`, factories and fakes. Included with `zerotal`. --- Source: https://zerotal.dev/docs/structure # Directory Structure A freshly scaffolded Zerotal app organizes code into predictable directories, most of which are auto-discovered and wired by convention so you rarely touch the bootstrap files. ```text # project root my-app/ ├── app/ │ ├── controllers/ │ ├── events/ ← event classes (auto-discovered) │ ├── exceptions/ │ │ └── Handler.ts │ ├── jobs/ │ ├── listeners/ ← event listeners (auto-discovered) │ ├── middleware/ │ ├── models/ ← ORM models (auto-discovered) │ ├── observers/ ← model observers (auto-discovered) │ ├── policies/ ← authorization policies (auto-discovered) │ ├── providers/ │ │ └── AppServiceProvider.ts │ ├── flow/ ← Flow Pages (server-driven UI) │ │ └── pages/ │ └── requests/ ← FormRequest validation classes ├── bootstrap/ │ ├── app.ts ← Application bootstrap │ └── providers.ts ← Provider registry ├── config/ │ ├── app.ts │ ├── database.ts │ ├── mail.ts │ └── ... ├── database/ │ ├── migrations/ │ ├── seeders/ │ └── factories/ ├── docs/ ← Optional: serve with Router.markdown() ├── public/ ← Static assets │ └── uploads/ ├── resources/ │ └── views/ ← JSX / TSX view components ├── routes/ │ └── index.ts ← Explicit route definitions ├── tests/ │ ├── Feature/ │ └── Unit/ ├── .env ├── .env.example ├── bun.lockb ├── package.json └── zt.ts ← CLI entry point (don't edit) ``` ## Key directories ### app/ Application code lives here. Zerotal uses no magic autoloading — you import what you need explicitly, so names and locations are entirely up to you. **`app/controllers/`** — HTTP controller classes. Each method maps to a route action. Name them freely; the framework just needs the class and method name at `Router.get('/path', MyController, 'method')`. **`app/exceptions/Handler.ts`** — your custom exception handler. Extends `ExceptionHandler` from `zerotal`. Registered in `bootstrap/app.ts` via `app.withExceptionHandler(Handler)`. **`app/jobs/`** — background job classes for `@zerotal/queue`. **`app/middleware/`** — custom middleware classes implementing `Pipe`. **`app/models/`** — ORM model classes extending `Model` from `@zerotal/orm`. Auto-discovered at boot; the table name is derived by convention, so `@table` is optional. **`app/providers/`** — service providers for registering custom bindings and booting application services. **`app/flow/pages/`** — Flow Component classes. When using file-based routing these are scanned automatically and registered as reactive WebSocket routes. **`app/requests/`** — FormRequest validation classes. Group by domain: `app/requests/posts/StorePostRequest.ts`. Providers, middleware, observers, policies, listeners, events, jobs, and validators are all auto-discovered and wired by convention. Providers run their full lifecycle without being listed in `bootstrap/providers.ts`; middleware registers as a named group (reference it by class name, or set `static global = true`); observers and policies attach by name; listeners bind via `static listens`; jobs and validators self-register on import. No manual wiring — see [Conventions](/docs/conventions). ### bootstrap/ **`bootstrap/app.ts`** — the application singleton. Wires together exception handling, global middleware, and opt-in conventions: ```ts fragment // bootstrap/app.ts import { Application } from "zerotal"; import { DevtoolsInjectionMiddleware } from "@zerotal/devtools"; import { Handler } from "../app/exceptions/Handler.ts"; import providers from "./providers.ts"; export default Application.create({ providers }) .withExceptionHandler(Handler) .routing({ web: `${import.meta.dir}/../routes/index.ts` }) .fileBasedRouting({ web: `${import.meta.dir}/../app/routes` }) .use([DevtoolsInjectionMiddleware]); ``` Auth resolves the session user automatically from your registered `AuthUser` model — no `withUserResolver(...)` wiring. Override with `app.withUserResolver(...)` or `AuthProvider.resolveUsing(...)` only for custom logic. **`bootstrap/providers.ts`** — ordered list of provider classes. Registration order matters: providers lower in the list can depend on bindings from providers higher up. > **Note** — Most providers are auto-discovered from `app/providers/`. Use > `bootstrap/providers.ts` for the package providers you register explicitly and > when registration order is load-bearing. ### config/ Each file exports a typed config object (default export); an optional named `validate(config)` export is run at startup. The `zt.ts` entry point loads the whole directory synchronously with `configLoader("./config")` and injects it via `app.useConfig(config.all())`. Access at runtime via the `Config` [facade](/docs/container#facades) — a static accessor over a container binding — or typed per-package helpers. App-wide auto-discovery settings live under the `conventions` key of `config/app.ts` — see [Conventions](/docs/conventions) and the [Config system](/docs/config-system) for the full loading flow. ### database/ **`database/migrations/`** — migration files named `YYYY_MM_DD_HHMMSS_description.ts`. Run with `bun zt migrate`. **`database/seeders/`** — seeder classes for populating the database with test or default data. **`database/factories/`** — model factories used in tests and seeders. ### public/ Files placed here are served directly as static assets. Register the directory with `Router.static('/assets', './public/assets')` in `routes/index.ts`. ### routes/index.ts All explicit route registrations. This file runs after file-based routes are scanned, so explicit routes take precedence over file routes for the same path. ```ts fragment // routes/index.ts import { Router } from "zerotal"; import { PostController } from "../app/controllers/PostController.ts"; Router.get("/posts", PostController, "index").name("posts.index"); ``` ### zt.ts The universal CLI entry point managed by the framework. Do not edit. ```bash # in your project root bun zt serve # start HTTP server bun zt worker # start background worker bun zt migrate # run pending migrations bun zt route:list # list all routes bun zt make:model # scaffold a model bun zt list # all available commands ``` ## File-based routing directory If you call `app.fileBasedRouting({ web: "./app/routes" })`, that directory mirrors the URL structure of your app. See the [Routing](/docs/routing) guide for full details. ```text # app/routes/ — paths map to URLs app/routes/ index.ts → GET / about.ts → GET /about users/ index.ts → GET /users [id].ts → GET /users/:id, DELETE /users/:id [id]/ posts.ts → GET /users/:id/posts (api)/ _middleware.ts ← middleware for everything below status.ts → GET /status ``` ## Flow Pages directory Flow Pages have their own directory under `app/flow/pages/` (or wherever you point `fileBasedRouting`). The directory supports the same `(group)` and `[param]` conventions as file-based routes. A `_middleware.ts` file in any subdirectory applies to all Flow Pages below it. ```text # app/flow/pages/ — Flow routes app/flow/pages/ (auth)/ _middleware.ts ← GuestMiddleware — only guests see these login.tsx → /login register.tsx → /register (protected)/ _middleware.ts ← AuthMiddleware dashboard.tsx → /dashboard settings.tsx → /settings index.tsx → / ``` ## Next steps - [Conventions](/docs/conventions) — how Zerotal wires these directories by name. - [Config system](/docs/config-system) — how the `config/` directory is loaded. - [Routing](/docs/routing) — define routes in `routes/index.ts`. - [Lifecycle](/docs/lifecycle) — how `bootstrap/app.ts` boots the app. --- Source: https://zerotal.dev/docs/config-system # Configuration Zerotal separates three things: deployment state (`env()`), code-level structure (`config/*.ts`), and runtime access (`config()`). You only need all three when your config has genuine structure or conditional logic — simple apps can rely on `env()` alone. ## Mental model Think of configuration as a pipeline from the environment to your code: ``` .env / process env config/*.ts files anywhere in the app ────────────────── ───────────────── ─────────────────── env("PORT") ─────► AppConfig({ ... }) ─────► config("app.port") (raw strings) (typed structure) (typed dot-path read) ``` - `env()` pulls a single value out of the environment, coercing it to the type of your fallback. - A `config/.ts` file assembles those values into a typed object via a package helper (`AppConfig`, `DatabaseConfig`, …). - At boot, every `config/*.ts` file is loaded into the config store; `config()` reads from it by dot-path. > **Tip** — Reach for the next layer only when you need it. A value used in exactly one place can stay an `env()` call; promote it to a config file when it gains structure, defaults, or conditional logic. ## The env helper Read environment variables with optional type coercion and a fallback. The fallback's type decides how the raw string is coerced: ```typescript // config/app.ts (or anywhere) import { env } from "zerotal"; const port = env("PORT", 3000); // number fallback → coerced to number const debug = env("APP_DEBUG", false); // boolean fallback → "true"/"1" become true const appName = env("APP_NAME", "Zerotal App"); // string fallback const apiKey = env("API_KEY"); // no fallback → string | undefined ``` `env()` reads `Bun.env` at call time. Use it in config files, providers, and anywhere you need deployment-time values. > **Note** — When you need a value to be present, use `requireEnv("APP_KEY")` instead — it throws a `ConfigError` at boot if the variable is unset, rather than returning `undefined`. ### Declaring the whole environment — `EnvSchema` `env()` is per-call and forgiving: an unset variable is `undefined` and you find out where it is used. `@zerotal/core/env` is the other end — declare every variable the app reads, once, and the boot either produces a fully typed frozen object or fails with every problem listed at the same time: ```typescript fragment // env.ts import { EnvSchema, t } from "@zerotal/core/env"; export const env = EnvSchema.define({ APP_KEY: t.string().min(32), PORT: t.port().default(3000), DATABASE_URL: t.string(), LOG_LEVEL: t.enum(["debug", "info", "warn", "error"]).default("info"), SENTRY_DSN: t.url().optional(), }); env.PORT; // number — never undefined, because it has a default env.LOG_LEVEL; // "debug" | "info" | "warn" | "error", narrowed to the literals ``` **It reports every failure at once.** A schema with three missing variables fails the boot naming all three, rather than one per restart — which is the difference between one fix and three round trips through a deploy. The failure is an `EnvSchemaError` carrying an `EnvFieldError` per field. | Type | What it is | | ---------------- | --------------------------------------------------------------------------- | | `EnvSchemaError` | The boot failure, listing every field that did not validate. | | `EnvFieldError` | One field's problem: which variable, and what was wrong with it. | | `FieldType` | The builders `t` offers — string, number, boolean, port, url, enum. | | `EnvOutput` | The typed object a schema produces. `typeof env` where you need to pass it. | | `InferDef` | The type one field definition resolves to. | Use `env()` for a value read in one place and `EnvSchema` for the set an app cannot start without. They coexist; the schema is not a replacement for the helper. ## Config files Config files live in `config/`. Each file exports a typed object via a package helper: ```typescript // config/database.ts import { DatabaseConfig } from "@zerotal/orm"; import { env } from "zerotal"; export default DatabaseConfig({ url: env("DATABASE_URL", "sqlite://./database.sqlite"), }); ``` ```typescript // config/session.ts import { SessionConfig } from "@zerotal/session"; import { env } from "zerotal"; export default SessionConfig({ driver: env("SESSION_DRIVER", "cookie") as "cookie" | "redis", secret: env("SESSION_SECRET", ""), lifetime: 86400, secure: env("APP_ENV") === "production", }); ``` Config helpers (`DatabaseConfig`, `SessionConfig`, etc.) are typed factory functions that give you autocomplete and catch typos. Some — like `AppConfig` — also fill in defaults for fields you omit. ## The config helper Access any loaded config value at runtime: ```typescript // in a provider, middleware, or controller import { config } from "zerotal"; config("app.name"); // get — typed as string (see below) config("app.name", "Zerotal"); // get with fallback — fallback must match the path's type config.require("app.key"); // throws ConfigError if absent config.set("app.debug", true); // override at runtime (useful in tests) config.all(); // dump all loaded config as a flat record ``` Dot-notation maps to the config file path and the key within it. `config('database.url')` reads `url` from `config/database.ts`. > **Note** — `config()` resolves against the booted application's config store. When no app is booted (some test or script contexts), use `config.safe("app.name", "fallback")`, which returns the fallback instead of throwing. ### Typed dot-paths `config()` is type-aware. Each path resolves to the type declared in the owning package's `*ConfigShape`, with autocomplete on the path string: ```typescript fragment // in application code config("app.name"); // string config("app.port"); // number config("cache.ttl"); // number config("app.throttle.maxAttempts"); // number — nested paths work too config.set("app.debug", "yes"); // type error: expected boolean ``` This works exactly like the container's `ContainerBindings`: there's a `ConfigRegistry` interface that every config-owning package augments by namespace. Core registers `app` and `health`; each package registers its own next to its `*ConfigShape`: ```typescript fragment // in a package's config registry declaration declare module "zerotal" { interface ConfigRegistry { cache: CacheConfigShape; } } ``` A namespace lights up as typed once its package is imported (which an app does by referencing its `XConfig` factory in `config/.ts`). Paths outside any registered namespace still compile — they fall back to the untyped `config(path: string)` overload returning `unknown`, so dynamic access is never blocked. ## Which layer do I use? | Layer | What it does | Reach for it when | | ------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------- | | `env()` | Reads deployment state (env vars) | Credentials, URLs, driver names — anything that changes per environment | | `config/*.ts` | Assembles code-level structure and logic | Multi-field configs, conditional logic, code references (class constructors, strategy objects) | | `config()` | Runtime access to loaded config | In service providers, middleware, and application code that needs cross-cutting config values | The rule of thumb: read raw values with `env()`, shape and default them in a `config/*.ts` file, and read the shaped result anywhere with `config()`. ## How config loads at boot Zerotal loads config **eagerly** when the application boots, before any provider registers: - During `boot()`, the app auto-discovers and imports every `config/*.ts` file, taking each file's `default` export. - Those exports are merged into the `ConfigManager` (bound in the container under the `"config"` key) before the provider `onRegister` → `onBooting` → `onBooted` phases run. - A file that throws on import (for example, a missing required env var) is skipped during auto-discovery rather than crashing the whole boot. Because every file is loaded as a normal module, a config file may `import` and read other modules at the top level — just avoid circular config imports between files. > **Warning** — Auto-discovery silently skips a config file that throws while importing. If a namespace seems to be missing all its values, check that the file imports cleanly and that its required env vars are set. Under `zt`, a file that fails is reported once the command is known. A command that boots the app reports it as an error, as before. A command that does not (`zt inertia:build`, the `make:*` scaffolders, `zt version`) prints one line saying the file did not load and why, and carries on; anything it reads from that file, such as a scaffolder's output path, falls back to its default. A build in CI needs no `APP_KEY`, and does not need a placeholder one to keep its log clean. ## Overriding config in tests ```typescript fragment // in a test setup file import { config } from "zerotal"; beforeEach(() => { config.set("mail.driver", "log"); // force log driver in tests config.set("queue.driver", "sync"); }); ``` > **Note** — `config.set()` overrides in-memory only. `.env` is never modified. ## Application-level config Create `config/app.ts` for app-wide settings: ```typescript // config/app.ts import { env } from "zerotal"; import { AppConfig } from "zerotal/config"; export default AppConfig({ name: "Example", url: env("APP_URL", "http://localhost:3000"), key: env("APP_KEY", "changeme-in-production"), cors: { origin: env("CORS_ORIGIN", "*"), credentials: false, }, throttle: { maxAttempts: 120, windowSeconds: 60, }, secureHeaders: { frameOptions: "SAMEORIGIN", }, }); ``` `AppConfig()` fills in sensible defaults for everything you omit (`env`, `key`, `debug`, `url`, `port`, `locale`, `timezone`, `http3`, `health`, `cors`, `throttle`, `secureHeaders`, and the `conventions` auto-discovery settings). Read any value with `config('app.name')`, `config('app.cors.origin')`, etc. The auto-discovery settings live under the `conventions` key — see [Conventions](/docs/conventions). ## Loading config explicitly The CLI entry (`zt.ts`) can load config **synchronously** at the top level and inject it into the app, so it's available before anything boots: ```typescript // zt.ts import { Application } from "zerotal"; import { configLoader } from "zerotal/config"; const config = configLoader("./config"); // sync — scans config/*.ts, safe at top level config.validate(); // runs each file's optional validate() export const app = Application.create({ config }); // …or app.useConfig(config) ``` `configLoader(dir, options?)` returns a `ConfigLoader` with `all()`, `get("dot.path", fallback)`, `has(path)`, `validate()` and `failures()`. A file that throws while loading is logged as an error, or, with `{ deferFailures: true }`, kept in `failures()` for the caller to report once it knows whether anything needs it. A config file may export a named `validate(config)` function; `ConfigLoader.validate()` runs them all and throws on the first failure. **One source of truth.** If config was passed to `Application.create({ config })`, a later `useConfig(...)` is **ignored** (create wins) — so the framework-managed `zt.ts`, which always calls `useConfig(...)`, never conflicts with an app that prefers to pass config to `create()`. When neither is used, the app auto-discovers `config/*.ts` at boot as described above. ## Environment files Zerotal automatically loads `.env` in development. For production, set variables in your deployment platform. > **Danger** — Never commit `.env` to version control. It holds real secrets. Commit `.env.example` with safe defaults instead. ```bash # .env.example (committed — safe defaults, no secrets) APP_NAME=My App APP_ENV=local APP_KEY= DATABASE_URL=sqlite://./database.sqlite SESSION_SECRET= ``` ```bash # .env (gitignored — real values) APP_KEY=base64:abcdef... DATABASE_URL=mysql://user:pass@localhost:3306/mydb SESSION_SECRET=super-secret ``` Use `APP_ENV` to differentiate behaviour: ```typescript fragment // in application code if (config("app.env") === "production") { // production-only logic } ``` ## References | Member | Signature | Description | | ----------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `env` | `env(key: string, fallback?: string \| boolean \| number)` | Read an env var, coercing to the fallback's type; `string \| undefined` with no fallback. | | `requireEnv` | `requireEnv(key: string): string` | Read a required env var; throws `ConfigError` if unset. | | `config` | `config(path: string, fallback?): value` | Read a config value by dot-path, optionally with a fallback. | | `config.require` | `config.require(path: string): value` | Read a config value; throws `ConfigError` if absent or null. | | `config.set` | `config.set(path: string, value): void` | Set a config value at runtime (in-memory only). | | `config.all` | `config.all(): Record` | Return all loaded config as a record. | | `config.safe` | `config.safe(path: string, fallback): value` | Read without throwing when no app is booted; returns the fallback. | | `AppConfig` | `AppConfig(options): AppConfigShape` | Build the `app` namespace config, filling defaults for omitted fields. | | `configLoader` | `configLoader(dir = "./config"): ConfigLoader` | Synchronously load a `config/` directory into a `ConfigLoader`. | | `ConfigLoader.get` | `get(key: string, fallback?): value` | Dot-path read against the loaded map. | | `ConfigLoader.validate` | `validate(): this` | Run each file's optional `validate(config)` export, throwing on failure. | ## Types | Type | What it is | | ------------------- | -------------------------------------------------------------------------------------- | | `ConfigValidator` | What `registerConfigValidator` takes — a function handed the config, reporting issues. | | `ConfigIssue` | One finding: its namespace, message, and level. | | `ConfigIssueLevel` | Whether an issue refuses a production boot or is only worth reading. | | `ConventionsConfig` | The `conventions` namespace — where the framework looks for models, jobs and the rest. | | `AppTlsConfig` | TLS settings under `app.tls`. | | `AssetLoaderKind` | How an asset is loaded by the build — the `loader` values `assets.loaders` accepts. | A validator reporting a **fatal** issue refuses a production-like boot rather than warning. That is the whole point of the level: an app that boots with a broken configuration serves wrong answers rather than failing, and the failure is the cheaper outcome. ## Next steps - [Conventions](/docs/conventions) — the auto-discovery settings under the `conventions` key. - [Providers](/docs/providers) — where `config()` is most often read. - [Application](/docs/application) — how config is injected and loaded at boot. - [Deployment](/docs/deployment) — setting env vars in production. --- Source: https://zerotal.dev/docs/conventions # Conventions Zerotal auto-discovers and wires your app classes by **convention** at boot — drop a file in the right `app/*` directory and it just works, no manual `register()` calls. This covers providers, middleware, services, models, observers, policies, event listeners, events, jobs, schedules, and validators, plus optional auto-migration. ## Mental model Each kind of class lives in a well-known directory; a **concern descriptor** knows how to scan that directory and register what it finds. Core owns a few concerns (events, services, listeners, jobs, validators); packages contribute the rest (`models`/`observers` from ORM, `policies` from auth, `schedules` from scheduler) via `app.registerConcern(...)`, so core depends on neither ORM nor auth. Discovery happens at three points in the boot sequence, each ordered so later steps can rely on earlier ones: ```text # boot timeline (left → right) app/providers/* → register → boot phases → app/middleware/* → convention phase (before register, (your explicit + the (before routes (everything else, full lifecycle) discovered providers) load) concerns by order) ``` - **Providers** are discovered _before_ the register phase, so they run their full lifecycle. - **Middleware** is discovered _before_ routes load, so routes can reference it by name. - Everything else runs in the **convention phase**, after all providers have booted, with each concern sorted by its `order` (lower runs first). > **Note** — In development and tests Zerotal scans the filesystem. You can disable discovery or > override any path via [config](#configuration); a generated manifest can replace runtime scanning > in production. ## Models — app/models/ Every `Model` subclass under `app/models/` is registered automatically: ```typescript fragment // app/models/User.ts import { Model, column, hasMany } from "@zerotal/orm"; import { Post } from "./Post.ts"; export class User extends Model { @column() name!: string; @column() email!: string; @hasMany(() => Post, { foreignKey: "user_id" }) posts!: Post[]; } ``` No `@table` needed. The table name is derived by convention — `pluralize(snake(ClassName))`: | Class | Table | | ---------- | ------------ | | `User` | `users` | | `BlogPost` | `blog_posts` | | `Category` | `categories` | | `Person` | `people` | Override the name (or set timestamps/soft-deletes) with `@table` whenever you need to: ```typescript fragment // app/models/Account.ts @table("legacy_accounts", { softDeletes: true }) export class Account extends Model { /* … */ } ``` > **Warning** — Use real fields for convention models. Declare columns as `@column() name!: string`, not > `@column() declare name: string`. The loader identifies a class's columns from a probe > instance's own fields, and `declare` fields are erased at runtime. (With an explicit `@table`, > either form works.) > > Models that ship **inside packages** (not under an app's `app/models/`) and models defined > **inline in tests** are not auto-discovered — they keep using `@table`. ## Observers — app/observers/ `XObserver` is attached to model `X` automatically (the `Observer` suffix is stripped and matched against the discovered models): ```typescript fragment // app/observers/UserObserver.ts import type { ModelObserver } from "@zerotal/orm"; import type { User } from "../models/User.ts"; export class UserObserver implements ModelObserver { creating(user: User) { user.uuid = crypto.randomUUID(); } created(user: User) { /* … */ } } ``` Override the target with `static model = SomeModel` when the name doesn't match. ## Policies — app/policies/ `XPolicy` is registered with the Gate for model `X`: ```typescript fragment // app/policies/PostPolicy.ts import { Policy } from "@zerotal/auth"; import type { Post } from "../models/Post.ts"; import type { User } from "../models/User.ts"; export class PostPolicy extends Policy { update(user: User, post: Post) { return post.userId === user.id; } delete(user: User, post: Post) { return post.userId === user.id; } } ``` Authorization (`Gate.allows("update", post)`, `ctx.authorize(...)`) resolves the policy from the model's class automatically. Override the target with `static model = Post`. ## Events & listeners — app/events/, app/listeners/ A listener declares the event(s) it handles via `static listens`: ```typescript fragment // app/events/UserRegistered.ts export class UserRegistered { constructor(public user: User) {} } ``` ```typescript fragment // app/listeners/SendWelcomeEmail.ts import { UserRegistered } from "../events/UserRegistered.ts"; export class SendWelcomeEmail { static listens = UserRegistered; // or an array: [UserRegistered, ...] async handle(e: UserRegistered) { await Mail.send(new WelcomeMail(e.user)); } } ``` The loader binds each listener on the app event bus — no `Emitter.on(...)` wiring. Classes under `app/events/` need no registration of their own; importing them is the whole effect (it bundles them and runs any module-level side effects before listeners bind). ## Model events A model can map its lifecycle events to event classes, which are dispatched on the bus when they fire — listeners then react with no coupling to the model: ```typescript fragment // app/models/Order.ts export class Order extends Model { static dispatchesEvents = { created: OrderPlaced, deleted: OrderCancelled }; } ``` Keys are the lifecycle event names: `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`, `retrieved`. Each event class is constructed with the model instance and emitted. Dispatch honours hook suppression, so factory seeding stays silent. If no event bus is bound (ORM used standalone), it's a safe no-op. > **Tip** — Observers and `dispatchesEvents` coexist. Use an **observer** to group all lifecycle > handlers in one class, and **`dispatchesEvents`** for decoupled pub/sub with independent > listeners. ## Providers — app/providers/ Any `ServiceProvider` under `app/providers/` is registered automatically — you don't list it in `bootstrap/providers.ts`. Discovered providers run the full lifecycle (`onRegister` → `onBooting` → `onBooted`), appended **after** the providers you registered explicitly (so framework providers boot first), and de-duplicated if also listed by hand. ```typescript fragment // app/providers/AppServiceProvider.ts import { ServiceProvider } from "zerotal"; // A string token is only valid once it is declared, which is what keeps // `make("billing")` typed at the call site. See Container for the full pattern. declare module "zerotal" { interface ContainerBindings { billing: Billing; } } export class AppServiceProvider extends ServiceProvider { override onRegister() { this.app.container.singleton("billing", () => new Billing()); } } ``` ## Middleware — app/middleware/ Each middleware class under `app/middleware/` is registered as a **named group** under its class name, so routes can reference it by string without importing it: ```typescript fragment // app/middleware/EnsureSubscribed.ts import { BaseMiddleware } from "zerotal"; export class EnsureSubscribed extends BaseMiddleware<{}> { async handle(ctx, next) { /* … */ return next(ctx); } } ``` ```typescript fragment // routes/web.ts — reference by class name Router.group({ middleware: ["EnsureSubscribed"] }, () => { /* … */ }); ``` Middleware is **not** applied globally by default. Opt a class into the global pipeline with `static global = true`: ```typescript fragment // app/middleware/RequestId.ts export class RequestId extends BaseMiddleware<{}> { static global = true; // runs on every request async handle(ctx, next) { /* … */ return next(ctx); } } ``` ## Services — app/services/ Service classes under `app/services/` auto-register with the container, so `App.make(MyService)` resolves them with the lifetime they declare. A class opts into a lifetime with a `static lifetime` flag: ```typescript // app/services/UsersService.ts import { GateService } from "@zerotal/auth"; export class UsersService { static lifetime = "singleton"; // "singleton" | "scoped" | "transient" constructor(private gate: GateService) {} } ``` - `singleton` / `scoped` → bound with a factory that auto-wires a fresh instance via `container.build()`. - `transient` or no flag → nothing is registered; the container already auto-wires unregistered classes on demand, so resolution still works (a new instance each time). Non-service exports (types, helpers) are therefore ignored. ## Jobs — app/jobs/ Queue job classes under `app/jobs/` are imported at boot, which triggers their `JobRegistry.register()` self-registration — so dispatch works without a manual import or the generated jobs barrel (the barrel is still used for production workers). ```typescript // app/jobs/NotifyFollowersJob.ts import { Job } from "@zerotal/queue"; export class NotifyFollowersJob extends Job { override readonly queue = "notifications"; override readonly maxAttempts = 5; constructor(private readonly postId: number) { super(); } // Constructor arguments must be serialised to survive the queue. override payload(): Record { return { postId: this.postId }; } async handle(): Promise { // … } } ``` Dispatch it from anywhere without importing the class into a barrel: ```typescript fragment // in a controller await Queue.dispatch(new NotifyFollowersJob(post.id)); ``` The registration key is the class name, so two jobs may not share one — see [Queue](/docs/queue) for the full lifecycle. ## Schedules — app/schedules/ Classes under `app/schedules/` that extend the `Schedule` base class are instantiated and registered with the scheduler at boot. Each declares its cadence (a `cron` string or the fluent `frequency()` method) and its work (`handle()`); the loader translates the class's declarative settings into a scheduled task. ```typescript fragment // app/schedules/SendDailyReports.ts import { Schedule } from "@zerotal/scheduler"; export class SendDailyReports extends Schedule { cron = "0 8 * * *"; withoutOverlapping = true; async handle() { await Queue.dispatch(new SendReportsJob()); } } ``` This concern runs in the **worker** environment (to execute tasks) and **console** (so `schedule:list` can enumerate them); it never runs in `web`. Contributed by `SchedulerProvider`. See [Scheduler](/docs/scheduler) for the full `Schedule` settings reference. ## Validators — app/validators/ Files under `app/validators/` are auto-imported at boot, so any module-level registration they perform is in place before the first request. This is where a shared `FormRequest` base class or a rule set used across several requests belongs: ```typescript // app/validators/StorePostRequest.ts import { FormRequest } from "@zerotal/validator"; export class StorePostRequest extends FormRequest { rules(r) { return { title: r.string().min(3).max(120), body: r.string().min(1), }; } } ``` The auto-import matters for anything with a **side-effect at module scope**. A `FormRequest` subclass imported by its controller would load anyway; a module that registers something on import only runs because this concern imports it. ## Auto-migration Once models are registered at boot, Zerotal can sync the schema additively — create missing tables and add missing columns to match your models (TypeORM-style `synchronize`): ```typescript fragment // config/database.ts import { DatabaseConfig } from "@zerotal/orm"; export default DatabaseConfig({ url: env("DATABASE_URL", "sqlite://./database.sqlite"), synchronize: true, // dev convenience }); ``` - **Opt-in:** off unless enabled (like TypeORM), and **hard-off in `production`** regardless — there you run `migrate` with generated migration files. A common setup enables it only for tests/local via env (`synchronize: env("APP_ENV") !== "production"`). - **Additive by default:** `true` creates missing tables and adds missing columns; it never drops or alters existing ones. - **Disruptive opt-in:** pass `synchronize: { enabled: true, disruptive: true }` to also drop columns no model declares anymore. This destroys their data (and logs a warning per drop), so keep it to local/test. See [Migrations → Disruptive sync](/docs/migrations#disruptive-sync). > **Danger** — Disruptive sync drops columns and the data they hold. Never enable it in production; > the concern is hard-off there regardless, but keep it scoped to local/test even so. ## Configuration Auto-discovery is configured under the `conventions` key in `config/app.ts`. `AppConfig()` fills in every default, so you only set what you want to change: ```typescript // config/app.ts import { env } from "zerotal"; import { AppConfig } from "zerotal/config"; export default AppConfig({ name: "Example", url: env("APP_URL", "http://localhost:3000"), key: env("APP_KEY", "changeme-in-production"), // Defaults shown — omit entirely unless you want to change them. conventions: { enabled: true, paths: { providers: "app/providers", middleware: "app/middleware", models: "app/models", observers: "app/observers", policies: "app/policies", listeners: "app/listeners", events: "app/events", jobs: "app/jobs", schedules: "app/schedules", validators: "app/validators", commands: "app/commands", }, }, }); ``` | Field | Required | Default | Description | | --------- | -------- | ---------------------- | ---------------------------------------------------------- | | `enabled` | no | `true` | Master switch for convention-based auto-registration. | | `paths` | no | the `app/*` dirs above | Per-concern directory overrides, relative to the app root. | Set `conventions.enabled: false` to opt out entirely and wire everything manually. Path overrides let you relocate any concern. Files starting with `_` and `*.test.ts` / `*.test.tsx` / `*.spec.ts` / `*.d.ts` are always skipped. ## Custom concerns Discovery is extensible. A provider can contribute its own concern descriptor via `app.registerConcern(...)`: ```typescript fragment // app/providers/AppServiceProvider.ts — inside onRegister/onBooting this.app.registerConcern({ name: "validators", order: 60, dir: "app/validators", register(mod, ctx) { for (const exported of Object.values(mod)) { /* register exported as needed */ } }, }); ``` `order` controls sequencing (lower runs first). A `run(ctx)` hook (no `dir`) defines a one-shot step that runs after the scanned concerns at the same point in the ordering — this is how auto-migration is wired (`order: 100`, `run`-only). Restrict a concern to certain runtimes with `envs` (e.g. `envs: ["worker", "console"]`, as `schedules` does). ## Reference The concerns that run in the convention phase, in `order`. `events`, `services`, `listeners`, `jobs`, and `validators` are owned by core; the rest are contributed by their packages. | Concern | Directory | Order | Runs in | Contributed by | | -------------- | ---------------- | ----- | --------------- | -------------------- | | `events` | `app/events` | 5 | all | core | | `models` | `app/models` | 10 | all | `@zerotal/orm` | | `services` | `app/services` | 10 | all | core | | `observers` | `app/observers` | 20 | all | `@zerotal/orm` | | `policies` | `app/policies` | 30 | all | `@zerotal/auth` | | `listeners` | `app/listeners` | 40 | all | core | | `jobs` | `app/jobs` | 50 | all | core | | `schedules` | `app/schedules` | 55 | worker, console | `@zerotal/scheduler` | | `validators` | `app/validators` | 60 | all | core | | `auto-migrate` | _(run-only)_ | 100 | non-production | `@zerotal/orm` | `providers` (`app/providers`) and `middleware` (`app/middleware`) are not convention-phase concerns — they are discovered earlier in the boot sequence (see [Mental model](#mental-model)). `commands` (`app/commands`) is discovered by the CLI's command runner rather than the convention phase — console, worker, and test environments only, since HTTP boot has no use for parsing CLI files. It honours `conventions.enabled` and the `paths.commands` override like the rest. See [Commands](/docs/commands#auto-discovery). ## Next steps - [Structure](/docs/structure) — see how the `app/*` directories fit the project layout. - [Providers](/docs/providers) — register and boot services explicitly when convention isn't enough. - [Config system](/docs/config-system) — how `config/*.ts` files are loaded and merged. - [Migrations](/docs/migrations) — generate schema changes instead of relying on `synchronize`. --- Source: https://zerotal.dev/docs/commands # Commands Zerotal ships a class-based CLI for running framework tasks and your own scripts. Every command is invoked with `bun zt `, and you can add new ones as classes or one-line closures. ```bash # in your project root bun zt list # list all commands with descriptions bun zt help # detailed usage for one command bun zt make:controller PostController ``` The command system is built into `@zerotal/core` — there is no package to install and no provider to register. The CLI bootstraps your application, then dispatches the matched command. ## Listing & help `bun zt list` prints every registered command, its description, and any aliases. `bun zt help ` prints the usage line, description, arguments, and options for a single command. ```bash # in your project root bun zt list bun zt help migrate bun zt migrate --help # the same page; -h works too ``` Adding `--help` (or `-h`) to any command prints that page and does **not** run the command, so it is safe to ask about one you are unsure of. A command that declares its own `help` flag or `-h` option keeps it, and everything after a bare `--` is passed to the command as it is. ## Class-based commands Extend `Command`, declare static metadata, and implement `run()`. Inside `run()` you read parsed positional arguments from `this.args` and flags from `this.flags`: ```typescript // app/commands/SendDigestCommand.ts import { Command } from "zerotal"; export class SendDigestCommand extends Command { static commandName = "digest:send"; static description = "Send the weekly digest email"; static args = [{ name: "segment", required: false, default: "all" }]; static flags = [{ name: "dry", type: "boolean" as const, default: false }]; async run(): Promise { const segment = this.args["segment"]; if (this.flags["dry"]) { this.warn("Dry run — nothing sent"); return; } this.info(`Sending digest to ${segment}…`); } } ``` A `FlagDef`'s `type` is `"string" | "boolean" | "number"`; the `as const` keeps the literal type so the field stays type-checked. > **Tip** — Run `bun zt make:command SendDigest` to scaffold a ready-to-edit > command class at `app/commands/SendDigestCommand.ts`. ## Closure commands For one-liners, register a plain definition with a signature string. The signature's first token is the name; `{arg}` is required, `{arg?}` optional, `{arg=default}` has a default, `{--flag}` is a boolean flag, and `{--flag=}` / `{--flag=default}` is a string flag. ```typescript fragment // in a service provider or bootstrap script const runner = app.container.tryMake("commands"); runner.command({ signature: "greet {name} {--loud}", description: "Say hello", handle: ({ name, loud }, cmd) => { cmd.info(loud ? `HELLO ${name}!` : `Hello, ${name}`); }, }); ``` The `handle` callback receives a single object merging the parsed arguments and flags, plus the `Command` instance so you can use its output helpers. > **Note** — `registerCommand()` is an alias for `command()`; both build a > synthetic `Command` subclass from the definition and register it. ### Which should I use? | You have… | Use | | ------------------------------------------------------ | -------------------- | | A quick task with little logic, defined inline | Closure | | Logic worth testing, multiple methods, or its own file | Class | | A folder of commands to register together | Class + `discover()` | ## Auto-discovery `app/commands/` is discovered automatically: any command class dropped there — including everything `make:command` generates — is registered when the CLI boots, with no imports or provider wiring. An app command registers after the built-ins, so it wins a name collision. The directory is configurable via `conventions.paths.commands` in `config/app.ts`, and discovery honours the `conventions.enabled` master switch. To register a folder from somewhere else, call `discover()` yourself: ```typescript fragment // in a service provider or bootstrap script await runner.discover("./vendor/acme/commands"); ``` Every non-test `.ts`/`.js` file under the directory is imported, and any exported `Command` subclass with a non-empty `commandName` is registered. `discover()` returns the list of registered names. ## Styled output & prompts The `Command` base class provides coloured output helpers and interactive prompts. The prompts read from stdin and only work on a real TTY: ```typescript fragment // inside a command's run() this.info("Success"); // green this.warn("Heads up"); // yellow this.error("Failed"); // red (written to stderr) this.line("Plain"); // cyan this.dim("subtle"); // dim this.section("Title"); // bold heading this.table([["Key", "Value"]]); // aligned two-column rows this.newLine(); const name = await this.ask("Your name?", "guest"); const ok = await this.confirm("Proceed?", true); const env = await this.choice("Environment:", ["local", "staging", "production"]); const token = await this.secret("API token:"); // input hidden on a Unix TTY ``` > **Warning** — `secret()` only hides input on a Unix TTY with raw mode; on > Windows and in non-interactive contexts it falls back to a visible prompt. ## Built-in Commands ### Server & Development | Command | Description | | ----------------------------- | --------------------------------------------------------------- | | `bun zt dev` | Dev mode: the server plus every registered process (alias: `d`) | | `bun zt dev --only=server` | Run only the named processes, comma-separated | | `bun zt dev --without=queue` | Run everything except the named processes | | `bun zt dev --list` | Print what would run, and which provider registered it | | `bun zt dev --stream` | Interleave prefixed output instead of drawing tabs | | `bun zt dev --force-build` | Rebuild assets even when the build cache says they're current | | `bun zt serve` | Start the HTTP server on `app.port`: `PORT`, else 3000 | | `bun zt serve --port 8080` | Start on a custom port, over `PORT` and `app.port` | | `bun zt serve --force` | If the port is busy, stop whatever holds it | | `bun zt serve --auto-port` | If the port is busy, start on the next free port | | `bun zt reload` | Hot-reload routes in the running server (sends SIGUSR2) | | `bun zt status` | Show live metrics from the running server | | `bun zt repl` | Start an interactive REPL with the bootstrapped app in scope | | `bun zt worker` | Start the background job worker process | | `bun zt worker --queue email` | Process a specific queue | | `bun zt worker --once` | Process one job then exit | | `bun zt test` | Run the test suite in the `test` environment | | `bun zt test --randomize` | Run tests in a random order; `--seed=` replays one | | `bun zt compile` | Compile to a binary; Deployment has its limits (alias: `build`) | | `bun zt css:build` | Build the Tailwind CSS bundle for production | #### When the port is already taken `serve` checks the port before it binds, so a busy one is a question rather than a crash. It tells you which process is holding it — usually a server you forgot was running — and offers to stop that process and take the port, or to start on the next free one instead. Pressing Enter takes the next free port, the answer that cannot cost you anything. Nothing prompts when there is no terminal to answer, which covers CI, containers, and anything reading `serve`'s output from a pipe. There it fails with the same explanation, so use `--force` or `--auto-port` to say up front which way you want it decided. Both flags work with `serve` and with `dev`. The dev server is a special case worth knowing about: on every restart it waits a few seconds for its own previous process to let go of the socket rather than asking you about it. A prompt on each file save would be unbearable, and the port is about to free itself anyway. #### Dev mode and the deck `bun zt dev` starts the server, the file watcher, and every process a provider or your app registered — a queue worker, a type-checker, a Stripe listener — in one terminal, each in its own tab. It subclasses `serve`, so it is the same supervisor, the same port resolution and the same restart behaviour, plus the flags that only make sense with a deck on screen — anything true of `serve` is true of it. `serve --dev` was the old spelling and was retired in 1.13.0; it now fails with a message rather than starting a plain server. The scaffold's `dev` script runs this, so `bun run dev` and `bun zt dev` are the same thing. An app with a queue no longer needs a second terminal: ```bash # in your project root bun zt dev ``` The deck draws one tab per process, colour-coded, showing whether each is running, restarting, or has given up: ```text 1 server ●│ 2 queue ●│ 3 types ◌ ───────────────────────────────────────────────── GET / 200 4ms GET /posts 200 11ms 1-9 tab · ←/→ cycle · ↑/↓ scroll · r restart · c clear · / search · t time · s stream · q quit ``` | Key | Does | | ------------- | ----------------------------------------------------------------- | | `1`–`9` | Select that tab | | `←` `→` `Tab` | Cycle through tabs | | `↑` `↓` | Scroll the focused tab a line at a time — as does the mouse wheel | | `PgUp` `PgDn` | Scroll it a screen at a time | | `Home` `End` | Jump to the oldest line, or back to the newest | | `r` | Restart the focused process | | `c` | Clear the focused tab's output | | `/` | Search within the focused tab (`Enter` keeps it, `Esc` drops it) | | `t` | Toggle per-line timestamps | | `s` | Switch to stream mode | | `q` | Quit — stops every process and restores your shell | Scrollback belongs to the deck rather than to your terminal, which is what makes per-tab history and search possible. It keeps the last 5,000 lines per process. Your terminal's own scrollbar does nothing while the deck is up — it has no history to move, because the deck holds it all. Use the keys above (or the wheel, which the terminal sends the deck as `↑`/`↓`). Scrolling up parks the view where you left it: the process behind the tab keeps printing, but what you stopped to read stays on screen until you scroll back down to the newest line. **A process that dies never takes the server with it.** It restarts on its own — three times, backing off between attempts — and if it still will not start, that one tab parks with a message telling you how to retry. Everything else keeps running. This is the opposite of the asset build, where a failure deliberately aborts the reload. #### Stream mode Not everything watching `zt dev` is a person at a terminal. When stdout is not a TTY — CI, a pipe, a log file — the deck writes prefixed lines instead, with no escape codes at all: ```text [server] GET / 200 4ms [queue ] processing SendWelcomeEmail [server] GET /posts 200 11ms ``` That happens automatically; `--stream` forces it, and `s` switches to it mid-session. It is the same information, and it is what you want in a file. #### Choosing what runs `--only` and `--without` take comma-separated names, and the server is an ordinary name among them: ```bash # in your project root bun zt dev --only=server,queue # just these two bun zt dev --without=queue # everything else bun zt dev --only=queue # no server at all ``` When you are not sure what a tab is or who asked for it, `--list` answers both without starting anything: ```bash # in your project root bun zt dev --list ``` ```text Dev processes server command managed by the orchestrator registered by @zerotal/core queue command bun zt queue:work registered by QueueProvider ``` Your app has the last word. `app.dev.disable` removes a process by name, and registering the same name again replaces it rather than adding a second tab: ```ts fragment // config/app.ts export default AppConfig({ dev: { processes: [ { name: "stripe", command: ["stripe", "listen", "--forward-to", "localhost:3000"] }, ], disable: ["queue"], }, }); ``` Packages register their own — see [Registering a dev process](/docs/package-development#registering-a-dev-process). ### Inspection | Command | Description | | ---------------------- | ------------------------------------------------------ | | `bun zt version` | Show the Zerotal, Bun and app versions | | `bun zt about` | Installed Zerotal packages, and what else ships | | `bun zt route:list` | List all registered routes with methods and middleware | | `bun zt route:types` | Write `types/routes.generated.ts` (`--check` in CI) | | `bun zt doctor` | Check the app for silent misconfigurations | | `bun zt key:generate` | Generate a new `APP_KEY` and write it to `.env` | | `bun zt key:rotate` | Replace `APP_KEY`, keeping the old one to decrypt with | | `bun zt init:env` | Create `.env` from `.env.example`, secrets generated | | `bun zt lint:packages` | Check every workspace package against convention rules | | `bun zt upgrade` | Apply the codemods for a version upgrade | #### What does this app have, and what else is there? `bun zt about` lists the Zerotal packages installed in the app with their versions, then the framework packages it does not have, each with the needs it covers, the command to add it and its docs page: ```text Zerotal 1.x.y · Bun 1.3.14 · shop 0.0.1 Installed @zerotal/arch 1.x.y @zerotal/core 1.x.y (through zerotal) @zerotal/notifications 1.x.y zerotal 1.x.y Available, not installed @zerotal/tenancy Multi-tenancy bun add @zerotal/tenancy · https://zerotal.dev/docs/tenancy ``` A package at a different version from the rest is marked, since the packages are released and tested together. The available list is the capability index that ships in `@zerotal/arch`, the same one [What Ships](/docs/what-ships) and `AGENTS.md` are built from; without that package, `about` lists what is installed and says where the index lives. Like `version`, it needs no booted app. `--json` prints the same report for a script. #### Which version am I on? `bun zt version` prints the framework, the runtime and the app: ``` Zerotal 1.11.0 Bun 1.3.14 App my-app 0.1.0 ``` It reports the version that is **running**, which is not always the version that is installed — a long-running server holds the code it booted with, so an upgrade lands on disk without reaching it. `--version` and `-v` answer the same question without booting the application: ```bash bun zt --version bun zt --version --json # for a script ``` Prefer the flag form in scripts, for two reasons. It still answers when the app does not boot — a config that no longer validates is exactly when you want to know which version you are on. And it is the form whose output can be piped: the application's boot log is written to stdout, so `bun zt version --json` carries a log line ahead of the JSON, while `bun zt --version --json` never boots and emits nothing else. If `node_modules` contains a second Bun, the report names it. Nothing executes that copy — it arrives as a peer dependency — but it is the one an install would use. ### Upgrading between versions `bun zt upgrade --to ` applies the codemods a version gap calls for — mechanical rewrites the framework can make on your behalf when an API changes. ```bash bun zt upgrade --to 2.0.0 # print the plan, change nothing bun zt upgrade --to 2.0.0 --write # apply it ``` **It writes nothing unless you ask.** That is the opposite of most tools and deliberate: it rewrites source across your whole project, so the first run should be something you can read and disagree with. `--from` defaults to the `zerotal` version in your `package.json`. The half worth reading is the last one. A codemod that quietly walks past something it does not understand is worse than none, because the changes it _did_ make suggest the job is finished — so anything it recognised and deliberately did not touch is listed with a file, a line and a reason: ```text 1 place(s) need a decision this cannot make for you: app/models/Post.ts:9 export function all(rows: T[]): T[] { `BaseModel` in a type position. It resolves to the same class as `Model`, so this compiles either way — renaming it is a readability call, not a correctness one. ``` Run it again after applying: a second run should report no changes. Codemods are idempotent, and that is the cheapest way to confirm one did what it said. #### What a release fixed for you `--notes` prints the changelog entries between two versions instead of running codemods, read from the changelogs the installed packages ship, so it covers exactly the packages your app has. It is read-only. ```bash bun zt upgrade --notes # after the version package.json declares, up to the installed one bun zt upgrade --notes --from 1.9.0 --to 1.15.4 bun zt upgrade --notes --grep smtp # is my SMTP workaround still needed? bun zt upgrade --notes --json # for tooling and CI ``` Entries come grouped as the changelog groups them, breaking changes first, each with the package and the version that shipped it. `--grep` searches the whole text of each entry, and entries say what used to fail, so it is the quickest way to check whether a workaround you carry has outlived its reason. Install the newer version first: the notes are the ones its packages carry. Some codemods rewrite nothing and only point. `retired-defaults` lists the lines in `config/app.ts` that set a value a default used to have and no longer does. Today that is `cors.origin` set to `"*"`, which older scaffolds wrote and which lets any website read your responses from a visitor's browser. Whether it was meant is your call, so it is reported with the file and line and left as it is. `doctor` runs every static sanity check against the booted app and prints each finding with its fix: APP_KEY strength, `database.synchronize` colliding with migration files, a `routes/` directory nothing loads, and class directories (`app/schedules`, `app/jobs`, `config/storage.ts`) whose consuming provider is not registered. These failures otherwise fail by _doing nothing_, which is the most expensive kind to find. Packages can contribute checks via `app.registerDoctorCheck()`. Exits non-zero when a check fails outright, so it can gate a deploy. ### Database | Command | Description | | ----------------------------- | -------------------------------------------------------------- | | `bun zt migrate` | Run all pending migrations | | `bun zt migrate --fresh` | Drop all tables, then re-run everything from scratch | | `bun zt migrate --seed` | Run migrations, then run the seeders | | `bun zt migrate --pretend` | Print the SQL pending migrations would run, and run none of it | | `bun zt migrate:rollback` | Roll back the most recent migration batch | | `bun zt migrate:fresh` | Alias: drop all tables and re-run all migrations | | `bun zt migrate:fresh --seed` | Rebuild the schema from scratch, then run the seeders | | `bun zt migrate:status` | Show the status (run / pending / batch) of each migration file | | `bun zt migrate:generate` | Auto-generate a migration from model schema changes | | `bun zt db:seed` | Run all seeders from `database/seeders/` | | `bun zt db:backup` | Take a verified SQLite snapshot with `VACUUM INTO` | > **Danger** — `migrate --fresh` and `migrate:fresh` drop every table before > re-running migrations. Never run them against a production database. `db:backup` is the counterpart to everything above it: those commands all assume the database file will still be there. It verifies every snapshot it writes and exits non-zero on any failure, so it is safe to run from a timer — see [Deployment](/docs/deployment#back-up-the-database) for the flags and a systemd unit. ### Generators | Command | Creates | | ---------------------------------------------------- | -------------------------------------------------------------------------- | | `bun zt make:model Post` | `app/models/Post.ts` | | `bun zt make:controller PostController [--resource]` | `app/controllers/PostController.ts` | | `bun zt make:middleware RequireAdmin` | `app/middleware/RequireAdminMiddleware.ts` | | `bun zt make:command SendDigest` | `app/commands/SendDigestCommand.ts` | | `bun zt make:request StorePost` | `app/requests/StorePostRequest.ts` | | `bun zt make:notification OrderShipped` | `app/notifications/OrderShippedNotification.ts` | | `bun zt make:job ProcessPayment` | `app/jobs/ProcessPaymentJob.ts` | | `bun zt make:event UserRegistered` | `app/events/UserRegisteredEvent.ts` | | `bun zt make:listener SendWelcome` | `app/listeners/SendWelcomeListener.ts` | | `bun zt make:observer UserObserver [--model User]` | `app/observers/UserObserver.ts` | | `bun zt make:policy PostPolicy [--model Post]` | `app/policies/PostPolicy.ts` | | `bun zt make:resource UserResource` | `app/resources/UserResource.ts` | | `bun zt make:migration create_posts_table` | `database/migrations/{timestamp}_create_posts_table.ts` | | `bun zt make:factory Post` | `database/factories/PostFactory.ts` | | `bun zt make:seeder PostSeeder` | `database/seeders/PostSeeder.ts` | | `bun zt make:provider Payment [--no-register]` | `app/providers/PaymentProvider.ts` + registers in `bootstrap/providers.ts` | | `bun zt make:package billing` | Full `packages/billing/` package skeleton | ### Queue | Command | Description | | ---------------------------------------------- | ---------------------------------------------------- | | `bun zt queue:work [--queue default] [--once]` | Process jobs. Daemon in production; `--once` for CI. | | `bun zt queue:failed` | List all failed jobs | | `bun zt queue:retry ` | Retry one failed job or all failed jobs | | `bun zt queue:flush [--queue name] [--force]` | Delete all failed jobs from the database | ### Cache | Command | Description | | -------------------- | ------------------------------------------------------- | | `bun zt cache:clear` | Clear all cached values from the configured cache store | ### Scheduler | Command | Description | | ---------------------- | ------------------------------------------------------------ | | `bun zt schedule:list` | List all registered scheduled tasks with their next run time | ## References The command surface lives in `@zerotal/core`. The base `Command` class is what you extend; `CommandRunner` (resolved from the container as `"commands"`) is the registry and dispatcher. ### Command static metadata | Field | Type | Description | | ------------- | ----------- | ----------------------------------------- | | `commandName` | `string` | The name invoked on the CLI. | | `description` | `string` | Shown in `list` and `help`. | | `args` | `ArgDef[]` | Positional arguments the command accepts. | | `flags` | `FlagDef[]` | Named flags the command accepts. | | `needsApp` | `boolean` | Whether the bootstrapped app is injected. | `ArgDef` is `{ name: string; required?: boolean; default?: string }`. `FlagDef` is `{ name: string; short?: string; type: "string" | "boolean" | "number"; description?: string; default?: unknown }`. ### Command instance members | Member | Signature | Description | | ------- | --------------------------------------------- | ------------------------------------------------- | | `run` | `run(): Promise` | The work the command performs (abstract). | | `args` | `Record` | Parsed positional arguments, set before `run()`. | | `rest` | `string[]` | Positionals beyond the declared `args`, in order. | | `flags` | `Record` | Parsed flags, set before `run()`. | | `app` | `unknown` | The application instance, set before `run()`. | ### Output helpers | Method | Signature | Description | | --------- | ------------------------------------------------ | ---------------------------- | | `info` | `info(msg: string): void` | Green success line. | | `warn` | `warn(msg: string): void` | Yellow warning line. | | `error` | `error(msg: string): void` | Red line, written to stderr. | | `line` | `line(msg: string): void` | Cyan line. | | `dim` | `dim(msg: string): void` | Dimmed line. | | `write` | `write(msg: string): void` | Raw write, no newline. | | `newLine` | `newLine(): void` | Blank line. | | `section` | `section(title: string): void` | Bold heading. | | `table` | `table(rows: [string, string][], indent?): void` | Aligned two-column rows. | ### Prompts | Method | Signature | Description | | --------- | --------------------------------------------------------------------- | --------------------------------- | | `ask` | `ask(question: string, defaultValue?: string): Promise` | Text input with optional default. | | `confirm` | `confirm(question: string, defaultValue?: boolean): Promise` | Yes/no confirmation. | | `choice` | `choice(question: string, options: string[]): Promise` | Pick one from a numbered list. | | `secret` | `secret(question: string): Promise` | Hidden input on a Unix TTY. | ### CommandRunner | Method | Signature | Description | | ----------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------ | | `register` | `register(Cmd: CommandClass, aliases?: string[]): void` | Register a command class under its name and aliases. | | `registerAll` | `registerAll(commandClasses: CommandClass[]): void` | Register several classes at once. | | `command` | `command(definition: CommandDefinition, aliases?: string[]): CommandClass` | Build and register a closure command. | | `registerCommand` | `registerCommand(definition: CommandDefinition, aliases?: string[]): CommandClass` | Alias for `command()`. | | `registerLazy` | `registerLazy(name: string, thunk: CommandThunk, aliases?: string[]): void` | Register a command imported lazily on first call. | | `discover` | `discover(dir: string): Promise` | Import a directory and register found command classes. | | `run` | `run(argv: string[]): Promise` | Parse argv, run the command, and `process.exit()`. | | `callInProcess` | `callInProcess(argv: string[], parameters?): Promise<{ code: number; output: string }>` | Run in-process, capture output, no exit. | ## Next steps - [Scaffolding](/docs/scaffolding) — what the `make:` generators produce. - [Scheduler](/docs/scheduler) — register tasks that `schedule:list` reports. - [Queue](/docs/queue) — the worker and queue commands in context. - [Container](/docs/container) — how commands resolve their dependencies. --- Source: https://zerotal.dev/docs/scaffolding # Scaffolding Zerotal's `make:*` commands generate boilerplate files so you spend time on logic, not structure. Each generator writes a typed stub to the conventional path and reports what it created. ```bash # in your project root bun zt make: [flags] ``` Every generator is idempotent: if the target file already exists it reports `File already exists: ` and writes nothing, so it never overwrites your work. ## Generators at a glance | Command | Creates | Notes | | --------------------- | ------------------------------------- | --------------------------------------------------------------------- | | `make:controller` | `app/controllers/.ts` | `--resource` adds CRUD stubs | | `make:middleware` | `app/middleware/.ts` | Pass-through `Pipe` stub | | `make:command` | `app/commands/.ts` | CLI command extending `Command` | | `make:request` | `app/requests/.ts` | `FormRequest` with `rules()` | | `make:notification` | `app/notifications/.ts` | Extends `Notification` | | `make:job` | `app/jobs/.ts` | Queue `Job`, self-registers | | `make:event` | `app/events/.ts` | `--broadcast` extends `BroadcastingEvent` | | `make:listener` | `app/listeners/.ts` | `handle(event)` method | | `make:observer` | `app/observers/.ts` | `--model` sets the target model | | `make:policy` | `app/policies/.ts` | `--model` sets the target model | | `make:resource` | `app/resources/.ts` | API resource transformer | | `make:admin-resource` | `app/admin/Resource.ts` | Admin panel resource for a model | | `make:provider` | `app/providers/Provider.ts` | Auto-registers in `bootstrap/providers.ts` | | `make:package` | `packages//…` | Full `@zerotal/*` package skeleton | | `make:model` | `app/models/.ts` | See [ORM](/docs/orm#generating-models) | | `make:migration` | `database/migrations/…` | See [Migrations](/docs/migrations) | | `make:factory` | `database/factories/Factory.ts` | Name the model, not the factory. See [Factories](/docs/orm/factories) | | `make:seeder` | `database/seeders/.ts` | See [Seeding](/docs/seeding) | ## make:controller ```bash # in your project root bun zt make:controller PostController # Created: app/controllers/PostController.ts bun zt make:controller PostController --resource # Created: app/controllers/PostController.ts (with index/show/store/update/destroy stubs) ``` The basic stub has a single `index` action; `--resource` adds the full CRUD set: `index`, `show`, `store`, `update`, and `destroy`. | Flag | Type | Description | | ------------ | ------- | --------------------- | | `--resource` | boolean | Add CRUD action stubs | ## make:middleware ```bash # in your project root bun zt make:middleware RequireAdminMiddleware # Created: app/middleware/RequireAdminMiddleware.ts ``` The stub implements `Pipe` with a `handle(ctx, next)` method that calls `next()`, plus a commented example of short-circuiting with a `Response`. ## make:command ```bash # in your project root bun zt make:command SendDailyReport # Created: app/commands/SendDailyReport.ts ``` The stub includes `static commandName` (kebab-cased from the class name), `static description`, `static needsApp`, placeholder `args` and `flags` arrays, and an async `run()` method. ## make:request Form requests centralise validation rules away from controller bodies. ```bash # in your project root bun zt make:request StorePostRequest # Created: app/requests/StorePostRequest.ts ``` The stub extends `FormRequest` from `@zerotal/validator` with a `rules(r)` method that returns a `Record`. ## make:notification ```bash # in your project root bun zt make:notification OrderShipped # Created: app/notifications/OrderShipped.ts ``` The stub extends `Notification` and ships with a `channels()` method (defaulting to `['database']`) and a `toDatabase()` method. ## make:job ```bash # in your project root bun zt make:job ProcessPayment # Created: app/jobs/ProcessPayment.ts ``` The stub extends `Job` from `@zerotal/queue`, sets a `default` queue, and calls `JobRegistry.register(...)` at the bottom of the file so the job is dispatchable. ## make:event ```bash # in your project root bun zt make:event UserRegistered # Created: app/events/UserRegistered.ts bun zt make:event OrderShipped --broadcast # Created: app/events/OrderShipped.ts (extends BroadcastingEvent) ``` By default the stub is a plain class with constructor parameters commented as examples. With `--broadcast` (`-b`) it instead extends `BroadcastingEvent` and includes `broadcastOn()` and `broadcastWith()` methods. | Flag | Type | Description | | ------------- | ------- | ----------------------------------------------- | | `--broadcast` | boolean | Generate a broadcastable event (`-b` for short) | > **Tip** — See [Broadcasting](/docs/broadcasting) for channels and authorization > rules used by broadcastable events. ## make:listener ```bash # in your project root bun zt make:listener SendWelcomeEmail # Created: app/listeners/SendWelcomeEmail.ts ``` The stub has a `handle(event: unknown)` method you narrow to the correct event type. ## make:observer ```bash # in your project root bun zt make:observer UserObserver # Created: app/observers/UserObserver.ts bun zt make:observer UserObserver --model User # Same path; stub names its parameters after the model ``` The stub implements `ModelObserver` from `@zerotal/orm` with `creating`/`created`, `updating`/`updated`, and `deleting`/`deleted` hooks. When `--model` is omitted the model name is inferred by stripping the `Observer` suffix. | Flag | Type | Description | | ---------------- | ------ | --------------------------------- | | `--model` (`-m`) | string | Model class this observer targets | ## make:policy ```bash # in your project root bun zt make:policy PostPolicy # Created: app/policies/PostPolicy.ts bun zt make:policy PostPolicy --model Post # Same path; stub references Post in commented imports ``` The stub extends `Policy` from `@zerotal/auth` with `view`, `create`, `update`, and `delete` methods. When `--model` is omitted the model name is inferred by stripping the `Policy` suffix. | Flag | Type | Description | | ---------------- | ------ | ----------------------- | | `--model` (`-m`) | string | Model the policy is for | ## make:resource API resource transformers shape model data before it leaves the controller. ```bash # in your project root bun zt make:resource UserResource # Created: app/resources/UserResource.ts ``` The stub extends `Resource` with a `toArray()` method and includes commented usage examples for single models and paginated `ResourceCollection`s. ## make:provider ```bash # in your project root bun zt make:provider Payment # Created: app/providers/PaymentProvider.ts # Registered in bootstrap/providers.ts bun zt make:provider Payment --no-register # Created: app/providers/PaymentProvider.ts (no codemod) ``` The name is suffixed with `Provider` if it isn't already. The stub extends `ServiceProvider` with `onRegister`, `onBooting`, and `onBooted` hooks ready to fill in. Unless `--no-register` is passed, a codemod appends the provider import and class name to the default export array in `bootstrap/providers.ts`. It is idempotent: rerunning reports `Already registered in bootstrap/providers.ts` rather than duplicating the entry. If `bootstrap/providers.ts` is missing, it warns and leaves the file for you to wire up manually. | Flag | Type | Description | | --------------- | ------- | --------------------------------------- | | `--no-register` | boolean | Skip modifying `bootstrap/providers.ts` | ## make:package Scaffolds a complete, conformant `@zerotal/` package under `packages/`. ```bash # in your project root bun zt make:package billing # Created @zerotal/billing # ./packages/billing/package.json # ./packages/billing/src/index.ts # ./packages/billing/src/config.ts # ./packages/billing/src/BillingManager.ts # ./packages/billing/src/provider/BillingProvider.ts # ./packages/billing/src/facades/Billing.ts # ./packages/billing/src/Billing.test.ts ``` The generated package follows the Zerotal package conventions: a manager class, a service provider (with a container binding and config wiring), a facade, a `XxxConfig()` factory, and a test file. The package name is normalised to a kebab-case token, and class names are derived in PascalCase. By default the package is written under `./packages`; pass a second argument to choose a different base directory: ```bash # in your project root bun zt make:package billing ./vendor ``` After generation, register the new provider and verify the package passes the structural checks: ```bash # in your project root bun zt make:provider Billing # adds BillingProvider to bootstrap/providers.ts bun zt lint:packages # verify the package passes structural checks ``` > **Note** — See [Package Development](/docs/package-development) for the full > package conventions the scaffold conforms to. ## Codemod helpers The underlying codemod utilities are exported from `zerotal` for use in your own generators, install scripts, or migration tools. Each is idempotent — a no-op when the change is already present. ```ts fragment // in your own generator or script import { addImport, addToDefaultArrayExport, registerProvider, type RegisterProviderOptions, type RegisterResult, } from "zerotal/build"; // Add an import after the last existing import (deduped): const withImport = addImport( src, `import { BillingProvider } from "./providers/BillingProvider.ts";`, ); // Append an identifier to the `export default [ ... ]` array literal: const withEntry = addToDefaultArrayExport(src, "BillingProvider"); // Combined: add the import AND register in bootstrap/providers.ts on disk: const result: RegisterResult = await registerProvider({ className: "BillingProvider", importPath: "../app/providers/BillingProvider.ts", // bootstrapPath defaults to "bootstrap/providers.ts" }); ``` > **Note** — These live on the `zerotal/build` subpath rather than the > root barrel: they are build-time tooling for generators, and an application > never calls them at runtime. > **Warning** — `registerProvider` reads and writes a file on disk. `addImport` and > `addToDefaultArrayExport` are pure string transforms — they take source text and > return the transformed text, leaving the file untouched. ## References | Function | Signature | Description | | ------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------ | | `addImport` | `(source: string, importStatement: string) => string` | Insert an import after the last existing import; no-op if already there. | | `addToDefaultArrayExport` | `(source: string, identifier: string) => string` | Append an identifier to an `export default [ … ]` array literal. | | `registerProvider` | `(options: RegisterProviderOptions) => Promise` | Add the import and register a provider in the bootstrap file on disk. | `RegisterProviderOptions`: | Field | Required | Default | Description | | --------------- | -------- | -------------------------- | --------------------------------------------------------------------------- | | `className` | yes | — | Provider class name to import and register. | | `importPath` | yes | — | Import specifier, e.g. `../app/providers/FooProvider.ts` or `@zerotal/foo`. | | `bootstrapPath` | no | `"bootstrap/providers.ts"` | Path to the bootstrap providers file. | `RegisterResult` is `'added' | 'exists' | 'missing'`: | Value | Meaning | | ----------- | ----------------------------------------------------------- | | `'added'` | Provider was written and registered. | | `'exists'` | Already registered; no change made. | | `'missing'` | `bootstrap/providers.ts` not found; nothing was registered. | ## Next steps - [Commands](/docs/commands) — built-in commands and writing your own. - [Service Providers](/docs/providers) — provider lifecycle and what to put in each hook. - [Directory Structure](/docs/structure) — where generated files live. --- Source: https://zerotal.dev/docs/deployment # Deployment A Zerotal app is a Bun process. Deploying it means: install dependencies, set production environment variables, run migrations, build frontend assets if you have them, and start the server (plus a worker if you use queues or the scheduler). If a reverse proxy sits in front of it — and in most deployments one does — read [Behind a reverse proxy](#behind-a-reverse-proxy) before you launch. A proxied app has one failure mode that a green test suite cannot see. ## `bun zt deploy:` One command runs the release and refuses to finish it when something is wrong: ```bash # on the box, with that environment's variables loaded APP_ENV=production bun zt deploy:production ``` It runs four phases, and **everything that can refuse runs before anything that mutates** — a bad origin list stops the deploy while the old release is still serving, rather than after the migration has run: | Phase | What it does | | --------- | ------------------------------------------------------------------------------------------------------------------------------- | | Preflight | Checks this process really is that environment, re-runs every config validator with production semantics, then runs `zt doctor` | | Build | `assets:build`, and `inertia:build --production` if the app has Inertia | | Migrate | `migrate` — skip with `--skip-migrations` | | Verify | `zt doctor` again, now that the schema has one story | It exits non-zero on any failure and **does not restart your service**. That is deliberate: systemd, your container runtime or your deploy script owns process lifecycle, and this gives it a gate to restart behind. ```bash bun zt deploy:production --check # run the gate only — see below bun zt deploy:production --dry-run # print the plan, run none of it bun zt deploy:production --skip-migrations # release without touching the schema bun zt deploy:production --probe=https://example.com # real handshake at the end ``` Every environment gets its own command. `production` and `staging` exist by default; declare more — or give one a URL and its own steps — in `config/deploy.ts`: ```ts import { DeployConfig } from "zerotal/config"; export default DeployConfig({ targets: { production: { url: "https://example.com" }, staging: { url: "https://staging.example.com" }, }, }); ``` The target name is checked against the deployment this process was started as, so `deploy:production` on a staging box stops on the first line instead of migrating the wrong database. Each entry is a `DeployTarget`: | Field | Meaning | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | The public URL in this environment. What `--probe` handshakes against when given no URL of its own. | | `steps` | Override the release steps. Defaults to `DEFAULT_DEPLOY_STEPS` — `assets:build`, `inertia:build`, `migrate`. Each names a `zt` command, and one that is not registered is skipped, so an app without Inertia simply has no Inertia step. | | `preflight` | Your own commands, run in the preflight phase — after the config validators and `doctor`, before anything is built or migrated. A non-zero exit refuses the release. Defaults to `release:check` when the app registers a command by that name. | Omit the file entirely and you get `DEFAULT_DEPLOY_TARGETS`: `production` and `staging`, both with the default steps. ### Your own release gate The framework's preflight knows the things a framework can know: that this really is the environment you think it is, that the config validators pass, that `doctor` is happy — which now includes refusing a production release whose `mail.driver` is still `log`, because mail written to a log file is delivered to nobody and says so nowhere. It cannot know that this workspace has no cancellation policy, or that the owner account is still on the password `admin:create` issued it. Those refusals are yours. Write them as a command and name it `release:check` (exported as `CONVENTIONAL_PREFLIGHT_COMMAND`). The pipeline finds it by name — nothing to wire up: ```ts // app/commands/ReleaseCheckCommand.ts import { Command } from "zerotal"; export class ReleaseCheckCommand extends Command { static commandName = "release:check"; static description = "Refuse a release this app is not ready for"; static needsApp = true; async run(): Promise { const problems: string[] = []; if (Bun.env["APP_KEY"] === "base64:CHANGE_ME") problems.push("APP_KEY is the example one."); if (problems.length > 0) throw new Error(problems.join(" ")); } } ``` A throw, or any non-zero exit, stops the release before `assets:build` has run. To run something else — or more than one thing — name them: ```ts // config/deploy.ts export default { targets: { production: { url: "https://example.com", preflight: ["release:check", "smoke:mail"], }, }, }; ``` A name in `preflight` that is not a registered command **fails the deploy** rather than being skipped. That is the opposite of how `steps` treats an absent command, and deliberately so: a missing `inertia:build` means the app has no Inertia, while a missing gate means the gate is not running — which is the state this exists to prevent. A gate nothing calls is a comment. Two things worth adding while you are there: `assets:build` and `inertia:build` accept `--clean`, which removes anything in the output directory the build did not write — see [Build assets](#build-assets). ### `--check`: the gate on its own A release script has a moment where the new code is on disk and the service has not restarted yet. That is the moment to ask whether this release is fit to go live, and `--check` is the whole preflight and nothing else: ```bash # on the box, after the new release is unpacked and before the restart APP_ENV=production bun zt deploy:production --check || exit 1 systemctl restart app ``` It runs the environment check, the config validators with production semantics, `doctor`, and your own `release:check` — everything that can refuse — and builds nothing, migrates nothing, restarts nothing. Exit 0 and restart; exit non-zero and keep serving the previous release, which is the point. A workspace that has lost its banking details, or had its mail driver knocked back to `log`, never goes live broken. `--check` and `--dry-run` answer different questions. `--dry-run` prints the plan without running any of it, including the gate. `--check` runs the gate for real. > **Note** — `deploy:` runs **where the app runs**, with that environment's > variables. It does not reach another machine over SSH. Run it on the box, or in > the container build, as the step before the restart. ## Production checklist The command above automates most of this. The list is what it runs, and what it cannot do for you. 1. **`APP_ENV=production`** — disables dev-only behavior (N+1 warnings, verbose errors, auto-`synchronize`) and normalizes to the `web` runtime mode. `staging` counts as production for all of it. 2. **Set a strong `APP_KEY`** — required for encryption, signed URLs, and sessions. Generate one with `bun zt key:generate` and store it as a secret. 3. **Set `APP_URL` to the public URL** — the origin browsers actually reach the app on. Endpoints that bypass the middleware pipeline are checked against it. 4. **Point `DATABASE_URL`** at your production database. 5. **Set `app.secureHeaders.secure: true`** once you serve over HTTPS, or no `Strict-Transport-Security` header is sent at all. 6. **Name your CORS origins** — `app.cors.origin: "*"` lets any site read this app's responses out of a visitor's browser. 7. **Run migrations** — never rely on auto-`synchronize` in production (it's hard-off there); ship migration files instead. 8. **Build frontend assets** as a release step, not at boot. 9. **Start the server**, and a **worker** if you use queues/scheduling. 10. **Run `bun zt doctor --url=…`** against the deployed site once it is live — the one check that cannot run before the cutover. Items 1–8 are what `deploy:` checks or does. Starting the process and probing the live site are yours. ### What `--url` sees that nothing else can `bun zt doctor` on its own reads the app from the inside, where the app is right about itself. `--url` fetches the deployed site back through whatever proxy is in front of it, and reports two things only that round trip can show: - **The WebSocket transport**, handshaked as a browser would. A proxy that gates or never forwards the upgrade leaves the app healthy from the inside — the HTML renders, the logs are quiet — while every action in the browser silently does nothing. - **Security headers sent twice.** A header the app sets and the proxy also sets is invisible from inside the process. `X-Frame-Options: DENY` from the proxy plus `SAMEORIGIN` from the app is a real deployment this found, and browsers do not agree on which one applies — a control enforced inconsistently, which is worse than one that is simply missing, because it looks configured. Conflicting values fail; identical duplicates warn. The fix for a duplicate is always the same shape: pick one place — `app.secureHeaders` in `config/app.ts`, or the proxy — and remove the other. ## Environment Set configuration through environment variables (not a committed `.env`). At minimum: ```ini # environment variables (set as platform secrets, not a committed .env) APP_ENV=production APP_URL=https://your.app APP_KEY=… # bun zt key:generate writes a base64 key DATABASE_URL=postgres://user:pass@db-host:5432/app ``` `key:generate` writes a raw 32-byte base64 key into `.env`; both a raw base64 string and a `base64:`-prefixed one are accepted. Generate it **on the server** — a key carried from a laptop is a key that has been in a shell history and a scrollback buffer. **After cloning, `bun zt init:env` does the whole step**: it creates `.env` from `.env.example` with `APP_KEY` (and `SESSION_SECRET`, where the example has one) generated, and leaves an existing `.env` alone. Like every `zt` command it needs the framework installed, so run `bun install` first; if you are preparing `.env` before that, read on. **On a first deploy you do not have to wait for the code.** `key:generate` is part of the application, so it only exists once the release is installed — which is awkward if you are preparing `.env` before that, since `migrate` wants the file and the file wants a key. There is nothing framework-specific about the value: ```bash fragment openssl rand -base64 32 ``` That is exactly what `key:generate` produces — 32 random bytes, base64 — so a key minted this way is indistinguishable from one it wrote. Use whichever fits the order you deploy in. `APP_ENV` accepts deployment names like `production` and `staging`; they all normalize to the `web` runtime mode — they describe _where_ the app runs, not _how_. See [Configuration](/docs/config-system). > **Danger** — store `APP_KEY` as a managed secret, never in a committed file. Losing or rotating it invalidates encrypted values, signed URLs, and active sessions. ## Run migrations Run pending migrations as part of each release, before the new server starts taking traffic: ```bash # in your project root bun zt migrate ``` Auto-`synchronize` is **hard-off in production** — generate and commit [migrations](/docs/migrations) during development and run them on deploy. ## Back up the database On SQLite the database is one file, which makes `cp` look like a backup. It is not one. A live SQLite database has pages in flight; copying the file while the server is serving can capture a half-written page, and the result is a file that sits in your retention directory for months and turns out to be corrupt on the one morning you open it. `zt db:backup` uses SQLite's own `VACUUM INTO`, which takes a read lock and writes a complete database while the server keeps serving. It needs no `sqlite3` binary on the box: ```bash # in your project root bun zt db:backup --dir=/var/backups/app --keep=30 --require-rows=bookings,invoices ``` | Flag | What it does | | ---------------- | ---------------------------------------------------------------------------- | | `--dir` | Where snapshots go. Default `storage/backups`. | | `--keep` | How many to keep, newest first. `0` keeps every one. Default `14`. | | `--require-rows` | Tables that must not be empty in the snapshot. **Set this.** | | `--rehearse` | Also perform the restore — copy the snapshot, open the copy, check it there. | Every snapshot is opened and integrity-checked the moment it is written, and **every failure path exits non-zero**. That is what makes it safe to run from a timer: a bad night leaves a failed unit somebody can see, rather than a green one and no file. `--require-rows` is the flag that turns "a file was written" into "the file has the business in it". An empty `bookings` table in a snapshot of a live system is not a small discrepancy, and it is invisible in a byte count. Run `--rehearse` on a schedule of its own — weekly is plenty. A backup nobody has restored is a hope, and the restore is the operation you will be doing at 3am. ```ini # /etc/systemd/system/app-backup.service [Service] Type=oneshot WorkingDirectory=/srv/app Environment=APP_ENV=production ExecStart=/srv/app/node_modules/.bin/bun zt db:backup --keep=30 --require-rows=bookings ``` Pair it with a `.timer`, and let the failed unit be your alert. Retention is handled by `--keep`; anything the command did not write is never touched. On PostgreSQL or MySQL the command refuses and points at `pg_dump` / `mysqldump`, which is where that job belongs. To take one as part of every deploy, set `backupBeforeMigrate: true` in `config/database.ts`: `zt migrate` then snapshots a SQLite database before it applies anything in production, and stops if the snapshot fails. See [A backup before migrating](/docs/migrations#a-backup-before-migrating-in-production). ## Build assets Build the frontend bundle as a release step, so `public/` holds compiled output before the process starts: ```bash # in your project root bun zt assets:build # every bundle this app declares bun zt inertia:build --production # Inertia (React/Vue) instead ``` `assets:build` covers both sources of bundles: the entrypoints named in `app.assets`, and Flow's conventional `resources/css/app.css` and `resources/js/app.js`. Outside production, `serve` builds these at boot so there is nothing to remember in development. In production it builds them only if the output directory is writable — so a release that built its assets ahead of time and locked the tree down serves what it shipped, and logs one line saying so. That is what lets the service run under a properly hardened unit; see [Hardening the service](#hardening-the-service). ### Replace the asset directory on release, do not merge into it Code splitting names every chunk after its content, so each build emits a new set and abandons the last. Both build commands clean those up as they go, and they do it without needing anything to have survived from the previous build — so the directory a build writes holds that build's output and nothing else, on a developer's machine and a fresh CI checkout alike. What the build cannot clean is a directory it never sees. A release that is **unpacked over the top** of the running one — `tar -xzf` into the app directory, `rsync` without `--delete` — merges: every file in the archive is written, and every file that is not in the archive is left exactly where it was. Nothing on that server ever ran a build, so nothing ever removes last release's chunks, and they collect one release at a time. That is not only clutter. They stay publicly fetchable at their content-hashed URLs, so a page whose copy you withdrew is still readable by anyone holding the link — pricing you took down, a policy you replaced, a feature you pulled. Clear the directory as part of the release, before the new files land: ```bash # on the server, before extracting rm -rf "$APP_DIR/public/assets" tar -xzf release.tgz -C "$APP_DIR" # or let rsync do it rsync -a --delete public/assets/ "$HOST:$APP_DIR/public/assets/" ``` Ordering matters if the old release is still serving traffic: clearing the directory takes its bundles away, so do it as close to the swap as you can, or stage the release in a new directory and move it into place. ### `assets:prune` — clearing up after the extract instead of before it Clearing the directory first has a cost the ordering note above hints at: between the `rm -rf` and the new files landing, the release still serving traffic has no bundles. If you would rather extract over the top and tidy afterwards, `assets:build` records what it wrote and `assets:prune` removes what that record does not claim: ```bash # on the build machine — the record is written under .zerotal/ bun zt assets:build tar -czf release.tgz public .zerotal # ship the record with the release # on the server, after extracting and before the restart bun zt assets:prune --dry-run # list what would go bun zt assets:prune ``` **Ship `.zerotal/` with the release** — that is the part that makes it work. Without the record, "which files belong to this release" has no answer on a server that never ran a build, and `assets:prune` says so and removes nothing rather than guessing. It is conservative by design: it deletes a file only when the record does not claim it _and_ it is named the way the bundler names a code-split chunk. Your images and favicon are never candidates, because an output directory is usually `public/`. ### `--clean` for a directory the build does not own outright The cleanup above recognises the filenames `Bun.build()` produces. An app that sets its own `naming`, or that writes a second bundle into the same directory by other means, can leave output the build does not recognise as its own. `--clean` needs no recognition — whatever this build did not write, goes: ```bash # in your project root bun zt assets:build --clean bun zt inertia:build --production --clean ``` It refuses `public/` itself and the project root, where deleting what was not rebuilt would take the app's images and favicon with it. Point the build at a directory of its own — `public/assets` is the Inertia default. Bump your asset version (or hash the bundle) so clients reload onto the new build — see [Inertia › Asset versioning](/docs/inertia/middleware#asset-versioning). ## Start the server ```bash # in your project root bun zt serve # binds 0.0.0.0 on app.port: PORT, else 3000 bun zt serve --port=8080 # custom port, over PORT ``` A host or container that sets `PORT` gets the app on that port with no flag. A `PORT` that is not a port, such as `80800`, stops `serve` with an error naming it instead of falling back to 3000. Run this under a process supervisor (systemd, Docker, Fly.io, Railway, a PaaS, …) so it restarts on crash. The server installs `SIGTERM`/`SIGINT` handlers and drains gracefully on shutdown, which works cleanly with rolling deploys. Set the port explicitly on a host that already runs something. The default is 3000, which is also what the last app you deployed is using. ### Worker process If you use [queues](/docs/queue) or the [scheduler](/docs/scheduler), run a separate worker process so background work is isolated from request handling and can be scaled independently: ```bash # in your project root bun zt worker ``` This boots in the `worker` environment (no HTTP server) and drains in-flight jobs on shutdown. For small deployments you can instead poll inline from a provider's `onStarted()` — see [Scheduler › Running the worker](/docs/scheduler#running-the-worker) — but a dedicated process is recommended for production. ## Behind a reverse proxy Proxying introduces one failure that nothing in your development loop can reproduce, so it is worth understanding rather than just copying the config below. ### Why a proxied app needs `APP_URL` Two kinds of request bypass the middleware pipeline and therefore carry their own origin check: **WebSocket upgrades**, and **raw routes** — of which Flow's `/__flow/http` action fallback is one. Both are credentialed and neither is protected by [CSRF middleware](/docs/csrf), so each compares the browser's `Origin` header against the origins the app accepts. The app's own origin is always accepted — but "own" means the origin of the request URL, which behind a proxy is the loopback address it bound to (`http://127.0.0.1:3002`), never the public URL the browser sends. So the public origin has to come from config, and it does: `AppConfig()` fills `app.allowedOrigins` from `url`. ```ts fragment // config/app.ts export default AppConfig({ name: "My App", url: env("APP_URL", "http://localhost:3000"), // ← allowedOrigins derives from this }); ``` Name additional origins only when a genuinely different host drives the app — an SPA on `app.example.com` calling `api.example.com`. What you pass is added to the URL's origin rather than replacing it: ```ts fragment // config/app.ts export default AppConfig({ url: env("APP_URL"), allowedOrigins: ["https://admin.example.com"], }); ``` Origins are compared exactly: no wildcards and no suffix matching, because `endsWith(".example.com")` also matches `evil-example.com`. > **Warning** — an app with the wrong origin configured renders every page correctly and refuses every action. There is no 500, nothing in the logs, and a status-code health check passes. The only symptom is that buttons do nothing. ### Rate limiting counts the proxy, not the visitor `ThrottleMiddleware` identifies a client by the address the request arrived from. Behind a proxy that address is the proxy — `127.0.0.1` for every visitor on the site — so one bucket is shared by everybody, and a single busy client can lock the whole site out. Tell it how many proxies sit in front of the app: ```ts fragment // One proxy (Caddy, nginx, a load balancer) between the internet and the app. ThrottleMiddleware.with({ maxAttempts: 60, trustedProxies: 1 }); ``` The count is how many proxies of yours the request went through: the client's address is that many entries from the right of `X-Forwarded-For`, which for one proxy is the last. It is opt-in and defaults to zero because the header is written by the client until something trusted overwrites it: trusting it by default would let anyone forge an address and walk around every limit you set. Zero is the safe default and the wrong answer once you deploy behind something — which is easy to do and never revisit, because nothing about it fails loudly. The symptom is a legitimate visitor getting a 429 they did not earn. Count the proxies you actually run. Setting `trustedProxies: 3` with one proxy in front reads an entry the client supplied. `zt doctor` warns about this: a production-like deployment with a registered throttle and no `trustedProxies` is reported as almost certainly wrong. It is a warning rather than a failure because the framework cannot see your deployment — an app served directly, with nothing in front of it, is correctly configured exactly as it stands. ### Never gate the transport path **Browsers do not attach basic-auth credentials to a WebSocket handshake.** An HTTP auth gate over a whole site — a pre-launch gate, an internal tool — therefore gates the transport, and the app degrades to slow HTTP fallback or stops working entirely. Exempt the transport path: ```caddyfile # Caddyfile your.app { encode zstd gzip @gated not path /__flow/* # browsers don't send basic-auth on a WS handshake basic_auth @gated { staging $2b$12$… } reverse_proxy 127.0.0.1:3002 { flush_interval -1 # long-lived socket: don't buffer or reap it } } ``` Be honest in your own config about the trade-off: action frames are then reachable without the gate password. That is usually fine — a staging gate keeps a site out of search results and away from passers-by, while your app's own login is what protects data, and that still applies to every action arriving this way. But it is a decision, and the next person should find it written down. On a host that already serves other sites, append to the config rather than overwriting it, validate, then reload — a syntax error takes down every app on the box: ```bash # on the server caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy ``` ### Hardening the service ```ini # /etc/systemd/system/your-app.service [Service] User=app WorkingDirectory=/opt/app ExecStart=/opt/app/.bun/bin/bun zt serve --port=3002 Restart=always NoNewPrivileges=true ProtectSystem=strict ProtectHome=read-only PrivateTmp=true ReadWritePaths=/opt/app/database /opt/app/storage ``` Grant write access to the directories the app genuinely writes — its database and its storage disk. Source, `node_modules` and `.env` have no business being writable by the running process. With assets built at deploy time, `public/` does not need to be writable either; if you would rather let the app build at boot, add it to `ReadWritePaths`. Give each app its own copy of Bun under its own directory. A Bun installed as root at `/usr/local/bin/bun` is usually a symlink into `/root/.bun/`, which a service user cannot traverse — the error is `Permission denied`, not `not found` — and a runtime upgrade for one app should not be able to break another. ## Verifying a deploy `bun zt doctor` runs every static check against a release: `APP_KEY` strength, the transport origins, whether the schema has one source of truth, providers that were configured but never registered. ```bash # in your project root, on the server bun zt doctor ``` Static checks run inside the process, and the expensive proxy failures are exactly the ones that cannot be seen from there. `--url` probes the deployed app from the outside, through the real proxy, with a real handshake and a real `Origin`: ```bash # in your project root bun zt doctor --url=https://your.app ``` It reports each registered WebSocket path, and reads the status the server actually returned: `101` means a browser can open the socket; `403` is the origin guard; `401` is an auth gate over the transport; `404` usually means the proxy is not forwarding the path. To check it by hand, pass `--http1.1`. curl over TLS negotiates HTTP/2, where `Connection: Upgrade` is meaningless, and you get a `404` that reads exactly like a broken route on a server that is working perfectly: ```bash curl -s -o /dev/null -w '%{http_code}\n' --http1.1 \ -H 'Origin: https://your.app' -H 'Connection: Upgrade' -H 'Upgrade: websocket' \ -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \ https://your.app/__flow/ws # expect 101 ``` Note that a plain `curl` against an action endpoint proves less than it appears to: a request with **no** `Origin` header is deliberately allowed through, because native and CLI clients do not send one. The check only bites when an origin is declared — which is what a browser always does, and what `--url` reproduces. ### Pre-launch checklist Everything here is something that can pass a green test suite and still break in production. - `APP_URL` is the public URL, and `bun zt doctor` reports it under Transport origins - `bun zt doctor --url=…` returns `101` for every transport path - The transport path is exempt from any proxy-level auth gate - A **browser** — not curl — has clicked a real action against the deployed site - The service survives `systemctl restart` and comes back listening - The app's port doesn't collide with anything already on the host - The service user can execute its own Bun binary - `APP_KEY` was generated on the server, not carried from a laptop - No development database was copied to the server - Backups actually exit `0` — run the unit once and check ## Compile to a single binary `bun zt compile` builds the Bun runtime, the framework, your app and its entry file (`zt.ts`) into one executable: ```bash # in your project root bun zt assets:build # or inertia:build --production bun zt compile --outfile=zerotal-app ``` Copy the binary to the server with what it reads at runtime: `.env`, `public/`, and the directories it writes to, such as `storage/` and an SQLite database. Run it from that directory, since it finds them relative to where it starts: ```bash # on the server, in the app's directory ./zerotal-app migrate ./zerotal-app serve --port=3000 ./zerotal-app worker ``` The binary carries: - **Your app's files**: `app/`, `bootstrap/`, `config/`, `database/` and `routes/`, Inertia's pages under `resources/js/pages/`, translation catalogs under `resources/lang/` or `lang/`, and the HTML templates directly in `resources/`. Another directory the framework should find goes in with `--include=src,modules`. Test files and `.d.ts` files are left out. - **Your Flow pages, compiled.** Each page is compiled when the binary is built, with and without [CSP-safe mode](/docs/flow/components#csp-safe-mode), using your `tsconfig.json`. A page that the CSP-safe compile refuses stops a CSP-safe boot of the binary, as it would stop `bun zt serve`. - **The framework's browser scripts**: the [Flow runtime](/docs/flow/performance#the-client-runtime) and the devtools panel, and the optional packages that were installed when it was built. It does not carry, and does not build: - **Front-end assets.** `serve` does not build them in a binary. It serves the `public/` beside it, so build them before you compile. - **Vue pages for server rendering.** `.vue` files need a compiler at build time that the binary build does not run. Inertia falls back to rendering a Vue page in the browser. React pages are server-rendered. - **Queue worker threads.** With `queue.workers` above zero, each thread loads its jobs from disk. Run `./zerotal-app worker` as its own process instead. Changing a file under `app/` or `config/` changes nothing in a built binary: compile again. The build writes its entry to `.zerotal/compile/entry.ts`, which is rewritten on every compile and is ignored by the starters' `.gitignore`. ## A minimal Dockerfile ```dockerfile # Dockerfile FROM oven/bun:1 AS base WORKDIR /app # Install deps first for better layer caching COPY package.json bun.lock ./ RUN bun install --frozen-lockfile # App source COPY . . RUN bun zt assets:build # omit if you have no frontend bundle ENV APP_ENV=production EXPOSE 3000 # Run migrations then serve (use your platform's release step for migrate in real setups) CMD bun zt migrate && bun zt serve --port=3000 ``` Run the worker as a **second** container/service from the same image with the command `bun zt worker`. On a server with no Node installed, `bun install` can fail on a transitive package whose `postinstall` shells out to `node`. The `bun` npm package is the usual one — its `postinstall` downloads a Bun binary the box already has, and there is no `node` to run the script with. `--ignore-scripts` resolves it, but check what you are skipping first. If your own `package.json` declares `bun`, which is how the runtime check suggests pinning the runtime, skipping scripts skips that package's `postinstall` too, and that script is what puts the real binary at `node_modules/.bin/bun`; without it the file is a placeholder, and anything that runs it fails with a message about a postinstall script that did not run. Use `--ignore-scripts` only for an install that never runs `node_modules/.bin/bun`, such as a server with its own Bun on `PATH`. Otherwise leave scripts on, or, when the `bun` package arrives only as a peer of another package, install with `--omit=peer` instead. Every starter sets `peer = false` under `[install]` in `bunfig.toml` (the ones that use Tailwind since 1.15.6), so it never arrives. An older app can add the same two lines, then delete `node_modules` and install again; an install over the old `node_modules` keeps the copy. To see which packages run an install script: ```bash # every package with an install script, before you skip them all for p in node_modules/*/package.json node_modules/@*/*/package.json; do grep -l '"\(post\|pre\)\?install":' "$p" done ``` ### `startZerotal` options `StartZerotalOptions` is what `zt.ts` may pass — currently `configDir`, for an app whose config does not live at `./config`. `isDevSurfaceAllowed(env)` is the check every dev-only surface gates on, exported so an app's own dev tooling can gate the same way; it **fails closed**, so an unset `APP_ENV` does not qualify. ## Next steps - [Configuration](/docs/config-system) — environment variables and config files. - [Migrations](/docs/migrations) — schema changes shipped with each release. - [Queue](/docs/queue) — what the worker process runs in the background. - [Health](/docs/health) — the health endpoint to wire into your platform's checks. --- Source: https://zerotal.dev/docs/site-gate # Site gate Two states a site can be in that are not "serving the public", and they are not the same thing. **Maintenance** — the site is _down_. Nobody may use it, staff included, because the usual reason a site is down is that its database is being changed underneath it, and letting one person in is letting them into that. Minutes, not weeks. Every request is answered `503` with `Retry-After`. **Private preview** — the site is _up and working perfectly_, for the people invited to it. Not down, not broken, not public yet. Weeks. An invited visitor gets the real site at `200` and can transact on it; the public gets a holding page. Building one and calling it both is the usual mistake, and it is why a pre-launch site ends up behind a `503` that search engines take seriously. ## Turning it on ```bash bun zt down --retry=120 # maintenance bun zt preview # private preview; prints the link bun zt preview --until=2026-09-30 bun zt up # open again bun zt gate:status # what is it doing ``` `zt preview` generates the token when you do not pass one, because a token typed by a person is the only thing between the public and an unlaunched site and nothing rate-limits guesses at it. **Keep the link it prints** — only a hash is stored, so the token cannot be read back. These four commands need no application and are registered in every environment. A maintenance command that only works when the app boots is one you cannot reach at the moment you need it. ## From your own console The framework's job is the primitive; the button is yours. ```ts import { Gate } from "@zerotal/core/gate"; await Gate.preview({ token, until: "2026-09-30", by: user.name }); await Gate.maintenance({ retryAfter: 120, by: user.name }); await Gate.open(); Gate.status(); // { mode, since, until, by, expired } — never the token ``` ## Getting in **A secret link.** `https://example.com/?preview=`. The gate recognises the token, sets a signed `HttpOnly` `SameSite=Lax` cookie, and **redirects to the same URL with the parameter removed.** That redirect is not tidiness. A token left in the address bar travels into `Referer` on every outbound link, into analytics, into screenshots, and into the message where somebody shares "the page I was looking at". Stripping it on first use leaves the secret in a cookie and nowhere else. **A signed-in staff account.** A request whose authenticated user holds a role on the allowlist is admitted without a token, so an app that already has staff accounts does not need a second secret for the same people. It defaults to `["admin"]`: ```ts // config/gate.ts export default { staffRoles: ["admin", "editor"] }; ``` An **allowlist**, and it matters. 1.13.3 shipped the inverse — "anyone whose role is not `customer`" — which in an app whose roles are `user` and `admin` admitted every signed-in visitor and let the public straight through. A gate that fails open is worse than no gate, because it reports success while doing nothing. An app whose staff role is named something this does not list gets no bypass and notices, which is the safe direction to be wrong in. The cookie lasts seven days. A preview cookie with no lifetime means an ex-tester keeps access to a site that has since gone live with real customer data. **Rotating revokes.** `zt preview --token=` invalidates every cookie issued under the previous token, because the way a preview leaks is a tester forwarding the link to somebody who has left. ## What stays reachable These are open whatever the gate is doing: | Path | Why | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `/__zerotal/*` | The health endpoint. Otherwise the uptime monitor pages the on-call about a planned window, and a deploy gate that polls health fails its own release. | | `/css/*`, `/js/*`, `/assets/*`, `/favicon.ico` | A maintenance page that 503s its own stylesheet is an unstyled apology. | **Your webhooks are not on that list, and this is the one that costs money.** A payment provider posting a settlement into a maintenance window gets a `503`, and depending on the provider that is a retry, a dropped callback, or a payment your books never learn about. Nothing can infer which of your routes a third party calls, so it has to be declared: ```ts // config/gate.ts export default { allow: ["/webhooks/", "/api/callbacks/"], }; ``` ## What the public gets during a preview `200` with a holding page by default, which is right for a pre-launch site collecting an email address. Set `publicResponse: "notFound"` when the site's existence is itself not public: ```ts // config/gate.ts export default { publicResponse: "notFound" }; ``` Both are legitimate and the framework does not pick. **Maintenance is always `503`** and is not configurable, because that one is not a preference: a maintenance page served at `200` tells a search engine that "we will be back shortly" is the content of your homepage, and it will index it as such. Sites have lost their rankings to a two-hour window served at the wrong status code. ## Where the state lives `storage/framework/gate.json`, not the database. A flag in the database is unreadable exactly when the database is the thing you are working on, so a maintenance mode kept there works only on the days you did not need it. The file is also why the gate survives a restart — an in-memory flag would be lifted by the very deploy it was supposed to run behind. The preview token is stored as a **hash**. The file sits on disk, readable by anything on the box and copied by every backup, and putting a live credential in it would be the same mistake as an `.env.example` carrying a working key. A file the gate cannot parse reads as **open**, deliberately. Failing closed would take a site down because a JSON file lost a brace, and "the site is up" is the safer error for a mechanism whose whole purpose is to be turned off again. ## It covers raw routes too `Router.raw()` bypasses the middleware pipeline by design — that is what it is for. It does **not** bypass the gate. A gate that covered only the pipeline would be the worst kind, because it gates the homepage and therefore looks like it works. This framework's own documentation site serves every `/docs/*` page from a raw route: with an early build of the gate on, the front page said "coming soon" and every page of content stayed public. Raw routes get no staff bypass, since no session has been resolved by then — the token cookie is the only way through. ## `zt doctor` reports it A gate is the most reversible thing in the framework and the easiest to forget, because when it is working nothing complains: the people who would notice are the ones being kept out, and they have no way to tell you. - **Maintenance in production** is reported as a failure. It is an outage. - **A preview in production** is a warning naming who set it and when, since a pre-launch gate is usually deliberate. - **A preview whose `until` has passed** is its own warning: the file says the site is gated and it is not, so what a reader believes and what visitors get have come apart. ## Reference | Name | Description | | -------------------- | ---------------------------------------------------------------------------- | | `Gate` | Read and write the gate: `maintenance()`, `preview()`, `open()`, `status()`. | | `GateStatus` | What `Gate.status()` returns. Never includes the token. | | `MaintenanceOptions` | `retryAfter`, `by`. | | `PreviewOptions` | `token`, `until`, `by`. | | `GateMiddleware` | The kernel middleware that answers for a closed site. | | `GateState` | The shape written to `storage/framework/gate.json`. | | `GateMode` | `"maintenance" | "preview"`. | | `readGate` | Read the state file, or `null` when the site is open. | | `gateExpired` | Whether a preview's `until` has passed. | | `GATE_FILE` | Path of the state file, relative to the project root. | | `GATE_COOKIE` | Name of the cookie the gate issues. | | `GATE_QUERY` | The query parameter that carries a token — `preview`. | | `bun zt down` | `DownCommand` — maintenance on. | | `bun zt preview` | `PreviewCommand` — private preview on, prints the link. | | `bun zt up` | `UpCommand` — open the site. | | `bun zt gate:status` | `GateStatusCommand` — what the gate is doing. | --- Source: https://zerotal.dev/docs/tutorial # Build Your First App This tutorial builds one feature end to end, in nine milestones. Each one ends with something you can see or run: a page, a passing test, a command's output. The starter you scaffold already has a working example resource, **Projects**: a model, a policy, a form request, a factory, pages and tests. You will not rebuild it. You will add **Tasks inside a project** next to it, using it as the pattern, and then grow the app around them: 1. **[Scaffold and run](/docs/tutorial/scaffold)** — a new app on your machine, signed in as the demo user. 2. **[A model and a migration](/docs/tutorial/model)** — a `tasks` table and the `Task` model. 3. **[Routes and pages](/docs/tutorial/routes-and-pages)** — a page per project that lists its tasks, with a form to add one. 4. **[Validation](/docs/tutorial/validation)** — what a task must contain, and the errors the form shows when it does not. 5. **[A policy](/docs/tutorial/policy)** — only the project's owner can change or delete its tasks. 6. **[A queued notification](/docs/tutorial/notifications)** — an email to whoever a task is assigned to, sent in the background. 7. **[Feature tests](/docs/tutorial/tests)** — every action, and the test that proves a stranger is refused. 8. **[Teams](/docs/tutorial/multi-tenancy)** — `@zerotal/tenancy`, so each team sees only its own projects and tasks. 9. **[Deploy](/docs/tutorial/deploy)** — the release gate, the production checklist, and the app running in production mode. ## Before you start You need [Bun](https://bun.sh) 1.3.14 or later, and nothing else: the starter uses SQLite, and mail is printed to the terminal until you configure a real driver. The [Getting Started](/docs/getting-started) page covers installation in more depth. Every command and every file in this tutorial was run on an app scaffolded from `create-zerotal@1.18.0`. If you are on a later version, the steps still apply; the [Release Notes](/docs/changelog) say what changed. ## React, Vue or Flow The main path uses the **React** starter. Everything on the server — models, migrations, routes that handle forms, validation, policies, notifications, tests and tenancy — is the same in all three. Where a step differs, a short **On Vue** or **On Flow** note says how: - **Vue** differs only in the page components, which are `.vue` files. - **Flow** renders its pages on the server as components registered in `routes/web.ts`, so its page steps differ more. Its form handlers are the same files as React's. [Choosing a frontend](/docs#choosing-a-frontend) explains the difference between them. ## Working with a coding agent The starter ships `AGENTS.md`, an MCP config and skills for the same tasks this tutorial covers: adding a resource, queued notifications, feature tests and tenancy. The tutorial does each step by hand so you know what the agent is doing when it does them for you. See [Agent Surface](/docs/arch). --- Source: https://zerotal.dev/docs/tutorial/scaffold # Scaffold and Run Milestone 1 of 9 in [Build Your First App](/docs/tutorial). ## Scaffold the app ```bash # in the directory that will hold the project bunx create-zerotal@1.18.0 my-app --template=react --yes cd my-app ``` `--yes` takes the defaults for anything not given on the command line. Leave both flags off to be asked instead. The scaffolder installs the dependencies, writes `.env` with a fresh `APP_KEY`, and ends by printing the next steps: ``` Next steps: cd my-app bun zt migrate bun zt db:seed # optional: demo@example.com / password with sample projects bun zt dev ``` > **On Vue** — use `--template=vue`. **On Flow** — use `--template=flow`. Everything on > this page is the same. ## Create the database and run it ```bash # in your project root bun zt migrate bun zt db:seed bun zt dev ``` `migrate` builds the SQLite database at `database/db.sqlite` from the six migrations the starter ships. `db:seed` adds a demo user with twelve projects. `dev` starts the server and rebuilds the frontend when a file changes. (A queue worker joins it in [milestone 6](/docs/tutorial/notifications), once the app has jobs to run.) ``` Zerotal v1.18.0 › dev Local http://localhost:3000 ``` Leave it running in its own terminal for the rest of the tutorial. ## Check it Open and sign in as `demo@example.com` with the password `password`. You land on the dashboard; **Projects** in the sidebar lists the demo projects, ten to a page. Two more checks, from a second terminal, that the starter is sound before you change anything: ```bash # in your project root bun zt test bun zt doctor ``` `bun zt test` ends with `0 fail` (on the React starter, `102 pass`). `bun zt doctor` ends with `All 22 checks passed.` ## What you have The files worth reading before the next milestone are the example resource's. Every milestone copies one of them: | File | What it is | | -------------------------------- | ---------------------------------------------- | | `app/models/Project.ts` | The model, and `toPage()`: what a page is sent | | `app/policies/ProjectPolicy.ts` | Only the owner may see, change or delete | | `app/requests/ProjectRequest.ts` | The form's validation rules | | `app/routes/(auth)/(verified)/` | The routes: the file path is the URL | | `resources/js/pages/projects/` | The pages | | `database/factories/` | Test data | | `tests/projects.test.ts` | Every action, including the refusals | [Directory Structure](/docs/structure) explains the rest of the layout, and [Conventions](/docs/conventions) what is found without being registered. **Next:** [A model and a migration](/docs/tutorial/model). --- Source: https://zerotal.dev/docs/tutorial/model # Add a Model Milestone 2 of 9 in [Build Your First App](/docs/tutorial). A task belongs to a project, has a title, can be ticked off, and can be assigned to someone. In this app [migrations](/docs/migrations) own the schema, so the table needs one as well as the [model](/docs/orm). ## Generate both ```bash # in your project root bun zt make:model Task -m ``` ``` Created: app/models/Task.ts Created: database/migrations/0007_create_tasks_table.ts ``` The generators write a starting point, not the finished file. Replace both. ## The migration ```ts // database/migrations/0007_create_tasks_table.ts import { Migration, Schema } from "zerotal/orm"; export default class CreateTasksTable extends Migration { override async up(): Promise { await Schema.create("tasks", (table) => { table.increments("id"); // Every list of tasks is one project's. table.integer("project_id").index(); table.string("title"); table.boolean("done").default(false); table.integer("assignee_id").nullable().index(); table.timestamps(); }); } override async down(): Promise { await Schema.drop("tasks"); } } ``` ## The model ```ts // app/models/Task.ts import { Model, column, table } from "zerotal/orm"; /** A piece of work inside a project. Whoever owns the project owns its tasks. */ @table("tasks") export class Task extends Model { // The project and the assignee are not on this list: the route sets them in code. static override fillable = ["title", "done"] as const; @column({ type: "number" }) projectId!: number; @column({ type: "string" }) title!: string; @column({ type: "boolean", default: false }) done!: boolean; @column({ type: "number", nullable: true }) assigneeId?: number | null | undefined; /** What a page is sent. */ toPage(): TaskData { return { id: this.id, title: this.title, done: Boolean(this.done) }; } } /** A task as the pages receive it. Mirrored in resources/js/types.ts. */ export interface TaskData { id: number; title: string; done: boolean; } ``` Three things here follow `app/models/Project.ts`: - **`fillable` lists only what a form may set.** `projectId` and `assigneeId` are left off, so no field in a request can move a task into someone else's project. The route assigns them in code. - **Attributes are camelCase, columns snake_case.** `projectId` is stored in `project_id`. The ORM maps one to the other. - **`toPage()` decides what a page receives**, so a column added later is not sent to the browser until you say so. A nullable column is declared `?: T | null | undefined`: the starter turns on `exactOptionalPropertyTypes`, under which clearing the field would not otherwise typecheck. ## Run it ```bash # in your project root bun zt migrate ``` ``` Migrated 1 migration(s). 0007_create_tasks_table ran ``` ## Check it `bun zt migrate:status` now lists `0007_create_tasks_table` as run. To see the table itself, open the REPL, which boots the app with `DB` in scope: ```bash # in your project root bun zt repl ``` ``` zerotal> await DB.table("tasks").get() [] ``` An empty list: the table exists and has no rows yet. Type `.exit` to leave. **Next:** [Routes and pages](/docs/tutorial/routes-and-pages). --- Source: https://zerotal.dev/docs/tutorial/routes-and-pages # Add Routes and Pages Milestone 3 of 9 in [Build Your First App](/docs/tutorial). The starter has a list of projects and an edit form, but no page for a single project. This milestone adds one, with the project's tasks on it. | Method | URL | What it does | File | | -------- | -------------------------- | ----------------------- | ----------------------------- | | `GET` | `/projects/:project` | The project and tasks | `projects/[project]/index.ts` | | `POST` | `/projects/:project/tasks` | Add a task | `projects/[project]/tasks.ts` | | `PATCH` | `/tasks/:task` | Tick it off, or back on | `tasks/[task].ts` | | `DELETE` | `/tasks/:task` | Delete it | `tasks/[task].ts` | All four live under `app/routes/(auth)/(verified)/`, the group whose `_middleware.ts` already requires a signed-in user with a confirmed email address. The file path is the URL, and an exported `GET`, `POST`, `PATCH` or `DELETE` function is the handler for that method. [Routing](/docs/routing) covers the rules. `:project` and `:task` arrive as loaded models — `Project` and `Task` are found by the parameter's name — or the request is answered with a 404 before your code runs. See [route-model binding](/docs/routing#route-model-binding). ## The form request Validation gets its own milestone. For now, a [form request](/docs/validator) that only says a title is a string: ```bash # in your project root bun zt make:request TaskRequest ``` ```ts // app/requests/TaskRequest.ts import { FormRequest } from "zerotal/validator"; import type { RuleBuilder } from "zerotal/validator"; /** What the "add a task" form must contain. */ export class TaskRequest extends FormRequest { rules(r: RuleBuilder) { return { title: r.string(), }; } } ``` ## The routes Add a `GET` to the file that already handles `PUT` and `DELETE` for a project. It checks the project policy's `view` ability, so only the owner gets past it, and renders a page that does not exist yet: ```ts fragment // app/routes/(auth)/(verified)/projects/[project]/index.ts — add to the top import { Inertia } from "@zerotal/inertia"; import { Task } from "@app/models/Task"; // GET /projects/:project — the project and its tasks, oldest first. export const GET = async (http: HttpContext<{ project: Project }>) => { const project = http.params.project; Gate.authorize("view", project); const tasks = await Task.query().where("project_id", project.id).orderBy("id").get(); return Inertia.render("projects/show", { title: project.name, project: project.toPage(), tasks: tasks.map((task) => task.toPage()), }); }; ``` The file already imports `HttpContext`, `Gate` and the `Project` type. Adding a task is a new file. The project comes from the URL and is checked against the policy's `update` ability; the task's `projectId` is set in code: ```ts fragment // app/routes/(auth)/(verified)/projects/[project]/tasks.ts import type { HttpContext } from "zerotal"; import { Gate } from "zerotal/auth"; import type { Project } from "@app/models/Project"; import { Task } from "@app/models/Task"; import { TaskRequest } from "@app/requests/TaskRequest"; // POST /projects/:project/tasks — add a task to the project. export async function POST(http: HttpContext<{ project: Project }>): Promise { const project = http.params.project; Gate.authorize("update", project); const data = await TaskRequest.validate(); const task = new Task(); task.fill({ title: data.title }); // Set in code, never from the form. task.projectId = project.id; await task.save(); http.flash("success", `“${task.title}” was added.`); http.redirect(`/projects/${project.id}`, 303); } ``` Ticking a task off and deleting it share a file: ```ts fragment // app/routes/(auth)/(verified)/tasks/[task].ts import type { HttpContext } from "zerotal"; import type { Task } from "@app/models/Task"; // PATCH /tasks/:task — tick a task off, or back on. export async function PATCH(http: HttpContext<{ task: Task }>): Promise { const task = http.params.task; task.done = !task.done; await task.save(); http.redirect(`/projects/${task.projectId}`, 303); } // DELETE /tasks/:task export async function DELETE(http: HttpContext<{ task: Task }>): Promise { const task = http.params.task; await task.delete(); http.flash("success", `“${task.title}” was deleted.`); http.redirect(`/projects/${task.projectId}`, 303); } ``` > **Warning** — These two handlers check nothing: anyone signed in can tick off or > delete any task by its id. That is deliberate for now, and it is the hole > [milestone 5](/docs/tutorial/policy) closes with a policy. Regenerate the route types, so the pages can call `route("projects.show", …)` with type-checked names and parameters: ```bash # in your project root bun zt route:types ``` ## The page ```bash # in your project root bun zt make:page projects/show ``` Replace the generated component. It is built from the starter's own components, the same ones the edit page uses: ```tsx fragment // resources/js/pages/projects/show.tsx import type { FormEvent, ReactNode } from "react"; import { Head, router, useForm } from "@inertiajs/react"; import AppLayout from "../../Layouts/AppLayout"; import { Button } from "../../Components/Button"; import { Card, CardBody } from "../../Components/Card"; import { TextField } from "../../Components/Field"; import { TrashIcon } from "../../Components/Icon"; import { PageHeader } from "../../Components/PageHeader"; import type { Project, Task } from "../../types"; interface Props { title: string; project: Project; tasks: Task[]; } function ShowProject({ title, project, tasks }: Props) { const form = useForm({ title: "" }); function add(event: FormEvent) { event.preventDefault(); form.post(route("projects.tasks.store", { project: project.id }), { preserveScroll: true, onSuccess: () => form.reset(), }); } return ( <>
    {tasks.map((task) => (
  • router.patch( route("tasks.update", { task: task.id }), {}, { preserveScroll: true }, ) } className="size-4 accent-primary" /> {task.title}
  • ))}
form.setData("title", e.target.value)} />
); } ShowProject.layout = (page: ReactNode) => {page}; export default ShowProject; ``` The page's props are typed from `resources/js/types.ts`. Add `Task` there, under `Project`: ```ts // resources/js/types.ts — add /** A task as the server sends it (app/models/Task.ts, `toPage()`). */ export interface Task { id: number; title: string; done: boolean; } ``` Last, link to the new page. In `resources/js/pages/projects/index.tsx` the project's name links to `projects.edit`; point that first link at `projects.show` instead, and leave the pencil button on `projects.edit`. ```bash # in your project root bun run typecheck ``` It finishes without errors. > **On Vue** — `bun zt make:page projects/show` writes `projects/show.vue`, and the > server side is the same. The component, with the starter's Vue components: > > ```vue > > > > ``` > > The list's link is in `projects/index.vue`. `bun run typecheck` runs `vue-tsc`. > **On Flow** — a page is a component registered in `routes/web.ts`, not a `GET` > export, so leave `projects/[project]/index.ts` as it is and skip `make:page`. Copy > `app/flow/pages/projects/edit.tsx` to `show.tsx` as `ShowProjectPage`: its > `onMount()` authorizes `view` instead of `update`, and loads the tasks onto the > component. Register it after the edit page, inside the `verified` group: > > ```ts fragment > // routes/web.ts > Router.flow("/projects/:project", ShowProjectPage).name("projects.show"); > ``` > > The forms are plain HTML forms that post to the same handlers as above. A browser > form cannot send `PATCH` or `DELETE`, so give it `method="post"` and a > `data-method`, as the project list's delete form does: > > ```tsx fragment >
> >
> ``` > > The list's link is in `app/flow/pages/projects/index.tsx`. ## Check it With `bun zt dev` running, open and click a project's name. The page shows its description and an empty list. Add a task: it appears in the list with a toast saying it was added. Tick it, and it is struck through; the trash button removes it. **Next:** [Validation](/docs/tutorial/validation). --- Source: https://zerotal.dev/docs/tutorial/validation # Validate the Form Milestone 4 of 9 in [Build Your First App](/docs/tutorial). Right now a task's title can be a single space, and there is nowhere to say who a task is for. This milestone adds both: a title of a sensible length, and an optional **Assign to** field that takes the email address of someone with an account. ## The rules ```ts // app/requests/TaskRequest.ts import { FormRequest } from "zerotal/validator"; import type { RuleBuilder } from "zerotal/validator"; /** What the "add a task" form must contain. */ export class TaskRequest extends FormRequest { rules(r: RuleBuilder) { return { title: r.string().trim().min(2).max(200), // Optional: a task can be nobody's yet. When given, it must be someone with an account. assignee: r.string().trim().email().exists("users", "email").optional(), }; } // A blank input posts "", which is a string, not an absent field. Treat it as absent. override prepareForValidation(body: Record) { if (body["assignee"] === "") delete body["assignee"]; return body; } } ``` `trim()` runs before the length check, so spaces do not count towards it. `exists("users", "email")` asks the database. [Validation](/docs/validator) lists every rule. `prepareForValidation()` is there because of how forms work. An empty input is sent as `""`, and for a string field `""` is a value, not a missing one, so `optional()` alone would let it through to `email()` and fail it. Removing the key makes a blank field count as not given. See [Preparing input](/docs/validator#preparing-input). When validation fails, `TaskRequest.validate()` does not return: it sends the visitor back to the form, with the messages in the page's `errors` prop and what they typed in `old`. Your route code only ever sees valid data. ## Use the assignee The route looks the address up and stores the user's id: ```ts fragment // app/routes/(auth)/(verified)/projects/[project]/tasks.ts import { User } from "@app/models/User"; // …in POST, after the projectId line: const assignee = data.assignee ? await User.query().where("email", data.assignee).first() : null; task.assigneeId = assignee?.id ?? null; ``` ## Show the field Add `assignee` to the form's data in `resources/js/pages/projects/show.tsx`, and a second field under the title. `TextField` shows the error under the input when there is one, and the hint otherwise: ```tsx fragment // resources/js/pages/projects/show.tsx const form = useForm({ title: "", assignee: "" }); // …in the form, after the "New task" field: form.setData("assignee", e.target.value)} />; ``` > **On Vue** — the same two changes in `show.vue`: `assignee: ""` in `useForm()`, and > `` with > `:error="form.errors.assignee"`. > **On Flow** — read errors with `this.error("assignee")` and the value typed with > `this.old("assignee")`, as `app/flow/pages/projects/create.tsx` does for its fields. > Give the input `name="assignee"` and an element with `data-error-for="assignee"` for > the message. ## Check it On a project's page, type `x` as the title and `nobody@example.com` as the assignee, and add it. The form comes back with both fields filled in and two messages: ``` The title field must be at least 2 characters. The selected assignee is invalid. ``` Now give it a proper title and leave **Assign to** blank: the task is added. Then add one assigned to `demo@example.com`, which exists. **Next:** [A policy](/docs/tutorial/policy). --- Source: https://zerotal.dev/docs/tutorial/policy # Write a Policy Milestone 5 of 9 in [Build Your First App](/docs/tutorial). The project routes are already guarded: `ProjectPolicy` lets only a project's owner see it, add tasks to it or change it. The task routes are not. `/tasks/:task` takes any id, so anyone signed in can tick off or delete any task in the app. A policy closes that. ## Generate it ```bash # in your project root bun zt make:policy TaskPolicy --model Task ``` The generated class allows everything. Replace it: ```ts fragment // app/policies/TaskPolicy.ts import { Policy } from "zerotal/auth"; import { Project } from "../models/Project.ts"; import type { Task } from "../models/Task.ts"; import type { User } from "../models/User.ts"; /** * Only the owner of a task's project may change or delete the task. * * Async, because the owner is on the project, not the task. Check it with * `Gate.authorizeAsync()`: the synchronous form treats a Promise as a yes. */ export class TaskPolicy extends Policy { async update(user: User, task: Task): Promise { return (await this.ownerOf(task)) === user.id; } async delete(user: User, task: Task): Promise { return (await this.ownerOf(task)) === user.id; } private async ownerOf(task: Task): Promise { return (await Project.find(task.projectId))?.userId; } } ``` There is nothing to register. A class in `app/policies/` named `TaskPolicy` is the policy for `Task`. [Authorization](/docs/authorization#gate-policies) covers policies and the `Gate`. The owner is on the project, so the policy has to load it, which makes its methods async. That matters at the call site: `Gate.authorize()` is synchronous and treats the returned Promise as truthy, so it would allow everyone. Use `Gate.authorizeAsync()`. ## Check it on every route ```ts fragment // app/routes/(auth)/(verified)/tasks/[task].ts import type { HttpContext } from "zerotal"; import { Gate } from "zerotal/auth"; import type { Task } from "@app/models/Task"; // PATCH /tasks/:task — tick a task off, or back on. export async function PATCH(http: HttpContext<{ task: Task }>): Promise { const task = http.params.task; await Gate.authorizeAsync("update", task); task.done = !task.done; await task.save(); http.redirect(`/projects/${task.projectId}`, 303); } // DELETE /tasks/:task export async function DELETE(http: HttpContext<{ task: Task }>): Promise { const task = http.params.task; await Gate.authorizeAsync("delete", task); await task.delete(); http.flash("success", `“${task.title}” was deleted.`); http.redirect(`/projects/${task.projectId}`, 303); } ``` A denial throws, and the exception handler answers it with a 403 and the starter's error page. The project page and the add-a-task route were already covered by `ProjectPolicy`'s `view` and `update`. ## Check it Test the policy on its own. It needs a project in the database, so first a factory for tasks, to go with the starter's `ProjectFactory` and `UserFactory`: ```bash # in your project root bun zt make:factory Task ``` Name the model, not the factory: `make:factory Task` writes `TaskFactory`. Replace the generated file: ```ts fragment // database/factories/TaskFactory.ts import { Factory } from "zerotal/testing"; import { Task } from "../../app/models/Task.ts"; /** * A task with a made-up title. Give it a project: * * await TaskFactory.for(project).create(); */ export const TaskFactory = Factory.define(Task, (fake) => ({ title: fake.sentence(), done: false, })); ``` `done` is listed although the column has a default: the factory's types cannot see a database default, so they ask for every column that is not optional. `.for(project)` fills `projectId` from the project. [Factories](/docs/orm/factories) has the rest. Then the test, next to the starter's `tests/project-policy.test.ts`: ```ts fragment // tests/task-policy.test.ts import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { refreshDatabase, type TestApp } from "zerotal/testing"; import { TaskPolicy } from "../app/policies/TaskPolicy"; import { TaskFactory } from "../database/factories/TaskFactory"; import { ProjectFactory } from "../database/factories/ProjectFactory"; import { UserFactory } from "../database/factories/UserFactory"; import { bootApp } from "./support"; let app: TestApp; beforeAll(async () => { app = await bootApp(); }); afterAll(() => app.close()); describe("task policy", () => { refreshDatabase(); const policy = new TaskPolicy(); test("lets the project's owner change and delete a task", async () => { const owner = await UserFactory.create(); const project = await ProjectFactory.for(owner).create(); const task = await TaskFactory.for(project).create(); expect(await policy.update(owner, task)).toBe(true); expect(await policy.delete(owner, task)).toBe(true); }); test("refuses everyone else", async () => { const owner = await UserFactory.create(); const stranger = await UserFactory.create(); const project = await ProjectFactory.for(owner).create(); const task = await TaskFactory.for(project).create(); expect(await policy.update(stranger, task)).toBe(false); expect(await policy.delete(stranger, task)).toBe(false); }); }); ``` ```bash # in your project root bun zt test tests/task-policy.test.ts ``` ``` 2 pass 0 fail ``` The test that sends a stranger's request through the routes, and sees the 403, is part of the [next-but-one milestone](/docs/tutorial/tests). **Next:** [A queued notification](/docs/tutorial/notifications). --- Source: https://zerotal.dev/docs/tutorial/notifications # Send a Queued Notification Milestone 6 of 9 in [Build Your First App](/docs/tutorial). When a task is assigned, its assignee should hear about it. Sending mail from inside the request makes the visitor wait for the mail server, and loses the message if the server is down. Queue it instead: the request stores a job and returns, and a worker sends it. ## The notification ```bash # in your project root bun zt make:notification TaskAssignedNotification ``` ```ts // app/notifications/TaskAssignedNotification.ts import { config } from "zerotal"; import { MailMessage, Notification } from "@zerotal/notifications"; /** * "You have a new task." Queued, so it is rebuilt from JSON by the worker: it holds * plain values, not the Task model. */ export class TaskAssignedNotification extends Notification { constructor( private readonly title: string, private readonly projectId: number, ) { super(); } channels(): string[] { return ["mail"]; } toMail(): MailMessage { return new MailMessage() .subject(`New task: ${this.title}`) .line(`You have been assigned “${this.title}”.`) .action("Open the project", `${config("app.url")}/projects/${this.projectId}`); } } ``` A queued notification is stored as JSON and rebuilt by the worker, so it holds plain values. A model instance does not survive the trip. [Notifications](/docs/notifications) explains what does, and how a class outside `app/notifications/` is found. ## Send it `User` already composes `Notifiable`, the mixin behind the starter's verification and password-reset mail. `notifyLater()` queues; `notify()` would send inline. In the add-a-task route, after the task is saved: ```ts fragment // app/routes/(auth)/(verified)/projects/[project]/tasks.ts import { TaskAssignedNotification } from "@app/notifications/TaskAssignedNotification"; // …in POST, after `await task.save();`: // Queued: the request does not wait for the mail server. if (assignee) await assignee.notifyLater(new TaskAssignedNotification(task.title, project.id)); ``` ## Register the queue Try it now, and adding an assigned task fails with a 500: ``` FacadeBindingMissingError: Could not resolve the "queue" facade. ``` The starter sends its own mail inline, so it does not register a queue. Add `@zerotal/queue` at the version the rest of the app is on: ```bash # in your project root bun add @zerotal/queue@~1.18.0 ``` ```ts // config/queue.ts import { QueueConfig } from "@zerotal/queue"; export default QueueConfig({ // Jobs are stored in the app's SQLite database until a worker runs them. driver: "sqlite", // Queued notifications go on their own "notifications" queue. List it, or no worker drains it. queues: ["default", "notifications"], }); ``` Register the provider in `bootstrap/providers.ts`, before `NotificationProvider`: ```ts fragment // bootstrap/providers.ts import { QueueProvider } from "@zerotal/queue"; const providers = [ // … AuthProvider, QueueProvider, NotificationProvider, // … ]; ``` The `queues` list matters. A queued notification is pushed onto a queue named `notifications`, and a worker that drains only `default` would leave every one of them waiting, with no error anywhere. [Queue](/docs/queue) covers the drivers and the worker. ## Check it Restart `bun zt dev`: providers are read at boot. Its output now includes a third process alongside the server and the asset build: ``` [queue ] Processing queue(s) [default, notifications] — Ctrl+C to stop. ``` On a project's page, add a task assigned to `demo@example.com`. The page answers at once, and a moment later the queue worker prints the message, since mail is logged rather than sent in development: ``` [queue ] [Mail] 2026-11-26T05:40:18.069Z [queue ] To: Demo User [queue ] From: my-app [queue ] Subject: New task: Review the focus order [queue ] [queue ] [Text] [queue ] Hello, [queue ] [queue ] You have been assigned “Review the focus order”. [queue ] [queue ] Open the project: http://localhost:3000/projects/12 [queue ] [queue ] Regards, ``` The HTML version of the message follows it. `bun zt doctor` now reports `All 23 checks passed.`: the new one is the queue worker check. **Next:** [Feature tests](/docs/tutorial/tests). --- Source: https://zerotal.dev/docs/tutorial/tests # Write Feature Tests Milestone 7 of 9 in [Build Your First App](/docs/tutorial). The policy test from milestone 5 checks the policy. A feature test checks the app: it sends a request through the router, middleware, validation, policy and database, and asserts on the response and on what was stored. `tests/projects.test.ts` is the starter's; this is the same thing for tasks. ## The tests ```ts fragment // tests/tasks.test.ts import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; import { NotificationFake } from "@zerotal/notifications"; import { assertDatabaseHas, assertDatabaseMissing, refreshDatabase, type TestApp, } from "zerotal/testing"; import { Task } from "../app/models/Task"; import { TaskAssignedNotification } from "../app/notifications/TaskAssignedNotification"; import { ProjectFactory } from "../database/factories/ProjectFactory"; import { TaskFactory } from "../database/factories/TaskFactory"; import { UserFactory } from "../database/factories/UserFactory"; import { bootApp } from "./support"; let app: TestApp; let notifications: NotificationFake; beforeAll(async () => { app = await bootApp(); }); afterAll(() => app.close()); beforeEach(() => { app.actingAsGuest(); notifications = NotificationFake.install(); }); afterEach(() => notifications.restore()); describe("tasks", () => { refreshDatabase(); test("shows a project with its tasks", async () => { const user = await UserFactory.create(); const project = await ProjectFactory.for(user).create(); await TaskFactory.for(project).create({ title: "Write the launch post" }); (await app.actingAs(user).get(`/projects/${project.id}`)) .assertOk() .assertInertia("projects/show"); }); test("adds a task to a project", async () => { const user = await UserFactory.create(); const project = await ProjectFactory.for(user).create(); const res = await app .actingAs(user) .postForm(`/projects/${project.id}/tasks`, { title: "Write the launch post", assignee: "" }); res.assertRedirect(`/projects/${project.id}`); await assertDatabaseHas("tasks", { title: "Write the launch post", project_id: project.id }); notifications.assertNothingSent(); }); test("rejects a task without a proper title", async () => { const user = await UserFactory.create(); const project = await ProjectFactory.for(user).create(); const res = await app .actingAs(user) .postForm( `/projects/${project.id}/tasks`, { title: "x", assignee: "nobody@example.com" }, { Referer: `${app.baseUrl}/projects/${project.id}` }, ); res.assertRedirect(`/projects/${project.id}`); res.assertInvalid(["title", "assignee"]); await assertDatabaseMissing("tasks", { title: "x" }); }); test("queues a notification for the assignee", async () => { const owner = await UserFactory.create(); const assignee = await UserFactory.create(); const project = await ProjectFactory.for(owner).create(); await app .actingAs(owner) .postForm(`/projects/${project.id}/tasks`, { title: "Review", assignee: assignee.email }); await assertDatabaseHas("tasks", { title: "Review", assignee_id: assignee.id }); notifications.assertQueued(assignee, TaskAssignedNotification); notifications.assertNotSentTo(owner, TaskAssignedNotification); }); test("ticks a task off", async () => { const user = await UserFactory.create(); const project = await ProjectFactory.for(user).create(); const task = await TaskFactory.for(project).create(); (await app.actingAs(user).patch(`/tasks/${task.id}`, {})).assertRedirect( `/projects/${project.id}`, ); expect((await Task.find(task.id))?.done).toBeTruthy(); }); test("refuses anyone but the project's owner", async () => { const owner = await UserFactory.create(); const stranger = await UserFactory.create(); const project = await ProjectFactory.for(owner).create(); const task = await TaskFactory.for(project).create({ title: "Private" }); (await app.actingAs(stranger).get(`/projects/${project.id}`)).assertForbidden(); ( await app.actingAs(stranger).postForm(`/projects/${project.id}/tasks`, { title: "Sneaky" }) ).assertForbidden(); (await app.actingAs(stranger).patch(`/tasks/${task.id}`, {})).assertForbidden(); (await app.actingAs(stranger).delete(`/tasks/${task.id}`)).assertForbidden(); const unchanged = await Task.find(task.id); expect(unchanged?.done).toBeFalsy(); await assertDatabaseMissing("tasks", { title: "Sneaky" }); }); }); ``` What each part relies on: - **`bootApp()`** from `tests/support.ts` boots the app from its own bootstrap against an in-memory database built by the real migrations. **`refreshDatabase()`** runs each test in a transaction that is rolled back, so every test starts from the same empty tables. - **`app.actingAs(user)`** signs the next request in as that user; **`actingAsGuest()`** in `beforeEach` keeps one test's user out of the next. - **`NotificationFake`** records notifications instead of sending them. Install it before each test and restore it after. `assertQueued()` checks the notification went through `notifyLater()`, not `notify()`. - **`assertInvalid()`** reads the field errors a failed `validate()` stored, so the test names the fields that failed without matching their wording. [Testing](/docs/testing) and [HTTP Tests](/docs/testing/http) cover every assertion. > **On Flow** — a Flow page is HTML, not an Inertia response. Replace > `assertInertia("projects/show")` with the starter's helpers from `tests/html.ts`, > as `tests/projects.test.ts` does: `assertPage(res, project.name)` checks the page's > title, and `attributes(page, "data-task")` reads a `data-task` attribute you put on > each row. Everything else is the same. ## The refusal test The last test is the one that matters most and gets written least. It signs in as someone who does not own the project and tries everything: open the page, add a task, tick one off, delete one. Every request must be refused, and nothing may change. Make sure it can fail. Comment out the `authorizeAsync` line in the `PATCH` handler of `tasks/[task].ts` and run the file: ``` error: Expected HTTP 403 but got 303. (fail) tasks > refuses anyone but the project's owner 5 pass 1 fail ``` The stranger's request went through and redirected, as a successful one does. Put the line back. ## Check it ```bash # in your project root bun zt test tests/tasks.test.ts ``` ``` 6 pass 0 fail ``` Then the whole suite, which now includes the policy test: ```bash # in your project root bun zt test ``` It ends with `110 pass` and `0 fail` on the React starter. **Next:** [Teams](/docs/tutorial/multi-tenancy). --- Source: https://zerotal.dev/docs/tutorial/multi-tenancy # Add Teams Milestone 8 of 9 in [Build Your First App](/docs/tutorial). So far each project belongs to one person. In a product people share, the unit is a **team**: everything a team creates is the team's, and nobody outside it can see it. Filtering every query by hand is how that goes wrong — one forgotten `where` and a customer sees another's data. `@zerotal/tenancy` does it for you: it works out the team for each request, adds the team to every query on a team-owned model, and fills it in on every new row. [Multi-Tenancy](/docs/tenancy) is the reference; this page applies it. In this app the team is the **tenant**, every account gets one when it signs up, and a request belongs to the signed-in user's team. ## Install and configure ```bash # in your project root bun add @zerotal/tenancy@~1.18.0 ``` The team is read off the signed-in user, from a `tenantId` attribute this milestone adds to `User`: ```ts // config/tenancy.ts import { AuthResolver, TenancyConfig } from "@zerotal/tenancy"; export default TenancyConfig({ // A request belongs to the signed-in user's team: users.tenant_id. resolvers: [new AuthResolver()], }); ``` Register the provider after `AuthProvider`, which is what puts the user on the request. The provider installs the middleware that resolves the team; do not add it yourself: ```ts fragment // bootstrap/providers.ts import { TenancyProvider } from "@zerotal/tenancy"; import tenancyConfig from "../config/tenancy"; const providers = [ // … AuthProvider, TenancyProvider.withConfig(tenancyConfig), QueueProvider, // … ]; ``` The package owns the `tenants` and `tenant_members` tables and creates them when the app boots. You do not write a migration for those. ## The columns `users` gets the team its user works in; `projects` and `tasks` get the team that owns them: ```bash # in your project root bun zt make:migration add_tenant_id_columns ``` ```ts // database/migrations/0008_add_tenant_id_columns.ts import { Migration, Schema } from "zerotal/orm"; const TABLES = ["users", "projects", "tasks"]; export default class AddTenantIdColumns extends Migration { override async up(): Promise { for (const name of TABLES) { // On users it is the team they are working in; on the others, the team that owns the row. await Schema.table(name, (table) => { table.integer("tenant_id").nullable().index(); }); } } override async down(): Promise { for (const name of TABLES) { // SQLite will not drop an indexed column, so the index goes first, in its own step. await Schema.table(name, (table) => { table.dropIndex(["tenant_id"]); }); await Schema.table(name, (table) => { table.dropColumn("tenant_id"); }); } } } ``` ## The models On `User`, next to `role`: ```ts fragment // app/models/User.ts /** The team this user works in. Set in code (app/support/teams.ts), never from a form. */ @column({ type: "number", nullable: true }) tenantId?: number | null | undefined; ``` `Project` and `Task` become team-owned by composing `Tenantable`. The change is the same in both files: ```ts // app/models/Task.ts (and the same in app/models/Project.ts) import { Model, column, table } from "zerotal/orm"; import { Tenantable } from "@zerotal/tenancy"; @table("tasks") export class Task extends Model.using(Tenantable) { static override fillable = ["title", "done"] as const; // The team that owns the row. Tenantable fills it on create and scopes every query by it. static override tenantColumn = "tenantId"; @column({ type: "number" }) tenantId!: number; // …the rest of the model as before } ``` `tenantColumn` names the model's attribute, `tenantId`, not the database column. With `@column` declarations a model saves only the attributes it declares, and the value `Tenantable` sets on create has to be one of them. Left at its default, `tenant_id`, every new row would be saved with no team. From here on, every query on `Project` or `Task` inside a request is limited to the user's team, and every new one is stamped with it. Outside a team — a query with no signed-in user, a console command — they match nothing at all, rather than everything. ## Give every account a team One helper, used wherever an account is created: ```ts fragment // app/support/teams.ts import { Tenant, TenantModel } from "@zerotal/tenancy"; import type { User } from "@app/models/User"; /** Give a new user a team of their own, with them as its admin, and work in it. */ export async function createTeamFor(user: User): Promise { // forceCreate: every value here is built in code, none comes from a form. const team = await TenantModel.forceCreate({ slug: `team-${user.id}`, name: `${user.name}’s team`, isActive: true, }); await Tenant.run(team, () => Tenant.addMember(user.id, { admin: true })); user.tenantId = team.id; await user.save(); return team; } ``` `TenantModel.forceCreate()` rather than `Tenant.create()`: `Tenant.create()` enrolls the signed-in user as the team's admin, and at registration nobody is signed in yet, so this adds the new user explicitly. `forceCreate()` is the right call for values built in code. Call it after the user is saved in the three places that create one: the registration route, the social sign-in helper and the seeder. ```ts fragment // app/routes/(guest)/register.ts and app/auth/social.ts import { createTeamFor } from "@app/support/teams"; // …right after `await user.save();` await createTeamFor(user); ``` The seeder creates the demo projects outside any request, so it runs that part inside the demo team: ```ts fragment // database/seeders/DatabaseSeeder.ts import { Tenant } from "@zerotal/tenancy"; import { createTeamFor } from "@app/support/teams"; // …after `await demo.save();` await createTeamFor(demo); // …and around the loop that creates the projects: // Inside the demo team, so each project is stamped with its tenant_id. await Tenant.forId(demo.tenantId!, async () => { for (const [name, description, status] of projects) { // …unchanged } }); ``` ## Assign only teammates The assignee rule from milestone 4 accepts anyone with an account. Now it should be someone in the team. Add the check to the add-a-task route, after the assignee is looked up: ```ts fragment // app/routes/(auth)/(verified)/projects/[project]/tasks.ts import { rejectInput } from "@app/support/validation"; import { Tenant } from "@zerotal/tenancy"; // …in POST, after the `const assignee = …` line: // Only someone in this team can be given its work. if (assignee && !(await Tenant.isMember(assignee.id))) { rejectInput( http, { assignee: "Assign the task to someone in your team." }, `/projects/${project.id}`, ); } ``` `rejectInput()` is the starter's helper for a check `validate()` cannot make: it fails the form the same way. ## Rebuild your development data The demo projects in your database were created before teams existed, so they belong to none, and the demo user has no team: signed in, you would now see an empty list. Start the development database again. Stop `bun zt dev` first, then: ```bash # in your project root rm database/db.sqlite* bun zt migrate bun zt dev ``` and, once `dev` is up, from another terminal: ```bash # in your project root bun zt db:seed ``` The order matters. The `tenants` table is created when the app boots as a server, a worker or a test run, not by a console command, so `db:seed` needs `dev` to have started once. `migrate:fresh` is not a substitute here: it leaves the package's tables as they are, and the old teams would stay behind. ## Update the tests Three things change for tests. **Every test user needs a team**, as every real one now has. Give the starter's `UserFactory` an `afterCreate`: ```ts fragment // database/factories/UserFactory.ts import { createTeamFor } from "../../app/support/teams.ts"; export const UserFactory = Factory.define(User, (fake) => ({ // …unchanged })).afterCreate(async (user) => { // Every account has a team, as registration gives it one. await createTeamFor(user); }); ``` **Factories skip model hooks** unless told otherwise, and `Tenantable`'s hook is what stamps the team. Add `.dispatchEvents()` to `ProjectFactory` and `TaskFactory`: ```ts fragment // database/factories/TaskFactory.ts (and the same in ProjectFactory.ts) export const TaskFactory = Factory.define(Task, (fake) => ({ title: fake.sentence(), done: false, })) // Factories skip model hooks unless told otherwise, and Tenantable's hook is what // stamps the team on a new row. Create these inside a team: inTeam() in tests/support.ts. .dispatchEvents(); ``` **Test data is created and read inside a team.** A test is not a request, so there is no team until you open one. Two helpers in `tests/support.ts`: ```ts fragment // tests/support.ts import { Tenant } from "@zerotal/tenancy"; import type { User } from "../app/models/User.ts"; /** * Run `fn` inside the user's team, where every request they make runs. Projects and * tasks are scoped to a team: created outside one they belong to no team, and read * outside one they are not found. */ export function inTeam(user: User, fn: () => Promise): Promise { return Tenant.forId(user.tenantId!, fn); } /** Move `user` into `owner`'s team, as a member who does not own its projects. */ export async function joinTeam(user: User, owner: User): Promise { await inTeam(owner, () => Tenant.addMember(user.id)); user.tenantId = owner.tenantId; await user.save(); } ``` Then wrap each factory call and each `find()` on a project or task in `tests/projects.test.ts`, `tests/tasks.test.ts` and `tests/task-policy.test.ts`: ```ts fragment // before const project = await ProjectFactory.for(user).create(); expect((await Project.find(project.id))?.name).toBe("Renamed"); // after const project = await inTeam(user, () => ProjectFactory.for(user).create()); expect((await inTeam(user, () => Project.find(project.id)))?.name).toBe("Renamed"); ``` In `task-policy.test.ts` the policy calls go inside the team too, since the policy loads the project. The refusal tests change meaning. A user from another team now gets a 404 — to them the project does not exist — so a 403 test needs a teammate who is not the owner. In both `projects.test.ts` and `tasks.test.ts`, put the stranger in the owner's team: ```ts fragment const owner = await UserFactory.create(); const stranger = await UserFactory.create(); // In the same team, so the project is visible to them and only the policy stands in the way. await joinTeam(stranger, owner); ``` The notification test's assignee needs `joinTeam(assignee, owner)` as well, and a new test covers the rule above: ```ts fragment // tests/tasks.test.ts test("assigns only to someone in the team", async () => { const owner = await UserFactory.create(); const outsider = await UserFactory.create(); const project = await inTeam(owner, () => ProjectFactory.for(owner).create()); const res = await app .actingAs(owner) .postForm(`/projects/${project.id}/tasks`, { title: "Review", assignee: outsider.email }); res.assertInvalid(["assignee"]); notifications.assertNothingSent(); }); ``` ## The isolation test This is the test the whole milestone exists for. Write it as a negative, and assert a count: ```ts fragment // tests/teams.test.ts import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; import { refreshDatabase, type TestApp } from "zerotal/testing"; import { Project } from "../app/models/Project"; import { Task } from "../app/models/Task"; import { ProjectFactory } from "../database/factories/ProjectFactory"; import { TaskFactory } from "../database/factories/TaskFactory"; import { UserFactory } from "../database/factories/UserFactory"; import { bootApp, inTeam } from "./support"; /** The test the whole of tenancy exists for: one team never sees another's rows. */ let app: TestApp; beforeAll(async () => { app = await bootApp(); }); afterAll(() => app.close()); beforeEach(() => app.actingAsGuest()); describe("teams", () => { refreshDatabase(); test("a team cannot see another team's projects or tasks", async () => { const alice = await UserFactory.create(); const bob = await UserFactory.create(); await inTeam(alice, async () => { const project = await ProjectFactory.for(alice).create(); await TaskFactory.for(project).create(); }); // Count, not the absence of one row: a query that ignored the team would return everything. expect(await inTeam(bob, () => Project.query().get())).toHaveLength(0); expect(await inTeam(bob, () => Task.query().get())).toHaveLength(0); expect(await inTeam(alice, () => Project.query().get())).toHaveLength(1); }); test("another team's project is not found, not just forbidden", async () => { const alice = await UserFactory.create(); const bob = await UserFactory.create(); const project = await inTeam(alice, () => ProjectFactory.for(alice).create()); (await app.actingAs(bob).get(`/projects/${project.id}`)).assertNotFound(); }); test("a new account gets a team of its own", async () => { const user = await UserFactory.create(); expect(user.tenantId).toBeNumber(); }); }); ``` `toHaveLength(0)` fails loudly if scoping breaks. Checking that one particular row is missing would pass a query that returned everything else. ## Check it ```bash # in your project root bun zt test ``` ``` 114 pass 0 fail ``` Make sure the isolation test can fail: change `Project` back to `extends Model`, run the suite, and both of the first two `teams` tests fail. Put it back. Run the suite once with `bun zt test --isolate` as well, which gives each test file a fresh process, so no file can pass on state another left behind. `bun zt doctor` now warns that `AGENTS.md` describes a different project: the app's packages have changed since the file was written. Refresh it, and the skills with it: ```bash # in your project root bun zt arch:update ``` Then in the browser: sign in as `demo@example.com`, and the demo projects are there. In a private window, register a new account and follow the verification link printed in the `dev` output. Its project list is empty, and opening the URL of one of the demo's projects answers 404. **Next:** [Deploy it](/docs/tutorial/deploy). --- Source: https://zerotal.dev/docs/tutorial/deploy # Deploy It Milestone 9 of 9 in [Build Your First App](/docs/tutorial). A Zerotal app is a Bun process: install, set the environment, migrate, build the frontend, start the server, and start a worker for the queue. `bun zt deploy:` runs the release part of that and refuses to finish when something is wrong. [Deployment](/docs/deployment) is the full guide, including proxies, Docker and a single compiled binary. This milestone rehearses a release on your own machine, so you see every refusal before a server does. ## See the plan ```bash # in your project root APP_ENV=production bun zt deploy:production --dry-run ``` ``` Deploy → production APP_ENV production preflight config validators, then doctor checks step assets:build step inertia:build step migrate verify doctor checks again Dry run — no steps executed. (The app was booted to resolve them.) ``` `production` and `staging` exist by default; `config/deploy.ts` adds more. The command runs where the app runs, with that environment's variables. It does not reach a server over SSH. ## Run the gate `--check` runs only the preflight: everything that can refuse, and nothing that builds, migrates or restarts. Rehearse with a separate database, so your development data is not touched: ```bash # in your project root APP_ENV=production DATABASE_URL=./database/production.sqlite bun zt deploy:production --check ``` It refuses. Most lines are warnings, marked `!`; one is a failure, marked `✗`, and that is enough to stop the release: ``` ✗ Transport origins — app.url is http://localhost:3000 in a production environment, so allowedOrigins is a loopback address. Browsers send the public origin, which is not in the list — every credentialed action will be refused. fix: Set APP_URL to the public URL the site is served from. ✖ 1 check(s) failed at preflight. Nothing further has run — fix these and deploy again. ``` ## The production environment Each refusal names a variable to set. In production these are your platform's secrets, not a committed file. For the rehearsal, put them in `.env.production`. The starter's `.gitignore` and `.dockerignore` already keep every `.env.*` file except `.env.example` out of the repository and the image, so this one stays on your machine: ```bash # .env.production APP_ENV=production APP_URL=https://tasks.example.com APP_SECURE=true DATABASE_URL=./database/production.sqlite HEALTH_KEY=rehearsal-health-key MAIL_DRIVER=smtp MAIL_FROM_ADDRESS=hello@tasks.example.com SMTP_HOST=smtp.example.com SMTP_USERNAME=apikey SMTP_PASSWORD=not-a-real-password ``` What each one is for: - **`APP_URL`** — the public origin. Requests that change data are checked against it. - **`APP_SECURE`** — the starter's switch for `Strict-Transport-Security`, for a site served over HTTPS. The gate fetches `APP_URL` and refuses when nothing sends it. - **`MAIL_DRIVER`** — this app sends real mail: verification links, password resets and the task notifications. With a real `MAIL_FROM_ADDRESS` and the driver still `log`, the gate refuses: every message would go to a log file. - **`HEALTH_KEY`** — `/health` answers load balancers in production only when they send it. - **`APP_KEY`** — already in `.env` from the scaffolder. Production needs a separate one, kept secret. Don't run `bun zt key:generate` for it here: that writes into this project's `.env` and replaces your development key. Print a new one instead and put it in your platform's secrets (or, for the rehearsal, add `APP_KEY=` with it to `.env.production`): ```bash # anywhere bun -e "console.log(Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64'))" ``` [Environment](/docs/deployment#environment) lists the rest. Load the file into your shell and run the gate again. This uses a POSIX shell (bash or zsh; on Windows, Git Bash or WSL): ```bash # in your project root set -a; . ./.env.production; set +a bun zt deploy:production --check ``` ``` ✓ 23 checks passed, 1 warning(s) ``` The warning left is that the eight migrations have not run on the new database. The release runs them. ## Release ```bash # in your project root, with .env.production loaded bun zt deploy:production ``` It runs the gate, then `assets:build` and `inertia:build`, then the eight migrations against the new database, then checks again: ``` migrate Migrated 8 migration(s). 0001_create_users_table ran 0002_create_password_reset_tokens_table ran 0003_create_user_sessions_table ran 0004_create_passkeys_table ran 0005_create_social_accounts_table ran 0006_create_projects_table ran 0007_create_tasks_table ran 0008_add_tenant_id_columns ran Verify ✓ 23 checks passed production release complete. Restart the service to pick it up. ``` It does not start or restart anything. Your process supervisor does that, after the command exits 0. ## Run it Two long-running processes: the server, and a worker for the queued notifications. ```bash # in your project root, with .env.production loaded PORT=3001 bun zt serve ``` ```bash # in your project root, with .env.production loaded, in a second terminal bun zt worker ``` ``` Starting Zerotal worker... INFO [QUEUE] Polling [default, notifications] every 500ms ``` Without the worker, every task notification waits in the queue and nobody is told. [Start the server](/docs/deployment#start-the-server) covers supervisors, and the starter's `Dockerfile` is a starting point for a container. ## Check it ```bash # in your project root curl "http://localhost:3001/health?key=rehearsal-health-key" ``` ``` {"status":"ok"} ``` Without `?key=` it answers 401. `curl -sI http://localhost:3001/` shows the `Strict-Transport-Security` header. And `doctor` reads the running site from outside, which is the one check the gate cannot make before the release is live: ```bash # in your project root, with .env.production loaded bun zt doctor --url=http://localhost:3001 ``` ``` All 23 checks passed. ``` Against a real deployment, point `--url` at the public address: it then also sees what the proxy in front of the app adds or drops. ## The production checklist The [production checklist](/docs/deployment#production-checklist) is what `deploy:production` checks or does, and what it cannot. For this app: | Checklist item | Done by | | -------------------- | --------------------------------------------------------- | | `APP_ENV=production` | `.env.production`; the gate's first check | | A strong `APP_KEY` | A new random key, kept as a secret, not the dev one | | `APP_URL` | `.env.production`; the gate refused without it | | `DATABASE_URL` | `.env.production` | | Secure headers | `APP_SECURE=true` | | CORS origins | The starter's default: same origin only | | Migrations | `deploy:production` | | Frontend build | `deploy:production` | | Server and worker | `bun zt serve` and `bun zt worker`, under your supervisor | | Probe the live site | `bun zt doctor --url=…` | Back up the database before the first real release: see [Back up the database](/docs/deployment#back-up-the-database). ## Where to go next You have built a feature the way the rest of an app is built: a model and migration, routes and pages, validation, a policy, background work, tests that include the refusals, and teams. [What Ships](/docs/what-ships) lists what the framework already does — roles, audit logs, uploads, scheduled jobs, an admin panel — so check it before you build the next thing. --- Source: https://zerotal.dev/docs/application # The Application The `Application` is the heart of every Zerotal project: the IoC container's owner, the service-provider registry, the route loader, and the lifecycle engine that takes you from `bun zt serve` to a running HTTP server. You construct it once in `bootstrap/app.ts`, and the framework drives it the rest of the way. Think of it as the **assembly line and the conductor** rolled into one. When the app starts it walks a fixed sequence of phases — register everything, boot it, start the server — and at each phase it gives your providers a chance to hook in. The container holds the _services_; the Application decides _when_ they get wired up, _when_ routes load, and _when_ the server opens for traffic. In practice you touch a small slice of this. `bootstrap/app.ts` is a short, mostly-declarative file: create the app, point it at your routes, and (optionally) register a binding or two. Almost everything else — discovering providers, loading config, scanning conventions — happens automatically. The rest of this page explains what's happening behind that file, and the handful of methods you'll actually call. ## Mental model The app is created once and exposed as a singleton. Every configuration method (`routing`, `bind`, `defer`, `use`, `withExceptionHandler`, …) returns the same instance, so in real code they chain straight onto `Application.create(...)`: ```text ┌──────────────────────────────────────────┐ bootstrap/app.ts│ Application.create() │ │ .bind(...).routing(...).use(...) │ ← config methods chain └──────────────────┬───────────────────────┘ │ start() / boot() / bootAsWorker() ▼ ┌─────────┐ ┌─────────┐ ┌────────┐ ┌──────────┐ ┌─────────┐ │ Register│ → │ Booting │ → │ Booted │ → │ Starting │ → │ Started │ └─────────┘ └─────────┘ └────────┘ └──────────┘ └─────────┘ phase 1 phase 2 phase 3 phase 4 phase 5 onRegister onBooting onBooted onStarting onStarted + routes load (Bun.serve live) ``` > **Note** — wherever this page shows a bare `app`, it means _this_ instance: the > one `Application.create()` returns and `bootstrap/app.ts` exports. ## Import ```typescript // bootstrap/app.ts import { Application } from "zerotal"; ``` ## Creating the application `Application.create()` builds the singleton instance and returns it. Call it once in `bootstrap/app.ts` — no providers or config arguments needed; both are discovered automatically at boot: ```typescript // bootstrap/app.ts import { Application, basePath } from "zerotal"; export default Application.create().routing({ web: basePath("routes/web.ts") }); ``` There is one application per process; once `create()` has run, the `currentApp()` helper reaches it anywhere. > **Note** — `Application.create({ providers })` and > `Application.create({ providers, config, env })` accept explicit providers and > config for lightweight in-process test setups that bypass auto-discovery. See > [Testing](/docs/testing). ### The current application ```typescript import { currentApp } from "zerotal"; // anywhere after create() has run const app = currentApp(); // throws if create() hasn't run yet ``` Calling `create()` a second time is an error — retrieve the running app with `currentApp()`. Tests reset the process between cases with `Application._resetInstance()`. The configuration methods (`defer`, `use`, `routing`, `withExceptionHandler`, …) each return `app`, so in real code they're usually chained directly onto `Application.create(...)` rather than called on a stored variable. ## Configuration An application needs its config loaded before providers boot. There are three ways to supply it, and they compose cleanly. The framework default is **zero-config auto-discovery**: if you never call `useConfig()` and never pass `config` to `create()`, `boot()` scans `/config/*.ts` and loads each file's default export under its filename (`config/app.ts` → the `app` namespace). Files that throw on import (e.g. a missing env var) are skipped rather than crashing the boot. To load config explicitly, use `configLoader()` and pass it to `useConfig()`: ```typescript // bootstrap/app.ts import { Application } from "zerotal"; import { configLoader } from "zerotal/config"; Application.create().useConfig(configLoader("./config")); ``` `useConfig()` accepts a `ConfigLoader`, the generated configs barrel, or a raw `{ namespace: { ... } }` map. If config was already provided via `Application.create({ config })`, this call is **ignored** (create wins). The managed `zt.ts` always calls `useConfig()` for you — in normal app usage you never need to call it directly. See [Configuration](/docs/config-system) for the config files themselves. ### Which config path should I use? - **Do nothing** — let zero-config auto-discovery scan `config/*.ts`. This is the right choice for almost every app. - **`useConfig(configLoader(...))`** — when you need an explicit config directory or want to pre-load before providers boot. - **`create({ config })`** — for in-process tests that bypass file discovery. ## Registering providers Providers are discovered automatically — you do not need to list them. At boot, before the register phase, the application scans `app/providers/*` and instantiates every `ServiceProvider` subclass it finds, running each through the full lifecycle. Create a provider and place it under `app/providers/`: ```typescript // app/providers/AppServiceProvider.ts import { ServiceProvider } from "zerotal"; export class AppServiceProvider extends ServiceProvider { onRegister(): void { // bind services into the container } } ``` That file is picked up automatically — no manual registration required. See [Service Providers](/docs/providers) for the full provider API and lifecycle hooks. ### Package providers Framework packages (`@zerotal/orm`, `@zerotal/auth`, `@zerotal/notifications`, …) ship their own providers. List them in the **providers array** in `bootstrap/providers.ts` and pass that array to `Application.create({ providers })`: ```typescript fragment // bootstrap/providers.ts import { DatabaseProvider } from "@zerotal/orm"; import { AuthProvider } from "@zerotal/auth"; import { AppServiceProvider } from "../app/providers/AppServiceProvider.ts"; const providers = [DatabaseProvider, AuthProvider, AppServiceProvider]; export default providers; ``` ```typescript fragment // bootstrap/app.ts import { Application, basePath } from "zerotal"; import providers from "./providers.ts"; export default Application.create({ providers }).routing({ web: basePath("routes/web.ts") }); ``` > **Note** — When one package depends on another, prefer declaring it on the class > with `static dependsOn` rather than relying on list order — the dependency is then > pulled in and booted first automatically, so the app only lists the features it > uses. Registration is idempotent, so listing a provider that's also pulled in via > `dependsOn` is harmless. See [Declaring dependencies](/docs/providers#declaring-dependencies). ### Deferred providers A deferred provider boots lazily — only the first time one of its container bindings is resolved. This keeps cold-start fast when a service isn't used on every request. ```typescript fragment // bootstrap/app.ts — defer() is called on the app instance (and returns it) const app = Application.create({ providers }); // Single token app.defer("cache", CacheProvider); // Object map app.defer({ cache: CacheProvider, mail: MailProvider }); // Array — each provider must declare `static provides = ['token'] as const` app.defer([CacheProvider, MailProvider, QueueProvider]); ``` Providers whose `static environments` list doesn't include the current runtime mode are filtered out before they ever instantiate, so a `web`-only provider never boots inside a `worker`. See [Conventions](/docs/conventions) for how the scanner works. ## Registering services without a provider A provider is the right tool when bootstrapping is involved — lifecycle hooks, config-driven wiring, middleware. But when you just need to register a binding or two, that's a lot of ceremony. For those cases, `bind()` lets you register straight from `bootstrap/app.ts`: ```typescript fragment // bootstrap/app.ts import { Application, basePath } from "zerotal"; import { Clock, SystemClock } from "../app/services/clock.ts"; export default Application.create({ providers }) .bind((container) => { container.singleton(Clock, () => new SystemClock()); }) .fileBasedRouting({ web: basePath("app/flow/pages") }); ``` The callback receives the live container and runs once at boot — **after** the core singletons are bound and **before** any provider's `onRegister()`, so a provider can still override what you register here. It's the natural home for **interface → implementation** bindings (binding a `Clock` contract to a `SystemClock`), which a self-registering service class can't express on its own. This is one of three lighter-than-a-provider paths, alongside the `app/services` convention and the `App` facade. For the full picture — including when to pick each — see [App-level dependency injection](/docs/container#app-level-dependency-injection). > **Tip** — to _resolve_ a service anywhere in your app (a page, a controller, a > job), use the [`App` facade](/docs/container#the-app-facade): > `await App.make(MyService)`, or the `make()` / `app()` global helpers. You > rarely need `currentApp()` directly. ## Routing Declare where your routes live; the application loads them at boot, after every provider has registered its middleware groups (so a route file can always reference `web`, `api`, or any provider-supplied group). ```typescript fragment // bootstrap/app.ts Application.create().routing({ web: "./routes/web.ts", api: "./routes/api.ts", }); ``` `web` and `api` have built-in defaults — `web` mounts at `/` with the `web` middleware group, `api` mounts at `/api` with the `api` group. Any other group name must declare both `prefix` and `middleware` explicitly (or an error is thrown at boot): ```typescript fragment // bootstrap/app.ts .routing({ web: "./routes/web.ts", admin: { file: "./routes/admin.ts", prefix: "/admin", middleware: ["web", "auth"] }, }) ``` For directory-based routing, use `fileBasedRouting()` — same key semantics, but each value is a directory that's scanned for exported HTTP-method handlers: ```typescript fragment // bootstrap/app.ts Application.create().fileBasedRouting({ web: "./app/routes" }); ``` Use [`basePath()`](/docs/helpers#basepath) to anchor these paths to the project root regardless of the calling file. ## Middleware Register global middleware that runs on every request, in array order: ```typescript fragment // bootstrap/app.ts import { CorsMiddleware, SecureHeadersMiddleware } from "zerotal"; Application.create().use([SecureHeadersMiddleware, CorsMiddleware]); ``` The resolved pipeline runs provider-registered middleware first, then everything you added via `.use()`. You can read the final ordering back off the app instance (handy in a test or a diagnostic): ```typescript fragment // in a test or diagnostic currentApp().globalMiddleware; // PipeClass[] in execution order ``` Middleware discovered from `app/middleware/*` is registered as a named group keyed by class name (so it isn't global by default); add `static global = true` to a class to push it onto the global pipeline automatically. See [Middleware](/docs/middleware). > **Note** — `useOnce()` registers a middleware idempotently and is what providers > use internally to guarantee their required middleware is present exactly once. > You generally won't call it directly. ## Other wiring These are the remaining configuration methods, all called on the app instance in `bootstrap/app.ts` (and all returning it, so they chain): ```typescript fragment // bootstrap/app.ts import { Handler } from "../app/exceptions/Handler.ts"; const app = Application.create({ providers }); // Custom exception handler for all unhandled route errors app.withExceptionHandler(Handler); // Resolve the authenticated user from a session id (usually automatic — see Auth) app.withUserResolver((id) => User.find(id)); // Register WebSocket handlers (used by the broadcasting provider) app.withWebSocket(handlers, (req) => ({ userId: tokenFrom(req) })); // Contribute a convention descriptor (used by packages, not apps) app.registerConcern(myConcern); ``` Each of these returns `app`, so in practice they chain straight onto `Application.create(...)` rather than being called on a stored variable. ## How the lifecycle works You normally call exactly one of `start()`, `bootAsWorker()`, or `boot()`; the managed `zt.ts` picks the right one based on the command. Each drives the provider hooks through a fixed set of phases. `boot()` runs phases 1–3 and is idempotent (a second call is a no-op): 1. **Register** — config and core singletons (`config`, `events`) are bound; `app/providers/*` is discovered; each provider's synchronous `onRegister()` runs. 2. **Booting** — each provider's `onBooting()` runs sequentially, in registration order, so later providers can depend on earlier ones. 3. **Booted** — every provider's `onBooted()` runs concurrently. Then middleware is discovered, route files load, and the convention phase registers models, observers, policies, listeners, jobs, and validators. `start(port = 3000)` boots (if needed) then runs phases 4–5 and binds the server: 4. **Starting** — `onStarting()` on every provider, before the socket opens. 5. **Started** — `Bun.serve()` is live; `onStarted()` fires. A health endpoint, a PID file, and `SIGTERM`/`SIGINT`/`SIGUSR2` handlers are installed. ```typescript fragment // zt.ts (managed) ultimately does: const app = (await import("./bootstrap/app.ts")).default; await app.start(Number(env("PORT", 3000))); ``` `bootAsWorker()` forces `worker` mode, boots, and runs the `starting`/`started` phases without binding an HTTP server — used by the queue worker. On shutdown it drains providers in reverse (LIFO) order. `stop()` runs the teardown phases in LIFO order: 6. **Stopping** — `onStopping()` on each provider, newest first. 7. **Stopped** — `onStopped()` on each, the PID file is removed, and the process exits. ### Which entry point should I use? - **`start(port?)`** — the normal web server. Boots, binds `Bun.serve()`, installs signal handlers. - **`bootAsWorker()`** — the queue worker. Boots in `worker` mode with no HTTP socket. - **`boot()`** — phases 1–3 only, no server. Useful in tests and one-off scripts that need the container wired but no listening port. ### Per-request provider hooks Beyond the boot phases, providers can observe every request without registering middleware. The application calls `onRequestReceived` before the pipeline, `onRequestProcessed` after `ctx.response` is set, and `onResponseSent` after the response has been flushed to the client. These power telemetry, request logging, and similar cross-cutting concerns. ### Zero-downtime route reload In development, sending `SIGUSR2` to the server re-runs your route files with cache-busting imports and hot-swaps the compiled route table with no dropped connections. The dev server wires this up for you on file change. ## References | Member | Purpose | | ---------------------------------------- | --------------------------------------------------------------------------- | | `Application.create()` | Create the process's application. Providers and config are auto-discovered. | | `currentApp()` | Return the current application (throws if not created). | | `.register(providers)` | Add providers. | | `.bind(callback)` | Register container bindings at boot, without a provider. | | `.defer(token \| map \| array)` | Register providers that boot lazily on first resolution. | | `.useConfig(input)` | Pre-load config (ignored if `create({ config })` was used). | | `.routing(config)` | Declare explicit route files per named group. | | `.fileBasedRouting(config)` | Declare file-route directories per named group. | | `.use(middleware)` | Add global middleware (array order). | | `.withExceptionHandler(Handler)` | Set the handler for unhandled errors. | | `.withUserResolver(fn)` | Set the session → user loader. | | `.withWebSocket(handlers, upgradeData?)` | Enable the WebSocket protocol. | | `.registerConcern(descriptor)` | Contribute a convention descriptor (packages). | | `.globalMiddleware` | Read the resolved global pipeline. | | `.environment` | The runtime environment (`web`, `worker`, `console`, …). | | `.booted` | Whether `boot()` has completed. | | `.boot()` | Phases 1–3 (idempotent). | | `.start(port?)` | Boot then bind the HTTP server (phases 4–5). | | `.bootAsWorker()` | Boot in `worker` mode, no HTTP server. | | `.stop()` | Teardown (phases 6–7) and exit. | | `.container` | The IoC [container](/docs/container). | | `.routerState` | The router state owned by this app. | ## Next steps - [Service Container](/docs/container) — the IoC container the application owns. - [Service Providers](/docs/providers) — the unit of bootstrapping. - [Conventions](/docs/conventions) — auto-discovery of providers, models, and more. - [Request Lifecycle](/docs/lifecycle) — how a request flows through the pipeline. - [Configuration](/docs/config-system) — config files and the `config()` helper. --- Source: https://zerotal.dev/docs/lifecycle # Request Lifecycle A Zerotal app has **two lifecycles** — one that runs once at startup and one that runs for every request. Keeping them straight is the key to putting logic in the right place. - **The boot lifecycle** runs **once**, when the server starts. It wires everything together — binds services, loads routes, scans your `app/*` directories — and then opens the socket. One-time setup belongs here, in a provider hook. - **The request lifecycle** runs **for every incoming request**. It opens a per-request scope, walks the middleware pipeline to your controller, builds a response, and tears the scope back down. Per-request work belongs here, in middleware, a controller, or an after-response hook. If you only remember one thing: _boot is for the app, request is for the visitor._ ## Mental model Two clocks tick at different rates. The boot clock ticks once — everything it sets up (container bindings, routes, the compiled route table) is shared by every request that follows. The request clock ticks on each visit and gets its own isolated scope, so concurrent requests never share state. ``` boot clock ──tick── (server starts: bind, load routes, open socket) │ request clock ───────────┼── tick (GET /a) → scope A → response → flush A ├── tick (GET /b) → scope B → response → flush B └── tick (POST /c) → scope C → response → flush C ``` ## Boot lifecycle Booting starts from the two files you own — `bootstrap/app.ts` (where you configure the app, declaratively) and the managed `zt.ts` entry point (which imports it and calls `start()`). From there `Application.boot()` runs a fixed sequence, **once**, and is idempotent (a second call does nothing): ```text # boot sequence (overview) bootstrap/app.ts ← you configure the app (declarative) Application.create({ providers }) .bind((container) => …) ← optional: register container bindings .routing({ … }) ← declare explicit route files .fileBasedRouting({ … }) ← declare route directories .use([ …middleware ]) ← register global middleware └─ exports `app` │ ▼ zt.ts (managed) ← imports bootstrap/app.ts, then: app.start(port) │ ▼ app.boot() ── runs once, idempotent ─────────────────────────────────── 1. bind core singletons `config`, `events` 2. load config scan `config/*.ts` (unless preloaded) 3. discover providers scan `app/providers/*` 4. run app.bind() callbacks your bootstrap bindings 5. onRegister() each, sync providers bind their services 6. onBooting() each, in order providers prepare; may use earlier ones 7. onBooted() all, in parallel every binding is now resolvable 8. discover middleware scan `app/middleware/*` 9. load routes routing() + fileBasedRouting() files run 10. convention phase scan app/{models, observers, policies, listeners, events, jobs, services, validators}; serve public/ │ ▼ app.start() ── continues ──────────────────────────────────────────────── 11. onStarting() each last chance before the socket opens 12. Bun.serve() server binds and starts listening 13. onStarted() each health endpoint, PID file, signal handlers ``` The three provider phases (steps 5–7) are the part you'll touch most. They're **ordered for a reason**: `onRegister()` only _binds_ (nothing is resolved yet), `onBooting()` runs **sequentially** so a later provider can depend on an earlier one, and `onBooted()` runs in **parallel** once every binding exists — so it's the safe place to resolve services that depend on other providers. See [Provider lifecycle hooks](#provider-lifecycle-hooks) below. > **Tip** — _Bind in `onRegister()`, resolve in `onBooted()`_ is the rule that > avoids 90% of ordering bugs. The convention phase (step 10) scans the `app/*` directories and registers what it finds — models, observers, policies, listeners, jobs, services, validators. Providers declare which directories get scanned via `this.app.registerConcern(...)`. See [Conventions](/docs/conventions). ## Request lifecycle Now the per-request path. Every request gets its **own isolated scope** — created when it arrives, flushed when it leaves — so concurrent requests never share state. The route table was already compiled at boot, so matching is a fast lookup, not a re-scan: ```text # per-request flow Bun.serve() receives Request │ ▼ compiled route table lookup → match path + method → RouteDefinition │ ├── no match → 404 NotFoundError → ExceptionHandler.render() │ ▼ createRouteHandler(definition, container) │ ▼ ScopedResolver created ← request-scoped DI scope HttpContext created ← ctx.requestId, ctx.startedAt, ctx.url, … RequestContext.run(ctx, fn) ← AsyncLocalStorage stores ctx for this async tree │ ▼ Model bindings resolved ← the model's resolver / .bind() runs ctx._models populated │ ▼ Pipeline runs (middleware chain): [global middleware] → [group middleware] → [route middleware] → controller action │ ├── any middleware can short-circuit by returning a Response (or setting ctx.response) │ ▼ Controller action executes → sets ctx.response (via ctx.json(), ctx.view(), ctx.redirect(), etc.) │ ▼ Pipeline unwinds (finally blocks in middleware run here — e.g. SessionMiddleware saves) │ ▼ ctx.response returned to Bun.serve() │ ▼ afterResponse callbacks fire ← ctx.afterResponse(() => sendEmail()) │ ▼ ScopedResolver.flush() ← request-scoped bindings disposed ``` ## Middleware execution order Middleware nests: the outermost layer runs first on the way in and last on the way out. The list below reads top-to-bottom as the order requests enter, then unwinds in reverse as responses leave: ```text # nesting order (outer → inner) Global (app.use) └── Provider auto-registered (SessionMiddleware, AuthMiddleware, …) └── Switch middleware (withCors, withThrottle, withSecureHeaders) └── Group middleware (Router.group({ middleware: [...] })) └── Route middleware (Router.get('/...', C, 'a', [M])) └── Controller action ┌── (unwind) ┌── (unwind) ┌── (unwind — session saved here) ┌── (unwind) ``` Middleware wraps the next step — `await next()` is where the inner layers run. Code before `next` runs on the way in; code after runs on the way out. `next()` resolves to the downstream `Response`. ```typescript // app/middleware/TimingMiddleware.ts import type { HttpContext } from "zerotal"; import type { Pipe, NextFn } from "zerotal"; export class TimingMiddleware implements Pipe { async handle(ctx: HttpContext, next: NextFn): Promise { const start = performance.now(); const response = await next(); // ← inner layers run here console.log(`${ctx.path()} took ${Math.round(performance.now() - start)}ms`); return response; } } ``` ## Exception handling If any middleware or controller throws, the pipeline catches the error and calls the exception handler — first to report it, then to turn it into a `Response`: ```text # on an unhandled throw ExceptionHandler.report(err, ctx) ← log / Sentry / whatever ExceptionHandler.render(err, ctx) → Response ``` The response is sent to the client, and `afterResponse` callbacks still fire. In production, raw 500 errors show a minimal "Internal Server Error" page. In dev, unhandled exceptions show a full stack-trace page. See [Error Handling](/docs/errors) for custom handlers. ## AsyncLocalStorage context `RequestContext` stores the request's `HttpContext` in an `AsyncLocalStorage` so that any code running inside the async tree of a request — facades, services, ORM models — can reach the current context without prop-drilling: ```typescript // in a service, anywhere in the async tree import { RequestContext } from "zerotal"; const ctx = RequestContext.tryGet(); // HttpContext | undefined const user = ctx?.user; ``` > **Note** — Use `RequestContext.tryGet()` (returns `undefined` outside a request) > for code that runs in both request and non-request contexts — CLI commands, > queue workers, scheduled jobs. Use `RequestContext.get()` when you want it to > throw if there is no active request. Facades like `Auth` and `Config` use this internally. You rarely need to access `RequestContext` directly. ## Provider lifecycle hooks A provider can hook into any step of the boot and shutdown sequence by overriding these methods. The three most-used ones map to boot steps 5–7 above; the rest bracket the server starting and stopping. | Hook | When it runs | Typical use | | -------------- | --------------------------------------- | --------------------------------------------- | | `onRegister()` | Boot step 5 — sync, nothing resolved | `container.singleton()`, `Router.macro()` | | `onBooting()` | Boot step 6 — sequential, in order | Prepare a service that a later provider needs | | `onBooted()` | Boot step 7 — parallel, all bound | Resolve cross-provider deps, warm singletons | | `onStarting()` | Just before the socket opens | Final pre-flight checks | | `onStarted()` | After the server is listening | Start background timers / workers | | `onStopping()` | Graceful shutdown, reverse order | Release resources, flush buffers | | `onStopped()` | After shutdown completes, reverse order | Final cleanup | Providers can also observe **every request** without registering middleware — `onRequestReceived()` (before the pipeline runs), `onRequestProcessed()` (after the pipeline sets `ctx.response`), and `onResponseSent()` (after the response is sent). The full phase reference lives in [The Application](/docs/application) and [Service Providers](/docs/providers). ```typescript fragment // app/providers/PaymentProvider.ts import { ServiceProvider } from "zerotal"; export class PaymentProvider extends ServiceProvider { onRegister(): void { this.app.container.singleton( PaymentGateway, () => new StripeGateway({ key: Bun.env.STRIPE_KEY! }), ); } async onBooted(): Promise { const gw = await this.app.container.make(PaymentGateway); gw.setWebhookSecret(Bun.env.STRIPE_WEBHOOK_SECRET!); } } ``` > **Warning** — Do not resolve services in `onRegister()`. Nothing is resolvable > yet at that phase — only _bind_ there, and resolve in `onBooted()` once every > provider has registered its bindings. ## Which hook should I use? - **Registering a binding (singleton, macro, alias)** → `onRegister()`. It runs first and only binds; nothing is resolved. - **Preparing a service a _later_ provider depends on** → `onBooting()`. It runs sequentially in registration order, so earlier providers are already booting. - **Resolving a service that spans providers, or warming a singleton** → `onBooted()`. Every binding exists by now and these run in parallel. - **Opening a socket / starting timers after the server is up** → `onStarted()`. - **Releasing resources on shutdown** → `onStopping()` / `onStopped()` (reverse order). - **Observing each request without owning a middleware slot** → `onRequestReceived()` / `onRequestProcessed()` / `onResponseSent()`. ## Reference Boot and shutdown phases in order, and the per-request hook surface. | Phase / hook | Runs | Concurrency | | ---------------------- | ---------------------------- | ------------------- | | `onRegister()` | Boot — bind services | Sync, sequential | | `onBooting()` | Boot — prepare services | Async, sequential | | `onBooted()` | Boot — every binding ready | Async, parallel | | `onStarting()` | Before `Bun.serve()` binds | Async, parallel | | `onStarted()` | After server is listening | Async, parallel | | `onStopping()` | Graceful shutdown | Async, reverse | | `onStopped()` | After shutdown completes | Async/sync, reverse | | `onRequestReceived()` | Per request, before pipeline | Async, parallel | | `onRequestProcessed()` | Per request, after pipeline | Async, parallel | | `onResponseSent()` | Per request, after response | Async, parallel | ### What booting cost `app.bootDurationMs` is the total. `app.providerReport` is the breakdown — one `ProviderReport` per provider, in boot order: ```typescript fragment for (const { name, durationMs, bindings } of app.providerReport) { console.log(`${name} ${durationMs}ms, bound ${bindings.length}`); } ``` | Field | Is | | ------------ | ------------------------------------------------------- | | `name` | Provider class name. The array order is the boot order. | | `durationMs` | Wall-clock across all three boot hooks. | | `bindings` | Container tokens this provider bound, as names. | Boot order is worth reading on its own: it decides who wins a contested binding. And because `onBooted()` runs in parallel, these durations **overlap** — they do not sum to `bootDurationMs`, and the report says so rather than serialising the boot to produce a tidier number. [DevTools](/docs/devtools) draws this as its Providers and Container tabs. ## Next steps - [Providers](/docs/providers) — register and boot services. - [Middleware](/docs/middleware) — the request pipeline in depth. - [Container](/docs/container) — dependency injection and scopes. - [Conventions](/docs/conventions) — auto-registration of app directories. - [HttpContext](/docs/context) — the per-request object and its helpers. --- Source: https://zerotal.dev/docs/container # Service Container The service container is the part of Zerotal that **builds your objects for you**: you describe how to construct something once, then ask for it by name and it wires up the dependencies. Most classes need other things to do their job: a repository needs a database connection, a mailer needs an API key, a service needs a logger. Wiring all of that by hand — `new PostRepository(new CacheManager(config), new Logger())` — gets tedious and couples every caller to the exact construction details. The container takes that job over: you tell it _how_ to build something once, and from then on you just ask for it by name. It figures out the dependencies, builds them in the right order, and hands you a finished object. This is **dependency injection**: your classes declare _what_ they need, and the container supplies it — instead of each class reaching out and constructing its own dependencies. The payoff is testability (swap a real mailer for a fake one in one line) and decoupling (a class depends on a `Mailer` contract, not on `SendGridMailer`). > **Note** — Do I need to learn all of this? Not up front. In everyday app code > you'll mostly _resolve_ services with [`App.make()`](#app-level-dependency-injection) > or let [`@inject()`](#auto-wiring-with-inject) wire them for you, and _register_ > the occasional one with the [`app/services` convention](#app-level-dependency-injection). > The lifetimes, contextual bindings, aliases, and hooks below are there when you > need finer control — reach for them as the need arises, not before. ## Accessing the container Inside a `ServiceProvider`, the container lives at `this.app.container`: ```typescript fragment // in a ServiceProvider method this.app.container.singleton(CacheManager, () => new CacheManager()); const cache = await this.app.container.make(CacheManager); ``` Anywhere else, reach it through the application singleton: ```typescript fragment // in application code outside a provider import { Application } from "zerotal"; const container = currentApp().container; const cache = await container.make(CacheManager); ``` > **Tip** — In application code, prefer [`@inject()`](#auto-wiring-with-inject) so the > container wires dependencies for you, or the [`App` facade](#app-level-dependency-injection) > (`App.make(...)`) for terse access — reaching for `currentApp()` is a > last resort. > **Note** — Reading the examples: a code block that opens with > `this.app.container.…` is inside a `ServiceProvider`. A block that uses a bare > `container.…` assumes you already obtained it one of the two ways above. Blocks > that belong in a specific file (`bootstrap/app.ts`, `app/services/…`) say so in a > comment on the first line. ## Binding lifetimes A _lifetime_ answers one question: **when you ask for this thing twice, do you get the same instance or a new one?** That's the only real decision when registering a binding, and it comes down to whether the object holds state and who that state belongs to. **Which should I use?** - Reach for **singleton** by default for services — a database manager, a cache, an HTTP client. They're expensive to build, safe to share, and you want one of them. This is the most common choice. - Use **scoped** when the object carries data that belongs to _one request_ and must never bleed into another — the current user, a per-request "unit of work", a request-id. Each request gets its own; concurrent requests stay isolated. - Use **transient** for cheap, stateless, or deliberately short-lived objects where sharing would be surprising — a fresh report builder per call. - Use **value** when you already _have_ the finished object and just want the container to hand it back — a config blob, a pre-configured SDK client. When in doubt, start with singleton; move a binding to scoped only once you find it holding per-request state. | Lifetime | Method | Instances created | Use for | | --------- | ------------- | ------------------------------- | -------------------------------------- | | Singleton | `singleton()` | Once per application | Shared, stateful services (cache, db) | | Scoped | `scoped()` | Once per HTTP request | Per-request state (current user, cart) | | Transient | `bind()` | Every `make()` call | Stateless or short-lived objects | | Value | `value()` | Never — you supply the instance | Config objects, pre-built clients | ### Singleton Created once, then cached for the lifetime of the application. Every caller gets the same instance. The factory receives the container so it can resolve its own dependencies: ```typescript fragment // in a ServiceProvider's onRegister() this.app.container.singleton(CacheManager, async (c) => { const cfg = await c.make("config"); return new CacheManager(cfg.get("cache")); }); ``` Singleton resolution is **concurrency-safe**: if two requests resolve the same unresolved singleton at the same time, the factory runs exactly once and the second caller awaits the same in-flight promise. ### Scoped Created once per HTTP request and isolated between concurrent requests via `AsyncLocalStorage`. Resolving a scoped binding outside of a request context throws `ScopedOutsideRequestError`: ```typescript fragment // in a ServiceProvider's onRegister() this.app.container.scoped(UserSession, (c) => new UserSession()); ``` ### Transient A fresh instance on every `make()`: ```typescript fragment // in a ServiceProvider's onRegister() this.app.container.bind(ReportGenerator, () => new ReportGenerator()); ``` ### Value Bind a pre-built instance directly — no factory, no lazy construction: ```typescript fragment // in a ServiceProvider's onRegister() this.app.container.value("config", configObject); ``` ## Registering bindings Bindings are registered in a `ServiceProvider`'s `onRegister()`: ```typescript fragment // app/providers/AppServiceProvider.ts import { ServiceProvider } from "zerotal"; import { CacheManager } from "../services/CacheManager.ts"; import { PaymentGateway } from "../services/PaymentGateway.ts"; export class AppServiceProvider extends ServiceProvider { onRegister(): void { // Singleton — shared across all requests this.app.container.singleton(CacheManager, async (c) => { const cfg = await c.make("config"); return new CacheManager(cfg.get("cache")); }); // Scoped — isolated per request this.app.container.scoped(PaymentGateway, async (c) => { const cfg = await c.make("config"); return new PaymentGateway(cfg.get("stripe.secret")); }); } } ``` > **Warning** — `onRegister()` is synchronous and runs before any binding is resolved. > Register here; **resolve** in `onBooted()`, once every provider has registered. See > [Service Providers](/docs/providers). ## App-level dependency injection Everything above is the container's full API, mostly used by framework packages inside providers. For your own application services you rarely need that machinery — a full `ServiceProvider` is overkill for one class. These are the lighter, everyday paths, all backed by the same container. **Which one should I use?** Match the path to what you're doing: - **Just need to _use_ a service?** Resolve it — [`App.make(MyService)`](#the-app-facade) or `@inject(MyService)` on the class that depends on it. No registration needed for a plain class; the container auto-wires it. - **Want a service to be a shared singleton?** Drop it in `app/services/` and add [`static lifetime = "singleton"`](#the-appservices-convention). Zero wiring. - **Binding a contract to an implementation** (e.g. `Mailer` → `SendGridMailer`), or doing setup that doesn't belong next to a single class? Use the [bootstrap `bind()` callback](#bootstrap-bind-callback). - **Genuinely complex bootstrapping** — config-driven wiring, lifecycle hooks, middleware registration? _Then_ write a [`ServiceProvider`](/docs/providers). As a rule of thumb: start with the convention, graduate to `bind()` when a class can't register itself, and only reach for a provider when you need lifecycle hooks. ### The App facade `App` is the canonical surface for application code — resolve from anywhere (pages, controllers, jobs) without importing `Application`: ```typescript fragment // in a controller, page, or job import { App } from "zerotal"; import { UsersService } from "@app/services/users-service.ts"; const users = await App.make(UsersService); // auto-wired const events = await App.make("events"); // named binding ``` It also exposes registration (`bind`, `singleton`, `scoped`, `value`, `alias`, `forget`), introspection (`bound`, `container`, `instance()`), and environment helpers (`environment()`, `isProduction()`, `isLocal()`). The `make()` and `app()` global helpers are shorthands: ```typescript fragment // in application code import { make, app } from "zerotal"; const users = await make(UsersService); // = App.make(UsersService) const kernel = app(); // the Application instance const same = await app(UsersService); // = make(UsersService) ``` ### Bootstrap `bind()` callback Register bindings in `bootstrap/app.ts` without a provider. The callback runs at boot, before any provider's `onRegister()`, so providers can still override: ```typescript fragment // bootstrap/app.ts — the callback receives the live container Application.create({ providers }) .bind((container) => { container.singleton(Clock, () => new SystemClock()); container.for(ReportService).give(Clock, () => new FixedClock()); // contextual }) .fileBasedRouting({ web: basePath("app/flow/pages") }); ``` This is the place for **interface → implementation** bindings, since a class can't register itself against a different token: ```typescript fragment // bootstrap/app.ts Application.create({ providers }).bind((container) => container.singleton(Mailer, () => new SendGridMailer(env("SENDGRID_KEY"))), ); ``` ### The `app/services` convention Any class under `app/services/` is auto-discovered at boot. Declare its lifetime next to the class with a `static lifetime` flag and it's registered for you: ```typescript fragment // app/services/users-service.ts @inject(Auth) export class UsersService { static lifetime = "singleton" as const; // "singleton" | "scoped" | "transient" constructor(private auth: AuthManager) {} } ``` Now `App.make(UsersService)` returns the **same** singleton on every call. `transient` (or no flag) registers nothing — the container still auto-wires the class on demand, just with a fresh instance each time. ### Registration is boot-time only The container is process-global and shared across every concurrent request, so the `App` registration methods are **locked once `boot()` completes** — calling `App.singleton()` (etc.) from inside a request throws `ContainerLockedError`. Register during boot; for genuinely per-request state, register a `scoped` binding at boot and the container hands each request its own instance. > **Danger** — The container is shared across every concurrent request. Mutating > it at request time would leak state between requests — which is exactly why the > `App` facade locks registration after boot. Use a `scoped` binding for anything > that must be per-request. > **Note** — the lock guards the `App` facade, not the raw container. Framework > internals (deferred providers that register lazily) and tests use > `container.*` directly and are intentionally unaffected. ## Resolving bindings ### Async resolution — make `make()` is the primary way to resolve a binding. It's async because factories may be async and deferred providers may need to boot first: ```typescript fragment // in application code const cache = await container.make(CacheManager); const cfg = await container.make("config"); ``` ### Sync resolution — makeSync `makeSync()` resolves **without awaiting** but only works for two cases: - **value** bindings, and - **singleton** bindings that have already been resolved. Anything else throws `SyncResolutionError`. This is what [facades](#facades) use internally — which is why providers pre-resolve (warm) their singleton in `onBooted()` before any facade call happens: ```typescript fragment // in application code const cache = container.makeSync(CacheManager); // throws if not yet resolved ``` ### Safe lookup — tryMake `tryMake()` resolves a string-keyed binding synchronously, returning `undefined` instead of throwing when the token isn't registered. Useful for optional services that exist only in certain runtime modes: ```typescript fragment // in a ServiceProvider — CommandRunner is only bound in console mode const runner = container.tryMake("commandRunner"); if (runner) runner.register(MyCommand); ``` ## Auto-wiring with @inject _Auto-wiring_ means: list what a class needs, and the container builds those dependencies and passes them to the constructor for you — no factory function, no manual `new`. It's the most common way app code consumes the container, because the class stays honest about its dependencies (they're right there in the constructor) while you never have to assemble them by hand. Pass a class's dependency tokens straight to `@inject(...)`. The container resolves each token — recursively, and **in parallel** — before constructing the class: ```typescript fragment // app/repositories/PostRepository.ts import { inject } from "zerotal"; import { CacheManager } from "../services/CacheManager.ts"; import { Logger } from "../services/Logger.ts"; @inject(CacheManager, Logger) export class PostRepository { constructor( private cache: CacheManager, private logger: Logger, ) {} } ``` No registration needed — the container auto-wires on first `make()`: ```typescript fragment // in application code const repo = await container.make(PostRepository); ``` The token order must match the constructor parameter order. Any listed token may itself be auto-wired or bound by a provider. Tokens may be classes, abstract classes, or string keys from `ContainerBindings`. ## Binding tokens A token is the key the container resolves against — a class constructor, an abstract class, or a string key declared in `ContainerBindings`: ```typescript fragment // in application code // Class token (most common) container.singleton(CacheManager, factory); const cache = await container.make(CacheManager); // String token (typed via ContainerBindings) container.value("config", cfg); const cfg = await container.make("config"); ``` Packages extend the `ContainerBindings` interface via declaration merging so string tokens stay fully type-safe: ```typescript fragment // in a package's types.ts declare module "zerotal" { interface ContainerBindings { db: SQL; search: SearchClient; } } ``` ## Resolution order When you call `make(token, consumer?)`, the container walks these steps: 1. **Alias** — follow the alias map to the canonical token. 2. **Deferred** — if a deferred provider is registered for this token, boot it now (once), then continue. 3. **Contextual** — if a `consumer` was supplied and has a contextual override for this token, use it. 4. **Registry** — otherwise use the registered binding. 5. **Auto-wire** — if nothing is registered but the token is a class with `@inject()`, construct it by resolving its dependencies. 6. Otherwise throw `BindingNotFoundError`. After construction, any [`resolving()`](#resolving-hooks) hooks for the token fire. ## Contextual bindings Hand a different implementation of the same dependency to different consumers: ```typescript fragment // in a ServiceProvider or bootstrap bind() callback // PostController gets the Redis cache; ReportController gets the file cache container.for(PostController).give(CacheDriver, () => new RedisCache()); container.for(ReportController).give(CacheDriver, () => new FileCache()); ``` `for(consumer).give(dependency, factory)` registers a transient contextual binding. The variants control lifetime: | Method | Lifetime of the contextual instance | | ----------------------------- | ------------------------------------- | | `give(dep, factory)` | Transient — new instance per resolve | | `giveSingleton(dep, factory)` | Singleton within the contextual scope | | `giveValue(dep, instance)` | A pre-built value | The `consumer` argument flows automatically when a class is auto-wired — the container passes the class being constructed as the consumer when resolving each of its `@inject` tokens. ## Aliases Bind one token as an alias for another. Resolving the alias returns the target's instance — handy for binding an interface/contract token to a concrete class: ```typescript fragment // in a ServiceProvider or bootstrap bind() callback container.alias(CacheContract, CacheManager); const cache = await container.make(CacheContract); // → the CacheManager singleton ``` Alias chains are followed to the canonical token, and the resolver guards against alias cycles. ## resolving hooks Run a callback every time a token resolves — for post-construction setup without subclassing or wrapping the factory: ```typescript fragment // in a ServiceProvider or bootstrap bind() callback container.resolving(Logger, (logger) => { logger.setChannel("app"); }); ``` Hooks fire for every binding kind (and for auto-wired classes) right after the instance is constructed. ## Deferred providers Register a provider so it boots only when one of its tokens is first resolved — keeping cold-start fast for services not used on every request: ```typescript fragment // in a ServiceProvider or bootstrap bind() callback container.defer(SearchClient, SearchServiceProvider); ``` The first `make(SearchClient)` runs the provider's full `onRegister → onBooting → onBooted` sequence, then resolves the binding. The provider is also tracked so its `onStopping`/`onStopped` hooks run at shutdown. See [The Application](/docs/application#deferred-providers) for the app-level `defer()` sugar. ## Scoped resolution lifecycle Each HTTP request runs inside `container.runScoped()`, which creates a fresh `ScopedResolver`, stores it in `AsyncLocalStorage`, and flushes it when the request finishes: - Every `make()` of a scoped binding during the request resolves against **that** request's resolver — even across `await` boundaries and concurrent requests. - There is no shared mutable state on the container, so scoped instances can never leak between requests. - After the response is sent the resolver is flushed; resolving a scoped binding afterward throws `ScopedAfterFlushError`. You rarely call `runScoped()` yourself — the HTTP pipeline does it per request. ## Errors | Error | Thrown when | | --------------------------- | -------------------------------------------------------------------- | | `BindingNotFoundError` | A token has no binding and can't be auto-wired. | | `ScopedOutsideRequestError` | A scoped binding is resolved outside any request scope. | | `SyncResolutionError` | `makeSync()` is used on a non-value / unresolved-singleton binding. | | `CircularDependencyError` | Auto-wiring detects a dependency cycle (clear chain in the message). | | `ScopedAfterFlushError` | A scoped binding is resolved after its request scope was flushed. | | `ContainerLockedError` | An `App` registration method is called after `boot()` completes. | All extend `ZerotalError`. ## References Members of the `Container` class: | Method | Signature | Description | | --------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------- | | `singleton(token, factory)` | `singleton(token: BindingToken, factory: Factory): this` | Bind a once-per-app instance. | | `scoped(token, factory)` | `scoped(token: BindingToken, factory: Factory): this` | Bind a once-per-request instance. | | `bind(token, factory)` | `bind(token: BindingToken, factory: Factory): this` | Bind a transient (new each time). | | `value(token, instance)` | `value(token: BindingToken, instance: T): this` | Bind a pre-built value. | | `make(token, consumer?)` | `make(token: BindingToken, consumer?: unknown): Promise` | Resolve asynchronously (preferred). | | `makeSync(token)` | `makeSync(token: BindingToken): T` | Resolve synchronously (value / resolved-singleton only). | | `build(ctor)` | `build(ctor: new (...args: unknown[]) => T): Promise` | Auto-wire a class, ignoring any registered binding. | | `tryMake(token)` | `tryMake(token: K): ContainerBindings[K] \| undefined` | Sync resolve or `undefined` if unregistered. | | `forget(token)` | `forget(token: BindingToken): boolean` | Remove a binding; `true` if one existed. | | `alias(from, to)` | `alias(from: unknown, to: unknown): this` | Resolve `from` as `to`. | | `for(consumer)` | `for(consumer: BindingToken): ContextualBindingBuilder` | Begin a contextual binding (`give` / `giveSingleton` / `giveValue`). | | `resolving(token, hook)` | `resolving(token: BindingToken, hook: (i: T) => void): this` | Run a hook after each resolution. | | `defer(token, Provider)` | `defer(token: unknown, provider: new (app) => unknown): this` | Boot a provider lazily on first resolve. | | `runScoped(cb)` | `runScoped(cb: (scoped: ScopedResolver) => Promise): Promise` | Run `cb` inside a fresh request scope. | ## Facades A facade is a thin static class that resolves a container binding for you, so consumers write `Cache.get(key)` instead of `await container.make("cache")`. Facades are sugar over the container — same instance, less ceremony. They are only usable **after the application has booted** (all providers have run `onRegister`/`onBooting`/`onBooted`), because they resolve their binding synchronously via `makeSync`. That's why providers pre-resolve their singleton in `onBooted()` — it warms the binding so the facade works everywhere afterwards. > **Warning** — Using a facade at module scope (top-level code that runs on > import) throws `FacadeAccessedBeforeBootError`, because the container isn't ready > yet. Move facade calls inside a function, controller method, or provider hook. ### Built-in facades Core ships a few, importable from `zerotal`: ```typescript fragment // in application code (after boot) import { Config, Events, Artisan } from "zerotal"; // Config — read loaded configuration Config.get("app.name"); // Events — the class-based event bus (events and listeners are plain classes) Events.on(UserRegistered, SendWelcomeEmail); await Events.emit(new UserRegistered(user.id, user.email)); // Artisan — invoke a CLI command programmatically await Artisan.call("migrate"); ``` Packages ship their own — for example `Cache` from `@zerotal/cache`, `Auth` from `@zerotal/auth`: ```typescript fragment // in application code (after boot) import { Cache } from "@zerotal/cache"; import { Auth } from "@zerotal/auth"; await Cache.set("key", value, 300); Auth.check(); // → boolean Auth.user(); // → AuthenticatedUser (throws if guest) Auth.userOrNull(); // → AuthenticatedUser | undefined ``` ### Defining a facade Build one with `createFacade(token)`, passing the same token the provider binds: ```typescript fragment // src/facades/Cache.ts import { createFacade } from "zerotal"; import type { CacheManager } from "../CacheManager.ts"; export const Cache = createFacade("cache"); ``` Every static call proxies to the resolved instance, so `Cache.get(...)` is exactly `(await container.make("cache")).get(...)` — just synchronous and terminless. See [Package Development](/docs/package-development#facades) for where facades fit in a package, and prefer [`@inject()`](#auto-wiring-with-inject) over facades inside your own application services where testability matters. ## Next steps - [Service Providers](/docs/providers) — where bindings are registered and booted. - [The Application](/docs/application) — the container's owner and lifecycle engine. - [Request Lifecycle](/docs/lifecycle) — where the per-request scope is opened and flushed. --- Source: https://zerotal.dev/docs/providers # Service Providers A service provider is a **feature's setup script**. When the app boots, each provider gets a turn to register its bindings into the container, wire up the things that feature needs, and (optionally) hook into later stages of startup and shutdown. Every framework feature — ORM, sessions, mail, queues — ships as a provider, and your own app can add as many as it needs. The mental model: the [container](/docs/container) holds the _services_, the [Application](/docs/application) runs the _boot sequence_, and a provider is how a feature plugs into that sequence. The two methods you'll use most are `onRegister()` (bind things) and `onBooted()` (use things) — the rest of this page is mostly about those two and when each runs. > **Note** — Do you even need a provider? Often not. Registering a single binding > or two doesn't justify a whole class — use the bootstrap [`app.bind()`](/docs/application#registering-services-without-a-provider) > callback or the [`app/services` convention](/docs/container#the-appservices-convention) > instead. Reach for a provider when there's real _bootstrapping_ involved: > lifecycle hooks, config-driven wiring, middleware registration, or a feature > that spans several bindings. ## Mental model A provider extends `ServiceProvider` from `zerotal` and overrides only the hooks it cares about. The framework drives every provider through the same boot sequence in list order: ``` register all providers onRegister() ← bind, no resolving yet │ ▼ boot (sequential) onBooting() ← prepare a service a later provider needs │ ▼ boot (parallel) onBooted() ← resolve and use, including from other providers │ ▼ server binding onStarting / onStarted │ ▼ graceful shutdown onStopping / onStopped ``` ```typescript // in a provider import { ServiceProvider } from "zerotal"; ``` ## Anatomy of a provider ```typescript fragment // app/providers/AppServiceProvider.ts import { ServiceProvider } from "zerotal"; import { PaymentGateway } from "../services/PaymentGateway.ts"; import { StripeGateway } from "../services/StripeGateway.ts"; export class AppServiceProvider extends ServiceProvider { /** * Register bindings into the container. * Called synchronously before boot. No resolved bindings are available yet. */ onRegister(): void { this.app.container.singleton( PaymentGateway, () => new StripeGateway({ key: Bun.env.STRIPE_KEY! }), ); } /** * Called after all providers have registered. * Safe to resolve bindings from other providers here. */ async onBooted(): Promise { const gw = await this.app.container.make(PaymentGateway); await gw.ping(); // verify connectivity at startup } } ``` ## How it works A provider boots in three ordered steps. The golden rule lives here: **bind in `onRegister()`, resolve in `onBooted()`.** Trying to resolve a binding too early is the most common provider mistake. | Hook | Runs | You should… | | -------------- | --------------------------------- | -------------------------------------------------- | | `onRegister()` | sync, before anything is resolved | _bind_ services — nothing is resolvable yet | | `onBooting()` | async, sequentially in list order | prepare a service a _later_ provider needs | | `onBooted()` | async, in parallel once all bound | _resolve_ services, including from other providers | Why the order matters: during `onRegister()` no binding has been resolved yet, so you can only register. By `onBooted()` every provider has registered, so resolving across providers is safe. `onBooting()` sits between them for the rarer case where one provider must be fully prepared before another even registers. There are also `onStarting`/`onStarted` (around the server binding) and `onStopping`/`onStopped` (graceful shutdown), plus per-request hooks (`onRequestReceived`, `onRequestProcessed`, `onResponseSent`) — see [the full phase list](/docs/lifecycle#provider-lifecycle-hooks). ## Registering providers List providers in `bootstrap/providers.ts`. Order matters — a provider can only resolve bindings registered by providers that appear earlier in the list: ```typescript fragment // bootstrap/providers.ts import { DatabaseProvider } from "@zerotal/orm"; import { CacheProvider } from "@zerotal/cache"; import { AppServiceProvider } from "../app/providers/AppServiceProvider.ts"; const providers = [ DatabaseProvider, // registers DB bindings CacheProvider, // may depend on DB AppServiceProvider, // can use both DB and Cache ]; export default providers; ``` > **Note** — `app/providers/*` are auto-discovered. Your own providers (e.g. `AppServiceProvider`) don't > need to be listed — any `ServiceProvider` under `app/providers/` is registered automatically and > runs its full lifecycle, appended after the explicitly-listed providers (so framework providers > boot first). List a provider explicitly only to control its order relative to others. See > [Conventions](/docs/conventions#providers-appproviders). ## Declaring dependencies Listing providers in the right order works, but it's fragile — it asks every app to remember that, say, `AdminProvider` needs `FlowProvider`'s `Router.flow()` macro to exist first. Instead, a provider can declare what it needs on the class itself with `static dependsOn`, and the framework pulls that dependency in and boots it first: ```typescript // packages/admin/src/provider/AdminProvider.ts import { ServiceProvider } from "zerotal"; import { FlowProvider } from "@zerotal/flow"; export class AdminProvider extends ServiceProvider { static dependsOn = [FlowProvider]; } ``` `dependsOn` holds **provider classes** — real imports, not magic strings — so it's type-checked and survives renames. It does two jobs at once: - **Pulls the dependency in.** You register only the feature you want — `AdminProvider` — and `FlowProvider` comes along automatically, even when it isn't listed in `bootstrap/providers.ts`. You list the _features_ your app uses, not the plumbing they each need. - **Orders it first.** A dependency always boots before the provider that declared it, regardless of where either sits in the list. So an app that uses the admin panel only needs the panel itself: ```typescript fragment // bootstrap/providers.ts — FlowProvider arrives via AdminProvider.dependsOn const providers = [AdminProvider]; export default providers; ``` ### Registration is idempotent You can list a provider explicitly _and_ have it pulled in through someone's `dependsOn` — it still boots exactly once. Registration is idempotent by class identity, and the first registration keeps its position, so explicit and automatic registration safely overlap. Listing `FlowProvider` yourself while `AdminProvider` also depends on it is harmless, not a double-boot. ### The priority tiebreak `dependsOn` orders a provider relative to the ones it names. Providers with _no_ dependency relationship fall back to `static priority` (lower boots earlier; defaults to `0`), then to registration order. It's a coarse knob — useful for a framework-core provider that should generally boot ahead of everything else, without every other provider having to name it explicitly: ```typescript fragment export class CoreProvider extends ServiceProvider { static priority = -100; // boots before ordinary (priority 0) providers } ``` Reach for `dependsOn` to express a real, specific dependency; reach for `priority` only for broad "this should come early/late" ordering. ### Cycles and environments The dependency graph is resolved once, at boot, with a few guarantees worth knowing: - **Transitive.** A dependency's own `dependsOn` is pulled in too, recursively, and de-duplicated. - **Environment-aware.** A dependency excluded by its own `static environments` isn't dragged in where it doesn't belong — a `web`-only provider won't be pulled into a `console` boot just because a console-active provider lists it. - **Cycle-checked.** A circular `dependsOn` throws at boot with the offending path (`Circular provider dependency: A → B → A`), failing fast rather than booting in a surprising order. > **Note** — your explicit list is never reshuffled. `dependsOn`/`priority` order the > providers that are _pulled in_; the providers you list by hand in > `bootstrap/providers.ts` keep their authored order, with dependencies slotted in > ahead of the providers that need them. ## onRegister — bind things Register container bindings, named middleware groups, and router macros. This hook is **synchronous** — no `await` — and runs before any binding is resolved, so treat it as pure wiring. The factory closures you pass don't run yet; they run _later_, when the binding is first resolved. ```typescript fragment // inside a ServiceProvider onRegister(): void { // Singleton — one shared instance per app lifetime this.app.container.singleton(AnalyticsService, () => new AnalyticsService({ apiKey: Bun.env.ANALYTICS_KEY! }) ); // Per-request scoped binding. The factory may be async — `make()` returns a // promise, so await it inside the factory. this.app.container.scoped(CartService, async (c) => new CartService(await c.make(DB)) ); // A named middleware group usable in Router.group({ middleware: ['api'] }) Router.middlewareGroup('api', [ThrottleMiddleware, JsonMiddleware]); // Extend the Router with a custom route method (macro) Router.macro('webhook', webhookRoute); } ``` ## onBooting — prepare in order `onBooting()` runs **sequentially**, in provider-list order, between register and booted. Reach for it only when one provider must finish preparing before the next one even registers — most providers skip it entirely. It's async, so you can `await`: ```typescript fragment // inside a ServiceProvider async onBooting(): Promise { // e.g. open a connection pool that a provider listed after this one // expects to already exist when its own onRegister() runs. const db = await this.app.container.make(DB); await db.connect(); } ``` ## onBooted — use things By `onBooted()` every provider has registered, so this is the safe place to _resolve_ bindings (including from other providers), start background work, and register event listeners. It runs in parallel across all providers: ```typescript fragment // inside a ServiceProvider async onBooted(): Promise { // Resolve a binding from another provider const db = await this.app.container.make(DB); // Register global event listeners Events.on(UserRegistered, async (event) => { await sendWelcomeEmail(event.user); }); // Start a background polling loop (only in the 'web' runtime) if (this.app.environment === 'web') { startHealthMonitor(); } } ``` ## this.app API `this.app` is the [Application](/docs/application) instance. The members you'll use from inside a provider: | Property / Method | Description | | ----------------------------- | ------------------------------------------------------------ | | `this.app.container` | The IoC [container](/docs/container) — bind and resolve here | | `this.app.environment` | `'web' \| 'console' \| 'worker' \| 'test' \| 'repl'` | | `this.app.useOnce(mw)` | Add a middleware to the global pipeline exactly once | | `this.app.registerConcern(d)` | Contribute an auto-discovery concern (see below) | To read configuration, resolve it from the container or use the `Config` facade — `this.app.container.makeSync('config').get('app.name')`, or simply `Config.get('app.name')` once booted. ### Contributing a convention A provider can add its own auto-discovered directory by registering a concern descriptor in `onRegister()`/`onBooting()`. The framework scans the directory at boot and calls `register()` for each file's exports: ```typescript fragment // inside a ServiceProvider onRegister(): void { this.app.registerConcern({ name: "validators", order: 60, // models=10, observers=20, policies=30, listeners=40 dir: "app/validators", register(mod, ctx) { for (const exported of Object.values(mod)) { /* register exported as needed */ } }, }); } ``` A `run(ctx)` hook (without `dir`) defines a one-shot step instead of a directory scan. See [Conventions](/docs/conventions#custom-concerns). ## Deferred providers When a provider registers something that's rarely needed at boot — a search engine, a payment SDK — you can **defer** it so it doesn't run until one of its bindings is first resolved. This keeps cold-start fast. Deferral takes two parts. First, the provider declares which tokens it provides: ```typescript // app/providers/SearchProvider.ts import { ServiceProvider } from "zerotal"; export class SearchProvider extends ServiceProvider { static provides = ["search.engine"] as const; onRegister(): void { this.app.container.singleton( "search.engine", () => new MeilisearchEngine({ host: Bun.env.MEILISEARCH_URL! }), ); } } ``` Second — and this is the part that actually defers it — register it with `app.defer()` instead of the normal providers array. `static provides` on its own is just metadata; it's `defer()` that wires the lazy boot: ```typescript fragment // bootstrap/app.ts const app = Application.create({ providers }); app.defer([SearchProvider]); // array form reads each provider's `static provides` ``` The first `make("search.engine")` runs the provider's full `onRegister → onBooting → onBooted` sequence, then resolves the binding. > **Warning** — A deferred provider must _not_ also sit in the eager providers list > or in `app/providers/*` auto-discovery, or it would boot at startup anyway, > defeating the deferral. See [The Application](/docs/application#deferred-providers) > for the `defer()` overloads. ## Environment-specific registration A provider runs in every runtime by default. Branch on `this.app.environment` to bind a different implementation per environment — a fake mailer under `test`, the real one everywhere else: ```typescript fragment // inside a ServiceProvider onRegister(): void { if (this.app.environment === 'test') { this.app.container.singleton(Mailer, () => new FakeMailer()); } else { this.app.container.singleton(Mailer, () => new SmtpMailer()); } } ``` To skip a provider entirely outside certain runtimes, set `static environments` on the class (e.g. `static environments = ['web']`) — the Application filters it out before it's ever instantiated. ## Auto-registering middleware Providers can push middleware into the global pipeline via `this.app.useOnce()` — the framework guarantees it's added exactly once, even if the same middleware is registered by several providers: ```typescript fragment // inside a ServiceProvider onBooting(): Promise { this.app.useOnce(SessionMiddleware); this.app.useOnce(AuthMiddleware); } ``` This is how framework packages (e.g. `@zerotal/session`) inject their middleware transparently, without the app developer needing to add it manually. ## Which hook should I use? - **`onRegister`** — for _binding_ services into the container, registering middleware groups, and router macros. Nothing is resolvable yet, so never call `make()` here. - **`onBooting`** — only when one provider must be fully prepared before a later provider registers, or to auto-register middleware via `useOnce()`. Most providers skip it. - **`onBooted`** — for _resolving_ services (including across providers), starting background work, and registering event listeners. - **No provider at all** — for one or two bindings with no lifecycle needs, prefer the bootstrap [`app.bind()`](/docs/application#registering-services-without-a-provider) callback or the [`app/services` convention](/docs/container#the-appservices-convention). ## References The lifecycle hooks a provider may override, in boot order: | Hook | Signature | When it runs | | -------------------- | ----------------------------------------------------- | ----------------------------------------------------------------- | | `onRegister` | `onRegister(): void` | Sync, before any binding is resolved. Bind here. | | `onBooting` | `onBooting(): Promise` | Sequentially in list order, after all providers registered. | | `onBooted` | `onBooted(): Promise` | In parallel once every provider has booted. Resolve here. | | `onStarting` | `onStarting(): Promise` | Just before the app starts accepting work (e.g. the HTTP server). | | `onStarted` | `onStarted(): Promise` | Once the app has started. | | `onStopping` | `onStopping(): Promise` | When graceful shutdown begins. Release resources here. | | `onStopped` | `onStopped(): Promise` | Once shutdown is complete. | | `onRequestReceived` | `onRequestReceived(ctx: HttpContext): Promise` | Before the middleware pipeline runs, per request. | | `onRequestProcessed` | `onRequestProcessed(ctx: HttpContext): Promise` | After the pipeline completes and `ctx.response` is set. | | `onResponseSent` | `onResponseSent(ctx: HttpContext): Promise` | After the response has been sent to the client. | | `replContext` | `replContext(): Record` | Returns variables to expose in `bun zt repl`. | Static members on the provider class: | Member | Type | Description | | --------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `static environments` | `AppEnvironment[]` | Runtimes the provider participates in. Defaults to all five. | | `static provides` | `readonly (keyof ContainerBindings)[]` | Tokens this provider registers. Required for the array form of `app.defer([Provider])`. | | `static dependsOn` | `ProviderClass[]` | Providers this one needs — pulled in automatically and booted first. See [Declaring dependencies](/docs/providers#declaring-dependencies). | | `static priority` | `number` | Boot-order tiebreak among providers with no `dependsOn` relationship. Lower boots earlier; default `0`. | ## Next steps - [Container](/docs/container) — the IoC container providers bind into. - [Lifecycle](/docs/lifecycle) — when `onRegister` and `onBooted` run during boot. - [Conventions](/docs/conventions) — auto-discovery of providers and concerns. - [Application](/docs/application) — the `this.app` instance and its environment. --- Source: https://zerotal.dev/docs/events # Events Zerotal has **two** event systems: one for reacting to things that happen in your domain, and one for observing the framework's own internals. Almost all of the time you want just one of them — **application events** — so start there and treat the other as advanced. ``` your code ──emit──▶ Events facade (Emitter) ──▶ listener classes (async, queueable) framework ──emit──▶ FrameworkEvents (bus) ──▶ handler functions (sync, no I/O) ``` - **Application events** are for things that happen in _your app_: a user signed up, an order was placed. You emit them and write listeners that react — send an email, grant a bonus. You'll use these through the `Events` facade. **This is the one you reach for.** → [jump to it](#emitter-the-events-facade) - **Framework events** are for _observing the framework itself_: slow queries, finished requests, cache hits. The framework emits them and built-in tools (the logger, devtools) listen. You only touch these to build your own instrumentation — metrics, audit, alerting. → [jump to it](#frameworkevents) **Which one do I want?** Ask what fired the event: - Something _you_ did in your domain → **application event**. - Something the _framework_ did under the hood → **framework event**. Two rules keep them from blurring: never do I/O (network, disk, DB) inside a framework-event handler — they run synchronously on the request hot path — and never use framework events to drive business logic. If you want the full side-by-side, here it is — but you can skip it and come back once you've read the section for the one you need: | Aspect | Framework events | Application events | | ------------- | --------------------------------- | --------------------------- | | Purpose | Observing the framework | Reacting to your domain | | Who emits | The framework | Your code | | Who listens | Built-in tools (logger, devtools) | Your code | | A listener is | a plain **function** | a **class** with `handle()` | | Timing | **synchronous**, fast, no I/O | async; can be **queued** | ## FrameworkEvents A single synchronous bus, exported as a singleton from `zerotal`. Framework packages emit lifecycle events into it; infrastructure packages subscribe to react. It is the reason domain packages never import devtools or the logger — everyone talks through the bus instead. ### API ```typescript fragment import { FrameworkEvents } from "zerotal"; import { QueryExecuted } from "@zerotal/orm"; // Subscribe — returns an unsubscribe function. const off = FrameworkEvents.on(QueryExecuted, (event) => { metrics.observe("db.query.ms", event.durationMs); }); // Emit (done by the framework; shown for completeness). FrameworkEvents.emit(new QueryExecuted(sql, bindings, startMs, durationMs, rowCount, ctx)); // Stop listening. off(); // Test isolation: drop every subscription. FrameworkEvents.clear(); // How many handlers are currently registered (leak assertions in tests). FrameworkEvents.handlerCount(); ``` ### Handler contract `emit()` runs every handler **synchronously in the caller's stack** and **swallows handler errors** — a throwing subscriber can never affect the code that emitted the event. Because emission is on the hot path, handlers must be fast and must not perform I/O. If you need to do real work, buffer the data and hand it off (e.g. dispatch a queue job) from outside the handler, or subscribe with `onAsync`: ```ts fragment // A ledger row is I/O. The request never waits for it. const off = FrameworkEvents.onAsync(AiGenerated, async (e) => { await LedgerRow.create({ model: e.model, costUsd: e.costUsd }); }); // On shutdown, so the last rows are not lost to the process exiting: await FrameworkEvents.settled(); ``` `onAsync` runs the handler after the emitter's current synchronous work, awaits it, and logs a failure to the `events` channel rather than throwing it at the emitter or leaving it as an unhandled rejection (which is what an `async` function passed to `on()` does when it fails). It is not durable: a handler still running when the process exits is lost, so use a queue job when the work must survive a crash. ### Subscribing from a provider Subscribe in `onBooted`, keep the unsubscribe functions, and release them in `onStopping` so handlers never leak between boots or test suites: ```typescript fragment import { ServiceProvider, FrameworkEvents, RequestFailed } from "zerotal"; export class MetricsProvider extends ServiceProvider { private _unsubs: Array<() => void> = []; override async onBooted(): Promise { this._unsubs.push( FrameworkEvents.on(RequestFailed, (e) => { metrics.increment("http.5xx", { path: (e.ctx as any).url?.pathname }); }), ); } override onStopping(): void { for (const off of this._unsubs) off(); this._unsubs = []; } } ``` ### Event catalogue Every event class is exported from `zerotal`. Events carry the active `RequestContext` as `ctx` where one applies (it is `undefined` outside a request). **HTTP** (`@zerotal/core`) | Event | Fields | Emitted by | | ------------------- | ----------------------------------------- | ---------------------------------------- | | `RequestHandled` | `ctx, startMs, durationMs` | route dispatcher / server, on success | | `RequestFailed` | `ctx, startMs, durationMs, error, status` | dispatcher / server catch blocks | | `MiddlewareSkipped` | `name, reason, ctx` | a middleware short-circuits the pipeline | `RequestFailed` also carries the thrown error's `type` and `stack`, and `expected`, which is `true` when the error is one the framework raised to answer the client ([which ones](/docs/errors#silencing-expected-errors)). The `status` alone cannot tell a refused request from a fault: an `HttpClientError` from an upstream 401 is answered with a 401 too. **ORM** (`@zerotal/orm`) | Event | Fields | | ----------------------- | --------------------------------------------------- | | `QueryExecuted` | `sql, bindings, startMs, durationMs, rowCount, ctx` | | `NPlusOneDetected` | `fingerprint, count, ctx` | | `TransactionStarted` | `txId, ctx` | | `TransactionCommitted` | `txId, durationMs, ctx` | | `TransactionRolledBack` | `txId, durationMs, reason, ctx` | | `MigrationRan` | `name, direction, durationMs, ok, error?` | **Mail** (`@zerotal/notifications`) | Event | Fields | | --------------- | -------------------------------------------------- | | `MessageSent` | `className, to, subject, html, durationMs, queued` | | `MessageQueued` | `className, to, subject, queue` | | `MessageFailed` | `className, to, subject, durationMs, error` | **Cache** (`@zerotal/cache`) | Event | Fields | | -------------- | ----------------------------------------------------------------------------- | | `CacheQueried` | `op ('hit'\|'miss'\|'write'\|'forget'\|'flush'\|'has'), key, ttl, durationMs` | | `CacheEvicted` | `key, reason ('ttl'\|'capacity'\|'manual')` | **Queue** (`@zerotal/queue`) | Event | Fields | | -------- | ----------------------------------------------------------------------------------------------- | | `JobRan` | `className, queue, status ('dispatched'\|'completed'\|'failed'\|'retried'), durationMs, error?` | **Scheduler** (`@zerotal/scheduler`) | Event | Fields | | ------------- | ------------------------------------------------------------------- | | `TaskRan` | `name, durationMs, ok` | | `TaskFailed` | `name, durationMs, error` | | `TaskSkipped` | `name, reason ('env'\|'window'\|'when'\|'skip'\|'overlap'\|'lock')` | **Auth** (`@zerotal/auth`) | Event | Fields | | --------------------- | -------------------------------- | | `LoginAttempted` | `guard, identifier, ctx` | | `LoginSucceeded` | `guard, userId, ctx` | | `LoginFailed` | `guard, identifier, reason, ctx` | | `LoggedOut` | `guard, userId, ctx` | | `TokenIssued` | `tokenId, abilities, userId` | | `AuthorizationDenied` | `ability, userId, ctx` | ### Who already subscribes - The **logger** auto-logs slow queries, N+1, and 4xx/5xx responses — see [Logger](/docs/logger). - **Devtools** buffers per-request traces keyed on the request context and streams them to the live dashboard — see [Devtools](/docs/devtools). You can add your own subscribers (metrics, audit, alerting) the same way, without the emitting packages knowing you exist. ### Reading the request context in a handler Some events carry `ctx`; for those that do not (mail/cache/queue happen outside the HTTP frame of reference), resolve the current request lazily: ```typescript fragment import { FrameworkEvents, RequestContext } from "zerotal"; import { CacheQueried } from "@zerotal/cache"; FrameworkEvents.on(CacheQueried, (e) => { const requestId = RequestContext.tryGet()?.requestId; // undefined outside a request metrics.increment(`cache.${e.op}`, { requestId }); }); ``` ## Emitter / the Events facade For business events — things that happened in your domain that other parts of your app should react to. Events are plain classes; listeners are classes with a `handle()` method. Access the per-application `Emitter` singleton through the `Events` facade. ### Define an event and a listener ```typescript fragment // app/events/UserRegistered.ts export class UserRegistered { constructor( readonly userId: number, readonly email: string, ) {} } // app/listeners/SendWelcomeEmail.ts import type { UserRegistered } from "../events/UserRegistered.ts"; import { Notify } from "@zerotal/notifications"; import { WelcomeNotification } from "../notifications/WelcomeNotification.ts"; export class SendWelcomeEmail { async handle(event: UserRegistered): Promise { await Notify.send({ email: event.email }, new WelcomeNotification(event.userId)); } } ``` ### Register and emit ```typescript fragment // usually a provider's onBooted(), or bootstrap code import { Events } from "zerotal"; import { UserRegistered } from "./app/events/UserRegistered.ts"; import { SendWelcomeEmail } from "./app/listeners/SendWelcomeEmail.ts"; Events.on(UserRegistered, SendWelcomeEmail); // Later, in a controller or service: await Events.emit(new UserRegistered(user.id, user.email)); ``` `Events` is a facade over the per-application `Emitter` singleton (the `events` container binding). Whatever you call on `Events` runs against the live emitter. **What `emit()` actually does:** it looks up every listener registered for the event's class, **instantiates a fresh listener per dispatch**, and runs them all **concurrently** with `Promise.allSettled`. That has two consequences worth internalising: - **Failures are isolated.** One listener throwing doesn't stop the others, and the error is _logged, not rethrown_ — `await Events.emit(...)` never rejects because a listener failed. Don't rely on a `try/catch` around `emit()` to catch listener errors; it won't. - **Order is not guaranteed.** Listeners run in parallel, so don't write one that assumes another has already finished. If you genuinely need ordered, awaited execution, use `Events.emitSync(event)` — it runs listeners one at a time in registration order and, unlike `emit()`, **does propagate** the first error. `await`-ing `emit()` waits for all inline listeners to settle (queued ones return as soon as the job is dispatched — see [Queued listeners](#queued-listeners)). To unregister a listener, call `Events.off(EventClass, ListenerClass)`. ### Auto-discovered listeners You usually don't call `Events.on(...)` yourself. A listener placed in `app/listeners/` declares the event(s) it handles via `static listens`, and the framework binds it on the emitter at boot — no registration code required. ```typescript fragment // app/listeners/SendWelcomeEmail.ts import { UserRegistered } from "../events/UserRegistered.ts"; export class SendWelcomeEmail { static listens = UserRegistered; async handle(event: UserRegistered): Promise { await Notify.send({ email: event.email }, new WelcomeNotification(event.userId)); } } ``` ### One listener, several events `static listens` accepts an array — the listener binds to each event and `handle()` receives whichever one fired: ```typescript fragment // app/listeners/GrantWelcomeBonus.ts import { UserRegistered } from "../events/UserRegistered.ts"; import { UserReactivated } from "../events/UserReactivated.ts"; export class GrantWelcomeBonus { static listens = [UserRegistered, UserReactivated]; async handle(event: UserRegistered | UserReactivated): Promise { await Credits.grant(event.userId, 100); } } ``` Multiple listeners can subscribe to the same event; each is instantiated and run with `Promise.allSettled`, so one failure never blocks the others. ### Queued listeners Listeners run inline by default. For slow work (sending mail, calling an API), mark the listener to run on the queue instead — the emitter serialises the event and dispatches a job, so `emit()` returns without waiting for the work to finish. Set `queue` to `true` for the default queue, or to a queue name. Two optional fields tune the retry behaviour of the dispatched job: ```typescript fragment // app/listeners/SendWelcomeEmail.ts import { UserRegistered } from "../events/UserRegistered.ts"; export class SendWelcomeEmail { static listens = UserRegistered; queue = "mail"; // or `true` for the default queue maxAttempts = 3; // optional: retry up to 3 times on failure retryDelay = 30; // optional: seconds to wait between attempts async handle(event: UserRegistered): Promise { await Notify.send({ email: event.email }, new WelcomeNotification(event.userId)); } } ``` Note `queue` (and the retry fields) are **instance** properties, not `static` — they describe how _this_ listener runs, whereas `static listens` describes _what_ it listens to. If no queue manager is registered, a queued listener falls back to running inline, so it's safe to add before you've configured a queue — it simply runs synchronously until a queue exists. Requires [`@zerotal/queue`](/docs/queue) for actual deferral. ### Events are auto-discovered too Event classes are plain data classes — they need no registration. Files in `app/events/` are imported at boot so their module-level side effects (if any) are in place and a production manifest can reference them. You can also just import an event class directly where you emit it; the `app/events/` folder is a convention, not a requirement. ### Reacting to model changes To emit application events from ORM lifecycle hooks (created / updated / deleted), use a model's `dispatchesEvents` map — see [Conventions → Model events](/docs/conventions#model-events). ### Broadcasting an event to the browser If an event class defines a `broadcastOn()` method, emitting it **also broadcasts it** over WebSockets to the channels it names — in addition to running any listeners. This is wired through [`@zerotal/broadcasting`](/docs/broadcasting); core stays broadcasting-free and calls the hook only when one is registered. Worth knowing here for one subtlety: the broadcast fires **even when the event has no listeners**, so an event can be purely a broadcast with no `handle()` anywhere. See [Broadcasting](/docs/broadcasting) for channels, authorization, and the client side. ### Testing events Both buses expose a reset so one test never leaks subscriptions into the next: ```typescript fragment import { Events, FrameworkEvents } from "zerotal"; // Remove every application listener Events.clear(); // Assert a specific event has a listener wired Events.hasListeners(UserRegistered); // → boolean // Drop every framework subscription, and check for leaks FrameworkEvents.clear(); FrameworkEvents.handlerCount(); // → number of live handlers ``` To assert that emitting an event triggered the right side effect, register a tiny inline listener (or spy) before emitting and check it ran — `emit()` awaits inline listeners, so a plain `await Events.emit(...)` is enough to observe their effects. ## References **`Events` facade** (Tier 2 — application events, from `zerotal`): | Method | Description | | ----------------------------- | --------------------------------------------------------------- | | `Events.on(Event, Listener)` | Register a listener class for an event class. | | `Events.off(Event, Listener)` | Remove a previously registered listener. | | `Events.emit(event)` | Dispatch concurrently; failures isolated and logged. | | `Events.emitSync(event)` | Dispatch sequentially in order; **propagates** the first error. | | `Events.hasListeners(Event)` | Whether any listener is registered for the event class. | | `Events.clear()` | Remove every listener (use in tests). | **`FrameworkEvents`** (Tier 1 — instrumentation, from `zerotal`): | Method | Description | | ------------------------------------ | -------------------------------------------------------- | | `FrameworkEvents.on(Event, fn)` | Subscribe a function; returns an unsubscribe function. | | `FrameworkEvents.onAsync(Event, fn)` | Subscribe an async handler, run off the emitter's stack. | | `FrameworkEvents.settled()` | Wait for every running async handler to finish. | | `FrameworkEvents.emit(event)` | Fire synchronously to all handlers; errors swallowed. | | `FrameworkEvents.clear()` | Drop every subscription (use in tests). | | `FrameworkEvents.handlerCount()` | Count of live handlers, for leak assertions in tests. | **Listener declaration fields** (Tier 2 listener classes): | Field | Kind | Description | | ---------------- | -------- | ------------------------------------------------------------ | | `static listens` | static | The event class (or array of classes) this listener handles. | | `handle(event)` | method | Runs when a subscribed event fires. | | `queue` | instance | `true` or a queue name → run on the queue instead of inline. | | `maxAttempts` | instance | Optional retry count for a queued listener. | | `retryDelay` | instance | Optional seconds between retry attempts. | For the full list of Tier 1 event classes and their fields, see the [Event catalogue](#event-catalogue) above. ## Next steps - [Conventions](/docs/conventions#events-listeners-appevents-applisteners) — how `app/events` and `app/listeners` are discovered. - [Queue](/docs/queue) — deferring listener work to background jobs. - [Logger](/docs/logger) — a built-in FrameworkEvents subscriber. - [Telemetry](/docs/telemetry) — turn framework events into metrics. --- Source: https://zerotal.dev/docs/routing # Routing The router maps incoming HTTP requests to the controller, view, or closure that should handle them, and is where you declare your application's URLs. Zerotal offers two complementary styles — **explicit** routes declared in route files and **file-based** routes discovered automatically from a directory tree. Both register into the same `Router` singleton and can be mixed freely in one app. Routing ships inside `@zerotal/core`, so there is no package to install or provider to register — the `Router` is available as soon as your app boots. ## Getting Started ```typescript // routes/index.ts import { Router, route } from "zerotal"; ``` ## Basic usage Register a `GET` route to a controller action, or to an inline closure: ```typescript fragment // routes/index.ts import { Router } from "zerotal"; Router.get("/users", UserController, "index"); Router.get("/", (ctx) => ctx.html`

Home

`); ``` A `GET /users` request now runs `UserController.index`, and `GET /` returns the inline HTML. ## Which routing style should I use? - **Explicit routes** (`routes/index.ts`) — best when you want every URL visible in one place, fine-grained control over names and ordering, or resource/group helpers. Start here. - **File-based routes** (a directory tree) — best for large apps where the URL map mirrors the filesystem, or for page-heavy frontends. Opt in per app. The two compose: file routes register first during boot, then explicit routes run and take precedence on duplicate `METHOD + path` keys. See [route registration order](#route-registration-order) for the full precedence rules. ## Explicit routes ### HTTP verbs ```typescript fragment // routes/index.ts Router.get("/users", UserController, "index"); Router.post("/users", UserController, "store"); Router.put("/users/:id", UserController, "update"); Router.patch("/users/:id", UserController, "update"); Router.delete("/users/:id", UserController, "destroy"); ``` Each call returns a `RouteRegistration` you can chain: ```typescript fragment // routes/index.ts Router.get("/posts/:slug", PostController, "show").name("posts.show").bind("post", Post); ``` Every `GET` route also answers `HEAD` — explicit, raw, view and markdown routes alike — so an uptime probe or `curl -I` gets the status and headers the `GET` would, with no body. The `GET` handler runs to produce them. Where the `HEAD` has a `Content-Length`, it is the length of the body the handler returned, measured, even where the handler declared another. A body that declares a length but is still arriving, such as a stream still producing, a file, or a large proxied `fetch()` response, is not waited for: the `HEAD` is answered with `Transfer-Encoding: chunked` and no length, and the body is cancelled. An event stream (`text/event-stream`) is answered the same way, rather than read to an end it never reaches. When `Router.raw()` registers a `GET` on a path a markdown dir or another route already serves, its `HEAD` follows it there too, unless a `Router.raw("HEAD", …)` of its own is registered. #### Per-route middleware Pass middleware classes as the fourth argument: ```typescript fragment // routes/index.ts Router.get("/dashboard", DashboardController, "index", [AuthMiddleware]); Router.post("/posts", PostController, "store", [AuthMiddleware, ThrottleMiddleware]); ``` #### Inline closure handlers Every verb method also accepts a closure instead of a `Controller`/action pair — handy for small endpoints that don't warrant a controller. The handler receives the same request `HttpContext` a controller action does; raw route params and resolved model bindings live on `ctx.params`: ```typescript // routes/index.ts import { Router, type HttpContext } from "zerotal"; Router.get("/", (ctx) => ctx.html`

Home

`); Router.get("/health", (ctx) => ctx.json({ ok: true })); // Raw route params arrive on ctx.params — type them with HttpContext<{ ... }>: Router.get("/posts/:slug", (ctx: HttpContext<{ slug: string }>) => ctx.json({ slug: ctx.params.slug }), ); ``` Middleware is passed as the **third** argument in closure form (there's no action name), and the returned `RouteRegistration` still chains `.name()` / `.bind()`: ```typescript fragment // routes/index.ts Router.get("/admin", (ctx) => ctx.json({ ok: true }), [AuthMiddleware]); Router.get("/posts/:post", (ctx: HttpContext<{ post: Post }>) => ctx.json({ post: ctx.params.post }), ).bind("post", Post); ``` > **Note** — Zerotal distinguishes the two forms by the third argument: a string is > treated as a controller action; anything else (a middleware array or nothing) > means the second argument is a closure handler. ### Resource routes `Router.resource()` registers all seven RESTful actions in one call: ```typescript fragment // routes/index.ts Router.resource("posts", PostController); ``` | Method | Path | Action | | -------- | ----------------- | --------- | | `GET` | `/posts` | `index` | | `GET` | `/posts/create` | `create` | | `POST` | `/posts` | `store` | | `GET` | `/posts/:id` | `show` | | `GET` | `/posts/:id/edit` | `edit` | | `PUT` | `/posts/:id` | `update` | | `DELETE` | `/posts/:id` | `destroy` | `PATCH /:id` is also registered and maps to `update`, so both `PUT` and `PATCH` are accepted. #### Filtering actions ```typescript fragment // routes/index.ts // Register only these actions Router.resource("photos", PhotoController).only(["index", "show"]); // Register everything except these Router.resource("tags", TagController).except(["create", "edit"]); ``` #### Resource middleware ```typescript fragment // routes/index.ts Router.resource("comments", CommentController, [AuthMiddleware]); ``` ### View routes Register a GET route that renders a `@zerotal/core` JSX component directly — no controller class needed for simple pages: ```typescript fragment // routes/index.ts import { AboutPage } from "../resources/views/AboutPage.tsx"; import { DashboardPage } from "../resources/views/DashboardPage.tsx"; // Static props — evaluated once at registration Router.view("/about", AboutPage, { title: "About Us" }); // Dynamic props — factory is called on each request Router.view("/dashboard", DashboardPage, (ctx) => ({ user: ctx.user, greeting: `Hello, ${ctx.user?.name ?? "guest"}`, })); // No props Router.view("/privacy", PrivacyPage); // With middleware Router.view("/settings", SettingsPage, (ctx) => ({ user: ctx.user }), [AuthMiddleware]); ``` The route chains `.name()` and `.withLayout()`: ```typescript fragment // routes/index.ts Router.view("/about", AboutPage).name("about").withLayout(AppLayout); ``` ### Static file serving Serve a local directory under a URL prefix: ```typescript fragment // routes/index.ts Router.static("/assets", "./public/assets"); Router.static("/uploads", "public/uploads"); // With cache headers Router.static("/assets", "./public", { headers: { "Cache-Control": "public, max-age=31536000, immutable" }, }); ``` Any `GET /assets/logo.svg` resolves to `./public/assets/logo.svg`, served with Bun's native file streaming. Returns 404 for missing files. By default every file is pre-registered at boot as a static `Response` (zero JS per request); pass `eager: false` to fall back to a per-request lookup. ### Markdown file serving Serve a directory of `.md` files as rendered HTML pages: ```typescript fragment // routes/index.ts Router.markdown("/docs", "./docs"); // With parser options and a fallback title Router.markdown("/docs", "./docs", { title: "Zerotal Docs", headings: { ids: true }, }); ``` URL mapping: `GET /docs/orm` → `./docs/orm.md` (also tries `./docs/orm/index.md` for bare directory paths). Uses `Bun.markdown.html()` with GFM extensions (tables, strikethrough, tasklists, autolinks) enabled by default. ### Raw routes Register a handler that receives the raw `Request` and bypasses the entire global middleware pipeline — no `HttpContext`, no session, no auth. Useful for internal health checks or asset endpoints: ```typescript fragment // routes/index.ts Router.raw("GET", "/__ping", () => new Response("pong")); Router.raw("GET", "/health", async () => { const ok = await db .query("SELECT 1") .then(() => true) .catch(() => false); return Response.json({ ok }); }); ``` > **Warning** — Raw routes skip every middleware (session, CSRF, auth). Only use > them for endpoints that must not run the pipeline. They are compiled last and > take precedence over same-path pipeline routes. ### Flow routes Added by the `@zerotal/flow` package: ```typescript fragment // routes/index.ts import { Router } from "zerotal"; Router.flow("/dashboard", DashboardPage); Router.flow("/chat", ChatPage, [AuthMiddleware]); ``` See the [Flow](/docs/flow) guide for full details. ### Request body size Every route accepts a request body of up to `app.maxRequestBodySize` bytes, 8 MiB unless you set it. A body over the limit is answered with `413` before any middleware or handler runs, and without being read, so refusing it costs no memory. One route sometimes needs more than the rest of the app: a webhook that receives mail with an attachment, an upload endpoint. Raising `app.maxRequestBodySize` raises it for every route, including the login form. Say it on the route instead: ```typescript fragment // routes/index.ts Router.post("/webhooks/inbound-mail", InboundMailController, "store").maxBodySize(25 * 1024 * 1024); // Or lower, for a route that should never see much. Router.post("/login", AuthController, "login").maxBodySize(16 * 1024); ``` The server is started accepting the largest limit any route declared, and the framework holds every other route to its own, so `/login` above still refuses a 1 MiB body even though the server would take 25 MiB. An app that never calls `maxBodySize` starts the server exactly as before. The limit is judged by the `Content-Length` header, which the server holds the connection to: a client cannot send more than it declared. A body sent in chunks, with no declared length, cannot be measured without reading it, so once any route sets a limit, such a body is answered with `411 Length Required` on every route whose limit is below the server ceiling. Browsers, `fetch` with a string, form or blob, and reverse proxies that buffer request bodies all declare a length; only a streamed upload does not. On Bun 1.3 the next request on the same connection as a refused chunked body is answered `400` once; Bun 1.4 does not do that. A hot reload (`SIGUSR2`) re-applies the limits of the reloaded routes, but cannot raise the ceiling the server started with. A route that asks for more after a reload needs a restart, and the log says so. > **Note** — The limit is on the whole request body. A multipart upload of a 20 MiB file is a body of a little over 20 MiB, and base64 inside JSON is a third larger than the bytes it carries. Set the limit above the size you mean to accept. ## Route groups Groups apply a shared prefix and/or middleware stack to a set of routes. Groups nest — prefix and middleware accumulate. ```typescript fragment // routes/index.ts Router.group({ prefix: "/api/v1" }, () => { Router.get("/users", UserController, "index"); Router.post("/users", UserController, "store"); // → GET /api/v1/users, POST /api/v1/users }); ``` ```typescript fragment // routes/index.ts Router.group({ prefix: "/api/v1", middleware: AuthMiddleware }, () => { Router.resource("posts", PostController); }); ``` A group is bookkeeping applied while its callback runs, not a runtime wrapper. Routes register themselves with the accumulated prefix and middleware already baked in, so grouping costs nothing per request. The surrounding state is restored even when the callback throws, so one broken group cannot leak its prefix into the routes declared after it. ### Named middleware groups Define a group of middleware classes under a string key, then reference it by name: ```typescript fragment // in a ServiceProvider or bootstrap Router.middlewareGroup("api", [ThrottleMiddleware, JsonMiddleware]); Router.middlewareGroup("web", [SessionMiddleware, CsrfMiddleware]); // Reference by name Router.group({ prefix: "/api", middleware: "api" }, () => { Router.resource("posts", PostController); }); // Mix names and classes Router.group({ middleware: ["web", AuthMiddleware] }, () => { Router.get("/dashboard", DashboardController, "index"); }); ``` Naming a stack once and referring to it keeps the definition in one place, which matters most when the stack changes: adding a middleware to the `web` group applies it everywhere that group is used instead of requiring an edit at every call site. ### Nested groups ```typescript fragment // routes/index.ts Router.group({ prefix: "/admin" }, () => { Router.group({ middleware: [AuthMiddleware, AdminMiddleware] }, () => { Router.get("/dashboard", AdminController, "dashboard").name("admin.dashboard"); Router.resource("users", AdminUserController); }); }); ``` The three options compose differently as groups nest, which is worth knowing before relying on it: | Option | Nesting behaviour | | ------------ | -------------------------------------------------------------------- | | `prefix` | Concatenates outer then inner — `/admin` + `/users` → `/admin/users` | | `middleware` | Appends, outermost first, so the outer stack runs earlier | | `domain` | Replaces — an inner `domain` overrides the outer one entirely | Because middleware order follows nesting depth, an outer `AuthMiddleware` runs before an inner `AdminMiddleware`. Put the checks that should fail fastest — or that the inner ones depend on, such as resolving the current user — in the outer group. ### Domain & subdomain routing The `domain` option scopes a group of routes to a specific host. Dynamic `:label` segments are captured and exposed on the context via `ctx.subdomains`. ```typescript fragment // routes/index.ts import { Router } from "zerotal"; // Static host Router.group({ domain: "admin.app.com" }, () => { Router.get("/", AdminController, "dashboard"); }); // Dynamic subdomain — captured as ctx.subdomains.tenant Router.group({ domain: ":tenant.app.com" }, () => { Router.get("/", DashboardController, "index"); }); ``` ```typescript fragment // app/controllers/DashboardController.ts class DashboardController { index(ctx: HttpContext) { ctx.subdomains; // { tenant: 'acme' } for acme.app.com ctx.subdomain("tenant"); // 'acme' (or null) } } ``` Routes that share a path across different hosts are dispatched by host at request time. > **Warning** — Register specific domains before wildcards — the first matching > host wins, just like route ordering. A domain-only path returns `404` for a > host that doesn't match and has no plain (domain-less) fallback. `domain` > composes with `prefix` and `middleware` in the same group. #### With multi-tenancy `@zerotal/tenancy`'s `SubdomainResolver` resolves the tenant _model_ from the same subdomain a domain group captures, so the two compose directly: ```typescript fragment // routes/index.ts Router.group({ domain: ":tenant.app.com" }, () => { Router.get("/dashboard", DashboardController, "index"); // ctx.subdomains.tenant === the resolved tenant slug; TenantContext holds the model }); ``` Configuring the resolver is covered in [Multi-tenancy](/docs/tenancy). ## Named routes Assign a name and generate URLs from it: ```typescript fragment // routes/index.ts Router.get("/posts/:slug", PostController, "show").name("posts.show"); // Generate the URL with route() route("posts.show", { slug: "hello-world" }); // → '/posts/hello-world' route("search", {}, { q: "zerotal", page: 2 }); // → '/search?q=zerotal&page=2' ``` `route(name, params, query)` takes three arguments, and each one means one thing: params fill `:segments`, query values become the query string. A key in `params` that matches no segment is an error, not a query param. Naming is what lets a path change without a sweep through templates: the URL lives in one place and every link asks for it by name. A dotted convention — `posts.show`, `admin.users.edit` — keeps names sorted and readable as the table grows, and mirrors the grouping the routes already sit in. > **Warning** — `route()` throws if the route name is unknown, a required param > is missing, or a param matches no `:segment`. Throwing rather than returning a broken string is deliberate: a typo surfaces the first time the code runs instead of shipping a link to a 404. Run [`bun zt route:list`](#the-routelist-command) to see every registered name. A catch-all route (`/docs/*`, or `[...slug].ts` under file-based routing) reaches the router as `*` — the segment's name is gone by then — so its value is passed under the `"*"` key, as a path or as segments: ```typescript route("docs.show", { "*": "guides/intro" }); // → '/docs/guides/intro' route("docs.show", { "*": ["guides", "intro"] }); // → '/docs/guides/intro' ``` ### Typed route names Run `bun zt route:types` and the names above stop being strings the compiler has to take on faith: ```typescript fragment route("psots.show", { slug }); // ✗ not assignable to RouteName route("posts.show"); // ✗ Expected 2 arguments, but got 1 route("posts.show", {}); // ✗ Property 'slug' is missing route("posts.show", { slugg: "x" }); // ✗ Did you mean to write 'slug'? ``` The command boots the app, reads the routes it registered, and writes `types/routes.generated.ts` — a name → pattern map plus a one-line augmentation that `route()` reads: ```typescript export const ROUTES = { home: "/", "posts.show": "/posts/:slug", } as const; ``` It boots rather than scanning the routes directory because a route name comes from three places and only one of them is a file path: the file-router's convention, a route file's `export const meta = { GET: { name } }`, and programmatic registrations — including those a package's provider makes. A scanner would see the first and quietly miss the other two. Params are derived from the pattern, so adding a segment changes one string and every call site updates with it. **Commit the generated file.** `zt dev` rewrites it on every restart, so it stays current while you work, but editors and CI need it without booting the app. In CI: ```bash bun zt route:types --check # fails when the file no longer matches the routes ``` Until you run the command, the registry is empty and `route()` behaves exactly as it always did — every name accepted, nothing checked. **When the name is not known at compile time** — read from config, chosen by a package — use the escape hatch, which does the same work with no checking: ```typescript fragment route.dynamic(config("app.home_route"), { id }); ``` It is a separate function rather than an overload on `route()` for a reason: an overload that accepts every string is matched by every string, and would make the checked signature above decorative. Typed names flow through the helpers built on `route()` too — `redirect().to()`, `Url.route()`, `Uri.route()`, and Flow's `redirectRoute()`. The types that checking is built from are exported from `zerotal/routes`, for when you write a helper that forwards to `route()` rather than calling it directly: | Type | What it holds | | ------------------ | ----------------------------------------------------------------------------------------------------------------- | | `RouteTarget` | The name a checked helper accepts: `RouteName` once the registry is generated, plain `string` before it. | | `RouteArgs` | Everything `route()` takes after the name — params required only when the pattern has one, query always optional. | | `RouteParamValues` | The loose param bag the unchecked overload accepts. | | `RouteQuery` | Query values. `null` and `undefined` entries drop out, and an array repeats the key. | ### route() in the browser `route()` works on the server with no setup: the application installs the table during boot, from the routes it just registered. That covers every URL your server renders — a `view` build's `href` attributes and form actions included. A browser bundle is a different process with no router to read, so there it needs the table handed to it once, at your entry point: ```typescript fragment // resources/js/app.js import { defineRoutes } from "zerotal/routes"; import { ROUTES } from "../../types/routes.generated"; defineRoutes(ROUTES); ``` From there the call is the one you already know: ```typescript fragment route("posts.show", { slug }); // → '/posts/hello' route("posts.index", {}, { page: 2 }); // → '/posts?page=2' ``` Same names, same params, same errors. Both helpers are typed as one `RouteBuilder` interface and share one URL builder, so a link rendered on the server and the same call made in a component cannot disagree about encoding — and because `types/routes.generated.ts` augments the one registry, a name that type-checks in a controller type-checks in a component. ### route() needs no import `defineRoutes()` also puts `route()` on `globalThis`, so a page, a component or a controller calls it with nothing at the top of the file: ```tsx fragment // no import line {post.title} ``` It is installed from `defineRoutes()` because that is the one function both processes already call — the server during boot, a browser entry beside its generated `ROUTES` — which means neither has to remember a second setup step. The table is installed before the global, so `route()` never exists in a state where calling it reports a missing table. The global is typed by an ambient declaration in `@zerotal/core/routes`, as the same `RouteBuilder` the named export is: an unknown route name or a missing `:param` still fails the build. > **Note** — `route` remains a named export. Importing it explicitly keeps > working, and is worth doing in a library that cannot assume an application has > booted. `defineRoutes()` takes the generated `ROUTES` object or any `RouteTable` (a name → pattern map). Calling it again replaces the table, which is what makes hot reload work — and what lets a browser entry install its own copy without disturbing the server's. `resetRoutes()` clears it again, for tests that assert on the unconfigured error. If your app renders through SSR, call `defineRoutes()` in the SSR entry too — the page components run in both processes. For a link that only exists when some package is installed, ask first rather than catching a throw: ```typescript import { hasRoute, route } from "zerotal/routes"; {hasRoute("admin.index") && Admin} ``` **In Flow**, the table arrives on its own. Flow's client runtime is built by the framework rather than by your app, so it cannot import your generated file; Flow serves the table as a small script of its own, loaded just before the runtime, and exposes the helper to Alpine expressions as `$route`: ```html Read ``` Nothing to install, and the names are the same ones the server rendered with. ### Submitting to a route with action() `route()` gives you a URL. A form needs two things — where to send the request and how — and a URL alone leaves the second one to be typed out beside it: ```typescript fragment // The URL is generated; the verb is a guess that happens to be right today. form.post(route("posts.comments.store", { post: id })); ``` `bun zt route:types` also writes a `METHODS` table, so the verb can come from the same place the URL does. `action()` returns both: ```typescript fragment // resources/js/app.js import { defineRouteMethods, defineRoutes } from "zerotal/routes"; import { METHODS, ROUTES } from "../../types/routes.generated"; defineRoutes(ROUTES); defineRouteMethods(METHODS); ``` ```typescript fragment import { action } from "zerotal/routes"; const endpoint = action("posts.comments.store", { post: id }); // → { url: '/posts/42/comments', method: 'POST' } form.submit(endpoint.method.toLowerCase(), endpoint.url); ``` `action()` takes the same names and params as `route()` and reports the same compile errors, so switching a call over costs nothing. What it buys is that a route which changes verb changes every submission with it — the failure it prevents is a 405 on submit, which looks nothing like its cause when the URL in front of you is plainly correct. Two tables rather than one map of `{ url, method }` objects, for two reasons: it leaves `ROUTES` alone, so a generated file from an earlier version still works; and a bundle that only renders links never pulls the verbs in. `defineRouteMethods()` is optional. Without it `action()` still resolves the URL and reports `GET`, which is the right answer for a link-only bundle and a better one than throwing. ## File-based routing Map a directory tree to routes: each file under the routes directory becomes an endpoint, with `_middleware.ts` for shared middleware. Opt in with `app.fileBasedRouting()` in `bootstrap/app.ts`, passing a map of named route groups (each `web`/`api` group brings its own default prefix and middleware) to directories: ```typescript fragment // bootstrap/app.ts import { Application, basePath } from "zerotal"; import providers from "./providers"; const app = Application.create({ providers }).fileBasedRouting({ web: basePath("app/routes"), }); ``` The scanner walks the directory and converts file paths to URL paths automatically. ### File → URL mapping | File path | URL | | ----------------------------- | --------------------------- | | `index.ts` | `/` | | `about.ts` | `/about` | | `users/index.ts` | `/users` | | `users/[id].ts` | `/users/:id` | | `(admin)/users/index.ts` | `/users` | | `api/users/[id]/posts.ts` | `/api/users/:id/posts` | | `blog/[...slug].ts` | `/blog/*` | | `.well-known/security.txt.ts` | `/.well-known/security.txt` | Rules in order: `(group)` directory segments are stripped (no URL contribution); `[...slug]` becomes `*` (catch-all); `[param]` becomes `:param` (dynamic segment); `index` becomes the directory URL. Dot-directories are routed like any other, so `.well-known/` can serve `security.txt`, `mta-sts.txt`, app links and OpenID discovery. Files whose names start with `_` or `.`, tests and declaration files are never routes. ### Handler exports A file may export handlers for one or more HTTP verbs: ```typescript fragment // app/routes/users/[id].ts import type { HttpContext } from "zerotal"; export async function GET(ctx: HttpContext): Promise { const user = await User.findOrFail(Number(ctx.params.id)); ctx.json(user); } export async function DELETE(ctx: HttpContext): Promise { const user = await User.findOrFail(Number(ctx.params.id)); await user.delete(); ctx.response = new Response(null, { status: 204 }); } ``` `export default` is a GET alias when no explicit `GET` export exists: ```typescript // app/routes/api/v2/status.ts import type { HttpContext } from "zerotal"; export default async function (ctx: HttpContext): Promise { ctx.json({ status: "ok", uptime: Math.floor(process.uptime()) }); } ``` ### Auto-generated route names File routes are automatically named following the RESTful convention: | URL | Method | Auto-name | | ---------------- | -------- | ------------------- | | `/` | `GET` | `home` | | `/about` | `GET` | `about` | | `/about` | `POST` | `about.store` | | `/api/users` | `GET` | `api.users.index` | | `/api/users` | `POST` | `api.users.store` | | `/api/users/:id` | `GET` | `api.users.show` | | `/api/users/:id` | `PUT` | `api.users.update` | | `/api/users/:id` | `DELETE` | `api.users.destroy` | Override with the `meta` export: ```typescript // app/routes/api/v2/posts/[id].ts export const meta = { GET: { name: "api.v2.posts.show" }, DELETE: { name: "api.v2.posts.destroy" }, }; ``` **A name that two paths share names neither.** The generated name leaves out `[param]` segments, so `applications/act.ts` and `applications/[id]/act.ts` both come out as `applications.act.store`, and an explicit name can repeat one by accident. Such a name is left out of the named routes and the generated route types, `route()` on it throws an error naming both paths, and `bun zt route:list` lists it under the table. Give one of the routes its own name in `meta`. Both routes still answer requests; only the name is withheld. ### Directory middleware Place a `_middleware.ts` file in any directory to protect all routes under it. The scanner walks from the root down to the file's directory and stacks middleware outermost-first: ```typescript fragment // app/routes/api/v2/me/_middleware.ts import { RequireAuthMiddleware } from "../../../middleware/RequireAuthMiddleware.ts"; export const middleware = [RequireAuthMiddleware]; ``` For `app/routes/api/v2/me/posts.ts` the stack would be: 1. `app/routes/_middleware.ts` (if present) 2. `app/routes/api/_middleware.ts` (if present) 3. `app/routes/api/v2/_middleware.ts` (if present) 4. `app/routes/api/v2/me/_middleware.ts` ← adds `RequireAuthMiddleware` The route group's own middleware (the `web` group's, or the `middleware` of an entry passed to `fileBasedRouting()`) runs once, ahead of this stack, and the file's own `export const middleware` runs after it. #### Route groups in file trees Use `(group)` directory names to apply shared `_middleware.ts` without affecting URLs: ```text app/flow/pages/ (auth)/ ← GuestMiddleware login.tsx → /login register.tsx → /register (protected)/ ← AuthMiddleware dashboard.tsx → /dashboard profile.tsx → /profile index.tsx → / ``` ### Flow component files When `@zerotal/flow` is installed, the file scanner recognises Flow `Component` class exports and registers them automatically without any extra configuration. Verb handlers (`POST`, `DELETE`, etc.) in the same file still register normally alongside the page: ```typescript fragment // app/flow/pages/(protected)/dashboard.tsx import type { HttpContext } from "zerotal"; export default class DashboardPage extends Component { /* ... */ } // Optional: form handler lives in the same file export async function POST(ctx: HttpContext): Promise { /* ... */ } ``` ## Route-model binding Resolve a route parameter straight to a model instance before the controller runs, with an automatic 404 when the record is missing. ### Implicit binding Because every model under `app/models/` is [auto-registered](/docs/conventions#models-appmodels), binding is automatic: a route param whose name matches a model resolves to a loaded instance with no configuration. `:user` resolves via `User`, `:post` via `Post`, `:blogPost` via `BlogPost` (and a plural `:users` resolves to `User` too, via singularization). ```typescript fragment // routes/index.ts — nothing to declare: Router.get("/users/:user", UserController, "show"); // app/controllers/UserController.ts — :user is already a loaded User // (or a 404 was thrown first): async show(ctx: HttpContext<{ user: User }>) { return ctx.json({ user: ctx.params.user }); } ``` Resolution uses `Model.findOrFail(value)` on the primary key; a missing record throws `ModelNotFoundError` (404) before the controller runs. Implicit binding only fires for params whose name maps to a model — `:id`, `:slug`, `:page`, and other non-model params stay raw strings. #### The model owns its lookup A model that resolves by something other than its primary key says so once, on the model, rather than at every route that mentions it. Declare `static resolveRouteBinding` and it is used wherever that model binds: ```typescript fragment // app/models/User.ts @table("users") export class User extends Model { static override async resolveRouteBinding(value: string, ctx: HttpContext, param: string) { // One model can answer for several segments — branch on the param, not the URL. if (param === "username") return this.where("username", value).firstOrFail(); return this.findOrFail(value); } } ``` It receives the matched value, the request context, and the **name of the segment** that matched. Branching on `param` is what lets `/users/:user` and `/users/:username/posts` resolve differently without the model knowing any route's shape; `ctx` is there for lookups that depend on the request, such as scoping to the current tenant. Because it is a static, a subclass inherits it, and everything that binds a model — controllers, [Flow pages](/docs/flow/routing), file routes — goes through it. Return anything you like; throwing `ModelNotFoundError` (as `firstOrFail`/`findOrFail` do) is what produces the 404. ### When bindings resolve Bindings resolve **after every middleware on the route, immediately before the controller**. That ordering is a guarantee, not an implementation detail: - A middleware that short-circuits — an auth guard returning 401, a tenant scope returning 403 — does so **before any binding query runs**. A protected route therefore answers the same way whether or not the record exists, rather than leaking that difference as 404-vs-401 to an unauthenticated caller. - Middleware runs with the raw string still on `ctx.params`. If a middleware needs the record itself, load it there — it cannot rely on the binding. - A `ModelNotFoundError` unwinds back out through the middleware, so their `finally` blocks (session persistence, for example) still run. #### Opting out and customising Two static properties on the model control implicit binding: ```typescript fragment // app/models/User.ts @table("users") export class User extends Model { // Never bind this model implicitly (the :user param stays a raw string): static implicitBinding = false; // Or claim a different param name than the class name: static implicitBindingKey = "author"; // now :author resolves via User, and :user does not } ``` `implicitBindingKey` **replaces** the name convention — a model that claims `:author` no longer answers to `:user`. > **Tip** — Need to resolve by something other than the primary key (e.g. a > slug)? Prefer [`static resolveRouteBinding`](#the-model-owns-its-lookup) — it > applies everywhere the model binds. Reach for an explicit > [per-route binding](#per-route-binding) when the override belongs to one route > rather than to the model; explicit bindings always win over implicit ones. ### Explicit binding There are exactly two ways to change how a param resolves, and they differ only in scope: put it on the **model** when it is how that model always resolves, or on the **route** when it belongs to that one route. ```typescript fragment // in a controller — either way, it is already resolved async show(ctx: HttpContext) { const user = ctx.model('user'); // no DB call needed here return ctx.json({ user }); } ``` If the record is not found, a `ModelNotFoundError` (404) is thrown before the controller runs. #### Per-route binding Overrides the model's own resolution for a single route: ```typescript fragment // routes/index.ts Router.get("/posts/:post", PostController, "show").name("posts.show").bind("post", Post); // Custom per-route resolver Router.get("/articles/:article", ArticleController, "show").bind("article", (value) => Article.where("slug", value).firstOrFail(), ); ``` #### Receiving bindings in controllers The resolved instance is available two ways — via `ctx.model()`, or on `ctx.params` under the param's name: ```typescript fragment // in a controller — via ctx.model() async show(ctx: HttpContext) { const post = ctx.model('post'); ctx.json(post); } // via ctx.params async show(ctx: HttpContext<{ post: Post }>) { ctx.json(ctx.params.post); } // mixed — model + raw route param async comments(ctx: HttpContext<{ post: Post; tab: string }>) { const { post, tab } = ctx.params; ctx.json({ post, tab, comments: await post.comments().all() }); } ``` `ctx.params` is one part of the request context every handler receives — reading input, sending responses, headers, flash, and after-response hooks all live on the same object. See [HttpContext](/docs/context) for that surface. ## Route registration order 1. `app.fileBasedRouting()` directories are scanned and registered during boot. 2. Explicit route files run and register their routes. 3. `Router.raw()` routes are compiled last and take precedence over same-path pipeline routes. Within explicit routes, last registration wins for duplicate `METHOD + path` keys — registering the same path twice overwrites the first. For resource routes, register literal paths **before** dynamic ones when there is a naming conflict: ```typescript fragment // routes/index.ts // Correct — /posts/create is matched before /posts/:slug Router.get("/posts/create", PostController, "showCreate"); Router.get("/posts/:slug", PostController, "show"); ``` ## Route inspection ### The route:list command Print a table of all registered routes: ```bash # in your project root bun zt route:list # Filter by method bun zt route:list --method GET bun zt route:list -m DELETE # Filter by path substring bun zt route:list --path /api bun zt route:list -p /users # Show only named routes bun zt route:list --name # Include middleware column bun zt route:list --verbose bun zt route:list -v ``` ### The route:types command Write the generated name → pattern map that makes [`route()` typed](#typed-route-names): ```bash # writes types/routes.generated.ts — commit it bun zt route:types # CI: fail when the committed file no longer matches the routes bun zt route:types --check ``` Both forms boot the app, so a route a provider registers is included. ### Programmatic inspection ```typescript fragment // anywhere after boot Router.routes; // ReadonlyMap Router.namedRoutes; // ReadonlyMap (name → path) // Middleware attached to a specific route Router.middlewareFor("GET", "/dashboard"); // MiddlewareClass[] ``` ## Testing Use `HttpContext.fake()` to unit-test controllers and route handlers without a running server: ```typescript fragment // src/tests/PostController.test.ts import { HttpContext } from "zerotal"; const ctx = HttpContext.fake("http://localhost/posts/42", { method: "GET" }); ctx.params = { id: "42" }; await new PostController().show(ctx); // assert ctx.response ``` For full integration tests, boot the real app with `createTestApp()` from `@zerotal/testing` and exercise it over real requests: ```typescript fragment // src/tests/PostTest.ts import { beforeAll, afterAll, it } from "bun:test"; import { createTestApp, type TestApp } from "@zerotal/testing"; import { app } from "../bootstrap/app.ts"; let testApp: TestApp; beforeAll(async () => (testApp = await createTestApp(() => app))); afterAll(() => testApp.close()); it("returns the post", async () => { const post = await Post.create({ title: "Hello" }); const res = await testApp.get(`/posts/${post.id}`); res.assertStatus(200); res.assertJson({ title: "Hello" }); }); ``` See [HTTP Tests](/docs/testing/http) for the full client and assertion surface. ## References ### Router methods | Method | Signature | Description | | -------------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `Router.get` / `post` / `put` / `patch` / `delete` | `(path, Controller, action, mw?)` or `(path, handler, mw?)` | Register a route for an HTTP verb (controller action or closure handler). Returns a `RouteRegistration`. | | `Router.resource` | `(name, Controller, mw?): ResourceRouteBuilder` | Register the seven RESTful routes; chain `.only()` / `.except()`. | | `Router.view` | `(path, Component, props?, mw?): ViewRegistration` | Render a JSX view with no controller. | | `Router.static` | `(prefix, dir, options?)` | Serve a directory of static files. | | `Router.markdown` | `(prefix, dir, options?)` | Serve `.md` files as rendered HTML. | | `Router.raw` | `(method, path, handler)` | Handle the raw `Request`, bypassing the middleware pipeline. | | `Router.flow` | `(path, Page, mw?)` | Register a Flow page (added by `@zerotal/flow`). | | `Router.group` | `(options, fn)` | Share a `prefix`, `middleware`, and/or `domain` across routes. | | `Router.middlewareGroup` | `(name, [...])` | Define a reusable, named middleware stack. | ### Registration chaining Every route registration returns a chainable handle: | Chain | Signature | Effect | | --------------------------------- | --------------------------------------------- | ---------------------------------------------------------- | | `.name(name)` | `(name): RouteRegistration` | Name the route for `route()` URL generation. | | `.bind(param, target)` | `(param, modelOrResolver): RouteRegistration` | Per-route model binding; overrides the global one. | | `.maxBodySize(bytes)` | `(bytes): RouteRegistration` | Per-route request body limit; see Request body size. | | `.withLayout(layout)` | `(layout): ViewRegistration` | Wrap a view route's output in a layout (view routes only). | | `.only([...])` / `.except([...])` | `(actions): this` | Limit which resource actions are registered. | ### URLs, inspection and CLI | API | Signature | Description | | -------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- | | `route(name, params?, query?)` | `(name, params?, query?): string` | Build a URL from a named route. Params are exact; query values go last. | | `route.dynamic(name, params?, query?)` | `(name, params?, query?): string` | The same, for a name only known at runtime — no compile-time checking. | | `Router.routes` / `Router.namedRoutes` | `ReadonlyMap` | Read the registered route and name maps. | | `Router.middlewareFor(method, path)` | `(method, path): MiddlewareClass[]` | List the middleware attached to a route. | | `HttpContext.fake(url?, init?)` | `(url?, init?): HttpContext` | Build a fake context for unit tests. | | `bun zt route:list` | — | Print every route (`-m` method, `-p` path, `--name`, `-v` middleware). | | `bun zt route:types` | `--check` | Write `types/routes.generated.ts`; `--check` fails when it is stale. | ## Types | Type | What it is | | -------------------- | --------------------------------------------------------------------------------------------------------- | | `HttpMethod` | The verbs a route can answer on. | | `HttpResponse` | What a handler may return when it does not write to `ctx.response`. | | `ControllerResponse` | A controller action's return type — `void`, a `ResponseBuilder`, or a `MarkdownBuilder`. | | `RouteParams` | The params a pattern captures, as a record. | | `ParamsOf

` | The params of one pattern, derived from the pattern string — what makes `route()` refuse a missing `:id`. | | `RouteRegistry` | The generated name → pattern table, augmented by `types/routes.generated.ts`. | | `RouteMiddleware` | What a route's middleware list accepts — a class, an array, or the method map. | | `GroupOptions` | `Router.group({ prefix, middleware, domain })`. | | `RoutingConfig` | The `routing` config namespace. | | `FileRoutingConfig` | File-router settings within it. | | `WebSocketHandlers` | The handler set a WebSocket route registers. | ## Next steps - [Controllers](/docs/controllers) — move route logic out of closures. - [Middleware](/docs/middleware) — protect and transform requests. - [HttpContext](/docs/context) — the request/response object actions receive. - [Multi-tenancy](/docs/tenancy) — resolve a tenant from the subdomain a group scopes to. - [HTTP Tests](/docs/testing/http) — boot the real app and assert over requests. --- Source: https://zerotal.dev/docs/middleware # Middleware Middleware sits in the HTTP pipeline between the server and your controller. Each piece of middleware receives the request context, can inspect or modify it, then either passes control to the next layer or short-circuits with a response. Middleware ships in `@zerotal/core`, so there is nothing to install or register — import the types and write a class. ## Getting Started The middleware pipeline is built into `@zerotal/core` — nothing to install: ```typescript import type { HttpContext, NextFn } from "zerotal"; ``` ## Writing middleware Implement the `Pipe` interface — a single `handle` method that receives the request `HttpContext` directly and reaches the request/response helpers on it. A middleware does exactly one of three things: **continue** by returning `next()`, **short-circuit** by returning a `Response`, or **wrap** by awaiting `next()` (which resolves to the downstream `Response`) and returning a transformed one. `next()` takes no arguments: ```ts // app/middleware/LogRequestMiddleware.ts import type { Pipe, NextFn, HttpContext } from "zerotal"; export class LogRequestMiddleware implements Pipe { async handle(ctx: HttpContext, next: NextFn): Promise { console.log(`→ ${ctx.request.method} ${ctx.path()}`); const response = await next(); // ← inner middleware + controller run here console.log(`← ${response?.status} (${ctx.took}ms)`); return response; } } ``` The `Pipe` and `NextFn` types come straight from the package: ```ts // the signatures, for reference interface Pipe { handle(payload: T, next: NextFn): Promise; } type NextFn = () => Promise; ``` ### Short-circuiting Return a `Response` without calling `next` to stop the pipeline: ```ts // app/middleware/MaintenanceMiddleware.ts import type { Pipe, NextFn, HttpContext } from "zerotal"; export class MaintenanceMiddleware implements Pipe { async handle(ctx: HttpContext, next: NextFn): Promise { if (Bun.env.MAINTENANCE_MODE === "true") { return new Response("Down for maintenance", { status: 503 }); // ← does NOT call next } return next(); } } ``` > **Note** — You can also set `ctx.response` and `return` (void) instead of returning the `Response` > directly — both are equivalent. `ctx.response` is the canonical store; a `void` return > leaves whatever it holds untouched, so it can never erase a response a deeper pipe set. ### Wrapping Code after `await next()` runs on the way out — after the controller has responded. `next()` resolves to the downstream `Response` (or `undefined` if none was produced). Use this for saving session data or appending headers. Because some responses (e.g. `Response.redirect()`) have immutable headers, reconstruct rather than mutate — the `withHeaders` helper does this: ```ts // app/middleware/TimingHeaderMiddleware.ts import type { Pipe, NextFn, HttpContext } from "zerotal"; import { withHeaders } from "zerotal"; export class TimingHeaderMiddleware implements Pipe { async handle(ctx: HttpContext, next: NextFn): Promise { const response = await next(); if (!response) return; return withHeaders(response, { "Server-Timing": `total;dur=${ctx.took}` }); } } ``` ## Attaching middleware to routes There are five ways to attach middleware. Reach for the one that matches the scope you want: - **Per-route** — one specific route needs the middleware. - **Route groups** — a handful of related routes share it. - **Named groups** — the same stack (`web`, `api`) is reused across many groups. - **File-based** (`_middleware.ts`) — every route file under a directory inherits it. - **Auto-discovered** — a class in `app/middleware/` referenced by its name as a string. For middleware that must run on _every_ request, see [Global middleware](#global-middleware). ### Per-route Pass an array of middleware classes as the fourth argument to any route registration method: ```ts fragment // routes/index.ts Router.get("/dashboard", DashboardController, "index", [AuthMiddleware]); Router.post("/posts", PostController, "store", [AuthMiddleware, ThrottleMiddleware]); ``` ### Route groups ```ts fragment // routes/index.ts Router.group({ middleware: AuthMiddleware }, () => { Router.get("/dashboard", DashboardController, "index"); Router.resource("posts", PostController); }); ``` ### Auto-discovered middleware Middleware classes under `app/middleware/` are auto-registered at boot as a **named group under their class name** — reference them by string in routes without importing: ```ts fragment // app/middleware/EnsureSubscribed.ts → referenceable as "EnsureSubscribed" Router.group({ middleware: ["EnsureSubscribed"] }, () => { /* … */ }); ``` They are **not** global by default; set `static global = true` on the class to add it to the global pipeline. See [Conventions](/docs/conventions#middleware-appmiddleware). ### Named middleware groups Define a group once, reference it by name everywhere: ```ts fragment // in a ServiceProvider.onRegister() Router.middlewareGroup("api", [ThrottleMiddleware, BearerTokenMiddleware]); Router.middlewareGroup("web", [SessionMiddleware, CsrfMiddleware]); ``` ```ts fragment // routes/index.ts Router.group({ prefix: "/api/v1", middleware: "api" }, () => { Router.resource("posts", PostController); }); Router.group({ middleware: ["web", AuthMiddleware] }, () => { Router.get("/dashboard", DashboardController, "index"); }); ``` ### File-based route middleware Drop a `_middleware.ts` file into any directory under your file routes folder. It applies to every route file in that directory and all subdirectories: ```ts fragment // app/routes/admin/_middleware.ts import { AuthMiddleware } from "@zerotal/auth"; import { AdminMiddleware } from "../../middleware/AdminMiddleware.ts"; export const middleware = [AuthMiddleware, AdminMiddleware]; ``` Middleware stacks from outer directories are prepended automatically — you get `root/_middleware → admin/_middleware → route handler` in one pipeline. > **It is `export const middleware`, an array — not `export default`.** Route > files in the same directory default-export their handler, so a default export is > the natural guess here and it is the wrong one. The app refuses to boot and tells > you which file, rather than serving the subtree unguarded and looking exactly > like a guarded one. The same applies to a `_middleware.ts` that > fails to import: a typo or a bad import path is a boot error, not a subtree that > quietly loses its guard. A directory with no `_middleware` file at all is the > convention working, and stays silent. > > Note the asymmetry with its sibling: a `_layout` file is read by its **default** > export, a `_middleware` file by a **named** one. Both now refuse to boot on the > other's spelling rather than applying nothing. ## Global middleware Register middleware that runs on every request in `bootstrap/app.ts`: ```ts fragment // bootstrap/app.ts export default Application.create({ providers }).use([ DevtoolsInjectionMiddleware, RequestIdMiddleware, ]); ``` Framework providers auto-register their own middleware (e.g. `SessionMiddleware` from `@zerotal/session`, `AuthMiddleware` from `@zerotal/auth`) — you do not need to add them manually. ## Built-in middleware The package ships several middleware you can drop straight into `app.use([...])` or a route's middleware array. Each extends `BaseMiddleware`, so `.with({ … })` bakes options into a zero-argument class. ### Names the framework already occupies Middleware live in a flat namespace: your `app/middleware/` classes are discovered by class name, and so are the ones a package exports. Naming one of yours after one of these is not caught as a conflict — it surfaces later as a type error somewhere that does not mention either file, which is a confusing way to learn that `TwoFactorMiddleware` was taken. The full list, so you can check before you name: | Middleware | Package | | -------------------------------------------------------------------------------------- | -------------------------------- | | `CorsMiddleware`, `SecureHeadersMiddleware`, `ThrottleMiddleware`, `WebhookMiddleware` | `@zerotal/core` | | `AuthMiddleware`, `GuestMiddleware`, `PersistUserMiddleware`, `RememberMeMiddleware` | `@zerotal/auth` | | `BasicAuthMiddleware`, `BearerTokenMiddleware`, `JwtGuardMiddleware` | `@zerotal/auth` | | `RequireRoleMiddleware`, `RequirePermissionMiddleware`, `TwoFactorMiddleware` | `@zerotal/auth` | | `ValidateSignatureMiddleware` | `@zerotal/auth` | | `SessionMiddleware`, `CsrfMiddleware`, `AuthSessionMiddleware` | `@zerotal/session` | | `InertiaMiddleware`, `PrecognitionMiddleware` | `@zerotal/inertia` | | `AdminGuardMiddleware`, `AdminAbilityMiddleware` | `@zerotal/admin` | | `MonitorAuthMiddleware`, `MonitorPayloadMiddleware` | `@zerotal/monitor` | | `IdempotencyMiddleware` | `@zerotal/cache` | | `LocaleMiddleware` | `@zerotal/i18n` | | `EnsureTenancyMiddleware` | `@zerotal/tenancy` | | `TelemetryMiddleware` | `@zerotal/telemetry` | | `BaseMiddleware` | `@zerotal/core` (the base class) | If yours does something different from the framework's, say so in the name rather than shadowing it — `RequireTwoFactorMiddleware` for "fence the console until staff have enrolled" reads better than `TwoFactorMiddleware` anyway, and cannot collide. ### CorsMiddleware ```ts fragment // bootstrap/app.ts import { CorsMiddleware } from "zerotal"; // Permissive (default — allow any origin) app.use([CorsMiddleware]); // Restrict to one origin app.use([CorsMiddleware.with({ origin: "https://app.example.com", credentials: true })]); // Dynamic origin check app.use([CorsMiddleware.with({ origin: (o) => o.endsWith(".mycompany.com") })]); ``` | Option | Default | Description | | ---------------- | -------------- | ------------------------------------------------------------ | | `origin` | `'*'` | Allowed origins — string, string[], or `(origin) => boolean` | | `methods` | all verbs | Allowed HTTP methods | | `allowedHeaders` | common headers | Allowed request headers | | `exposedHeaders` | `[]` | Headers JS may read from the response | | `credentials` | `false` | Allow cookies / auth in cross-origin requests | | `maxAge` | `600` | Preflight cache duration (seconds) | > **Danger** — Setting `origin: '*'` together with `credentials: true` is rejected by browsers > and leaks cross-origin responses. Name an explicit origin (or use the function form) whenever > you allow credentials. ### ThrottleMiddleware Rate-limits requests with an in-memory sliding window counter. Returns `429` with `Retry-After` and `X-RateLimit-*` headers when the limit is exceeded. ```ts fragment // bootstrap/app.ts (global) and routes/index.ts (per-route) import { ThrottleMiddleware } from "zerotal"; // Global: 120 requests / minute app.use([ThrottleMiddleware.with({ maxAttempts: 120, windowSeconds: 60 })]); // Per-route: 5 login attempts / minute Router.post("/login", AuthController, "login", [ ThrottleMiddleware.with({ maxAttempts: 5, windowSeconds: 60 }), ]); // By authenticated user ID instead of IP ThrottleMiddleware.with({ maxAttempts: 1000, windowSeconds: 3600, keyResolver: (ctx) => String(ctx.user?.id ?? ctx.ip()), }); ``` | Option | Default | Description | | ---------------- | ----------- | ------------------------------------- | | `maxAttempts` | (required) | Max requests in the window | | `windowSeconds` | `60` | Window length in seconds | | `keyResolver` | IP address | Function returning the rate-limit key | | `trustedProxies` | `undefined` | Number of trusted upstream proxies | ### RateLimiter — named limiters For limits reused across routes (and queryable/resettable at runtime), define a **named limiter** once at boot (e.g. in a `ServiceProvider`), then apply it by name. ```ts // in a ServiceProvider (boot time) import { RateLimiter } from "zerotal"; // 1000 req/hour per authenticated user (falls back to IP when unauthenticated) RateLimiter.for("api").limit(1000).every(3600).byUser().register(); // 5 login attempts per minute, per IP RateLimiter.for("login").limit(5).every(60).byIp().register(); // 500 req/min keyed by an API-key header (unknown key -> per IP) RateLimiter.for("partner").limit(500).every(60).byApiKey("x-api-key").register(); // Custom key RateLimiter.for("upload") .limit(10) .every(3600) .by((ctx) => `user:${ctx.user?.id ?? "anon"}`) .register(); ``` Apply as route middleware with `RateLimiter.middleware(name)`: ```ts fragment // routes/index.ts Router.post("/login", AuthController, "login", [RateLimiter.middleware("login")]); Router.group({ prefix: "/api", middleware: [RateLimiter.middleware("api")] }, () => { Router.get("/users", UserController, "index"); }); ``` | Method | Keys on | Falls back to | | -------------------- | ----------------------------------------------------------------- | ------------------------ | | `.byUser()` | `ctx.user.id` | IP when unauthenticated | | `.byApiKey(header?)` | `x-api-key` header (or custom) | IP when header is absent | | `.byIp()` | Socket IP, or `X-Forwarded-For` from the right (`trustedProxies`) | `'unknown'` | | `.by(fn)` | Return value of your function | - | Check or reset a limiter manually — e.g. clear failed login attempts after a successful sign-in: ```ts fragment // in a controller action — `ctx` is the HttpContext the action receives if (await RateLimiter.tooManyAttempts("login", ctx)) { return ctx.json({ message: "Too Many Requests" }, 429); } RateLimiter.resetFor("login", ctx); // clear the counter for this actor ``` > **Tip** — `ThrottleMiddleware.with({ … })` is inline and per-attachment; a named `RateLimiter` > is defined once and can be reused, queried with `tooManyAttempts()`, and cleared with > `resetFor()`. Use the inline form for one-off routes, the named form when the same limit > appears in several places. See [Rate limiting](/docs/rate-limiting) for the full surface. ### SecureHeadersMiddleware Adds `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy` and `Permissions-Policy` to every response, and a `Content-Security-Policy` when you set `contentSecurityPolicy` (Flow's guide has a [recommended policy](/docs/flow/components#recommended-csp-header)): ```ts fragment // bootstrap/app.ts import { SecureHeadersMiddleware } from "zerotal"; app.use([SecureHeadersMiddleware]); ``` It is registered for you as kernel middleware, so an app gets these headers without asking. Configure them under `app.secureHeaders` in `config/app.ts` — see [Configuration](/docs/config-system). **A header a route sets itself wins.** These are defaults: a response that already carries one of them keeps its own value, and the rest are still added. So a print view can send `Content-Security-Policy: sandbox allow-scripts` and a preview the app frames itself can send `frame-ancestors 'self'`, while every other page gets the global policy: ```ts fragment // app/routes/messages/[id]/print.ts export function GET() { return new Response(html, { headers: { "Content-Type": "text/html", "Content-Security-Policy": "sandbox allow-scripts" }, }); } ``` **Static files get the same headers**, even though no middleware runs for them. Files under `public/` are handed to Bun as pre-registered responses and served without entering JavaScript, so the pipeline never sees them; the header set is baked into those responses at registration time instead. A per-directory header passed to `Router.static()` still wins, so a mount that is deliberately embeddable stays that way. > **Tip** — Run [`bun zt doctor --url=…`](/docs/deployment) after deploying. A > header your app sets and your proxy also sets is invisible from inside the > process, and browsers disagree about which copy applies. ### WebhookMiddleware Verifies HMAC-SHA256 signatures on incoming webhook requests: ```ts fragment // routes/index.ts import { WebhookMiddleware } from "zerotal"; Router.post("/webhooks/stripe", StripeController, "handle", [ WebhookMiddleware.with({ secret: Bun.env.STRIPE_WEBHOOK_SECRET!, header: "stripe-signature", algorithm: "sha256", }), ]); ``` > **Danger** — Keep the webhook `secret` in an environment variable, never hard-coded. A leaked > secret lets anyone forge valid signatures and call your webhook endpoint. ## Middleware with constructor injection Decorate the class with `@inject(...)`, listing its dependency tokens in constructor order; the container resolves them and passes them in: ```ts fragment // app/middleware/AuditMiddleware.ts import { inject } from "zerotal"; import type { Pipe, NextFn, HttpContext } from "zerotal"; @inject(AuditLogger) export class AuditMiddleware implements Pipe { constructor(private logger: AuditLogger) {} async handle(ctx: HttpContext, next: NextFn): Promise { const response = await next(); await this.logger.record(ctx.request.method, ctx.path(), ctx.user?.id); return response; } } ``` ## Execution order Middleware nests like layers of an onion: outer layers run first on the way in, and last on the way out (after `await next()`). ```text Kernel ← outermost: the maintenance gate, then SecureHeaders Provider middleware ← Session, Auth, Inertia, … (registered by providers) Global (app.use) ← CORS, Throttle, your own Group middleware ← Router.group({ middleware }) Route middleware ← Router.get(path, C, a, [M]) Controller action ← innermost ← route mw unwind ← group mw unwind ← global mw unwind ← provider mw unwind ← session saved here ← kernel unwind ``` So middleware you add with `app.use()` already sees the session and the signed-in user. If you register your own `SecureHeadersMiddleware` (configured with `.with()`, or a subclass), it replaces the kernel's copy of the headers and runs where you registered it. The maintenance gate stays in the kernel and still runs first. ## Testing Set your suite up once as described in [Testing](/docs/testing). Middleware has two behaviours worth proving, and they are easy to confuse: what it does when it lets a request **through**, and what it does when it **stops** one. **Test the stop first**, because it is the reason the middleware exists: ```typescript fragment // tests/http/middleware.test.ts import { test } from "bun:test"; import { createApp } from "../helpers.ts"; test("a guest is turned away from a protected route", async () => { const app = await createApp(); const res = await app.get("/dashboard"); res.assertRedirect("/login"); await app.close(); }); ``` **Then prove it lets the right request through**, otherwise a middleware that rejects everything passes the first test perfectly: ```typescript fragment // tests/http/middleware.test.ts const res = await app.actingAs(user).get("/dashboard"); res.assertOk(); ``` **A middleware that transforms rather than blocks** is tested through its effect. Register a probe route in the `setup` callback — `createTestApp(bootstrap, setup)` runs it before the server starts, so the route compiles into the router: ```typescript fragment // tests/http/middleware.test.ts const app = await createApp(() => { Router.get("/probe", () => ({ locale: Context.get("locale") })).middleware([LocaleMiddleware]); }); const res = await app.get("/probe", { "Accept-Language": "fr" }); res.assertJsonPath("locale", "fr"); ``` > **Warning** — Middleware ordering is behaviour, not configuration. If auth must > run before a rate limiter (so anonymous floods are cheap) or after it (so > logins are throttled), write the test that fails when the order flips — > reordering the array is a one-line change nobody reviews closely. ## References Imported from `zerotal`. | Member | Signature | Description | | ---------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `Pipe` | `interface Pipe { handle(payload: T, next: NextFn): Promise }` | The contract every middleware implements (`T` is `HttpContext`). | | `NextFn` | `type NextFn = () => Promise` | Passes control downstream; resolves to the downstream `Response`. | | `HttpContext` | `class HttpContext` | The request context passed to `handle` — read params from `ctx.params`. | | `withHeaders` | `withHeaders(res: Response, headers: Record): Response` | Returns a copy of `res` with headers added (safe on immutable responses). | | `BaseMiddleware` | `class BaseMiddleware { static with(options: Partial): new () => … }` | Base class providing the `.with()` option-baking helper. | Built-in middleware classes (`MiddlewareClass.with(options)` where noted): | Class | Configure with | Purpose | | ------------------------- | ----------------------------- | -------------------------------------------------- | | `CorsMiddleware` | `.with(CorsOptions)` | Cross-origin resource sharing headers. | | `ThrottleMiddleware` | `.with(ThrottleOptions)` | In-memory sliding-window rate limiting. | | `SecureHeadersMiddleware` | `.with(SecureHeadersOptions)` | Security response headers (CSP, frame options, …). | | `WebhookMiddleware` | `.with(WebhookOptions)` | HMAC signature verification for webhooks. | Named rate limiters via `RateLimiter`: | Method | Signature | Description | | ---------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------- | | `RateLimiter.for` | `for(name: string): LimiterDefinition` | Start defining a named limiter. | | `RateLimiter.middleware` | `middleware(name: string): ThrottleMiddleware` | Get the middleware for a registered limiter. | | `RateLimiter.tooManyAttempts` | `tooManyAttempts(name: string, ctx: HttpContext): Promise` | Record a hit and report whether the limit is hit. | | `RateLimiter.resetFor` | `resetFor(name: string, ctx: HttpContext): void` | Clear the counter for this actor's key. | | `LimiterDefinition.limit`/`.every` | `limit(max): this` / `every(seconds): this` | Set the window size and length. | | `LimiterDefinition.byUser`/`.byIp`/`.byApiKey`/`.by` | `byUser(): this` / `byApiKey(header?): this` / `by(fn): this` | Choose the key strategy. | | `LimiterDefinition.register` | `register(): this` | Register the limiter with the global registry. | ## Next steps - [Routing](/docs/routing) — attach middleware to routes and groups. - [Lifecycle](/docs/lifecycle) — where middleware sits in the request flow. - [Controllers](/docs/controllers) — move route logic out of closures. - [Rate limiting](/docs/rate-limiting) — named limiters in depth. --- Source: https://zerotal.dev/docs/controllers # Controllers A controller groups related request handlers into a single class, where each public method is an action that a route can target. Controllers are resolved through the IoC container, so a class declaring `@inject(...)` gets its dependencies wired up automatically. ## Basic controller A controller is a plain class. Each action receives the request `HttpContext` directly, reads input from it, and sets the response by calling a helper on it — actions return `void`, not a value. ```typescript fragment // app/controllers/PostController.ts import type { HttpContext } from "zerotal"; import { Post } from "../models/Post.ts"; export class PostController { async index(ctx: HttpContext): Promise { const posts = await Post.all(); ctx.json({ posts }); } async show(ctx: HttpContext): Promise { const post = await Post.findOrFail(Number(ctx.params.id)); ctx.json(post); } async store(ctx: HttpContext): Promise { const { title, body } = await ctx.body<{ title: string; body: string }>(); const post = await Post.create({ title, body }); ctx.json(post, 201); } async destroy(ctx: HttpContext): Promise { const post = await Post.findOrFail(Number(ctx.params.id)); await post.delete(); ctx.response = new Response(null, { status: 204 }); } } ``` Map routes to actions by passing the controller class and the action name: ```typescript fragment // routes/index.ts import { Router } from "zerotal"; import { PostController } from "../app/controllers/PostController.ts"; import { AuthMiddleware } from "@zerotal/auth"; Router.get("/posts", PostController, "index"); Router.get("/posts/:id", PostController, "show"); Router.post("/posts", PostController, "store", [AuthMiddleware]); Router.delete("/posts/:id", PostController, "destroy", [AuthMiddleware]); ``` > **Note** — The fourth argument is the per-route middleware array: > `Router.get(path, Controller, action, middleware?)`. See > [Routing](/docs/routing) for groups, prefixes, and named routes. ## Dependency injection A controller is constructed by `container.make()`, which auto-wires its dependencies. Decorate the **class** with `@inject(...)`, listing the tokens in constructor order — the container resolves each token and passes it to the constructor: ```typescript fragment // app/controllers/PostController.ts import type { HttpContext } from "zerotal"; import { inject } from "zerotal"; import { CacheManager } from "@zerotal/cache"; @inject(CacheManager) export class PostController { constructor(private cache: CacheManager) {} async index(ctx: HttpContext): Promise { const posts = await this.cache.remember("posts.all", 60, () => Post.all()); ctx.json({ posts }); } } ``` > **Warning** — `@inject` is a **class** decorator and only supports constructor > injection. There is no parameter-level or property-level `@inject` — the tokens > are listed on the class and matched to constructor parameters by position. ### Which should I use? - **Facades** — reach for these first for one-off lookups. No constructor wiring, resolved from request-scoped storage on demand. - **`@inject(...)` on the class** — when the controller depends on a service for most of its actions and you want it injected once at construction. ### Resolving via facades Facades are the lightest-weight option — no constructor wiring needed. They read the current request from `AsyncLocalStorage`, so they work anywhere in the async tree: ```typescript // app/controllers/DashboardController.ts import type { HttpContext } from "zerotal"; import { Cache } from "@zerotal/cache"; import { Auth } from "@zerotal/auth"; export class DashboardController { async index(ctx: HttpContext): Promise { const user = Auth.user(); // resolved from AsyncLocalStorage const stats = await Cache.get("stats"); ctx.json({ user, stats }); } } ``` ## Model binding A route parameter whose name matches an auto-registered model is bound without any declaration — the resolved instance arrives on `ctx.params` under the param's name, or you can read it explicitly with `ctx.model()`. `.bind()` and the model's own `resolveRouteBinding` are for overriding that default: ```typescript fragment // routes/index.ts — :post already resolves through Post Router.get("/posts/:post", PostController, "show"); ``` ```typescript fragment // app/controllers/PostController.ts — via ctx.params: async show(ctx: HttpContext<{ post: Post }>): Promise { ctx.json(ctx.params.post); } // app/controllers/PostController.ts — or via ctx.model(): async show(ctx: HttpContext): Promise { const post = ctx.model("post"); ctx.json(post); } ``` > **Note** — If the bound record is not found, the resolver throws a 404 > automatically — no guard needed. `ctx.model()` throws if no binding was > registered for that param name. ## FormRequest validation Delegate validation to a `FormRequest` class for cleaner controllers. The class comes from `@zerotal/validator`: ```typescript // app/requests/posts/StorePostRequest.ts import { FormRequest, RuleBuilder } from "@zerotal/validator"; export class StorePostRequest extends FormRequest { // Do NOT annotate the return type — validate() infers the typed shape from it. // (Pipe-strings like "required|string" are Flow's @validate syntax; FormRequest // uses the RuleBuilder.) rules(r: RuleBuilder) { return { title: r.string().min(3).max(255), body: r.string().min(10), tags: r.array(r.string()).optional(), }; } } ``` `StorePostRequest.validate()` parses the request body, runs the rules, and returns the validated data fully typed from your `rules()` return — it throws a validation error on failure: ```typescript fragment // app/controllers/PostController.ts import { StorePostRequest } from "../requests/posts/StorePostRequest.ts"; async store(ctx: HttpContext): Promise { const data = await StorePostRequest.validate(); // throws on validation failure const post = await Post.create(data); ctx.json(post, 201); } ``` > **Tip** — Do not annotate the `rules()` return type explicitly. The static > `validate()` infers the result shape from `ReturnType`, so an explicit > annotation would widen the result back to `Record`. See the [Validator](/docs/validator) guide for the full rules reference. ## Resource controllers A resource controller implements the standard seven RESTful actions: ```typescript // app/controllers/ArticleController.ts import type { HttpContext } from "zerotal"; export class ArticleController { async index(ctx: HttpContext): Promise { /* GET /articles */ } async create(ctx: HttpContext): Promise { /* GET /articles/create */ } async store(ctx: HttpContext): Promise { /* POST /articles */ } async show(ctx: HttpContext): Promise { /* GET /articles/:id */ } async edit(ctx: HttpContext): Promise { /* GET /articles/:id/edit */ } async update(ctx: HttpContext): Promise { /* PUT /articles/:id */ } async destroy(ctx: HttpContext): Promise { /* DELETE /articles/:id */ } } ``` Register all seven with a single call, or narrow them with `.only()` / `.except()`: ```typescript fragment // routes/index.ts Router.resource("articles", ArticleController); Router.resource("articles", ArticleController).only(["index", "show"]); Router.resource("articles", ArticleController).except(["create", "edit"]); ``` > **Tip** — Generate either shape with `bun zt make:controller` — add > `--resource` for the full CRUD stubs. ## Returning responses Controllers set `ctx.response` via helper methods — they do not return a value (the return type is `Promise`): ```typescript fragment // in a controller action ctx.json(data); // 200 JSON ctx.json(data, 201); // 201 JSON ctx.view(MyComponent, props); // full HTML document from a view component ctx.html("

fragment

"); // raw HTML, no DOCTYPE ctx.redirect("/dashboard", 303); // redirect (default 302) ctx.back(); // redirect to a same-origin Referer, else "/" ``` See the [Responses](/docs/responses) guide for the full API. ## Single-action controllers For an action that doesn't need grouping, give the controller a single method and name it when you register the route — a file route function works equally well: ```typescript // app/controllers/HealthCheckController.ts import type { HttpContext } from "zerotal"; import { Router } from "zerotal"; export class HealthCheckController { async handle(ctx: HttpContext): Promise { ctx.json({ status: "ok", uptime: Math.floor(process.uptime()) }); } } Router.get("/health", HealthCheckController, "handle"); ``` ## Accessing the authenticated user With `@zerotal/auth` installed, the authenticated user is available at `ctx.user` after `AuthMiddleware` runs. The `Auth` facade exposes the same data from anywhere in the async tree — handy inside services called by the controller: ```typescript fragment // in a controller action import { Auth } from "@zerotal/auth"; async store(ctx: HttpContext): Promise { // Via ctx (optional — undefined for guests): const userId = ctx.user?.id; // Via the facade (throws ForbiddenError when not authenticated): const user = Auth.user(); const id = Auth.id(); // number } ``` > **Note** — `ctx.user` and the `Auth` facade are contributed by > `@zerotal/auth`, not core. See [Authentication](/docs/authentication). ## After-response work Register a callback to run after the response has been sent — useful for expensive side effects that shouldn't block the client. `afterResponse` returns `this`, so it chains: ```typescript fragment // in a controller action async store(ctx: HttpContext): Promise { const post = await Post.create(data); ctx.json(post, 201); ctx.afterResponse(async () => { await NotifyFollowersJob.dispatch({ postId: post.id }); await Cache.forget("posts.all"); }); } ``` > **Note** — An error thrown inside an `afterResponse` callback is logged and > swallowed; it never crashes the server or affects the already-sent response. ## References Controller actions interact with the request through the `ctx` object (`HttpContext`). The members used most often from a controller: | Member | Signature | Description | | -------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------- | | `ctx.params` | `Record` | Route params, plus resolved model bindings under their name (e.g. `/posts/:id` → `{ id }`). | | `ctx.body()` | `() => Promise` | Parse and cache the JSON / form request body. | | `ctx.input(key, fallback?)` | `(key, fallback?) => T` | Read from route params → cached body → query, in order. | | `ctx.model(name)` | `(name) => T` | The route-model-bound instance for a param; throws if unbound. | | `ctx.json(data, status?)` | `(data, status?) => void` | Set a JSON response (default 200). | | `ctx.view(component, props?, status?)` | overloaded | Render a view component to a full HTML document. | | `ctx.html(markup, status?)` | `(markup, status?) => void` | Set a raw HTML response (no DOCTYPE). | | `ctx.redirect(url, status?)` | `(url, status?) => void` | Set a redirect response (default 302). | | `ctx.back(status?)` | `(status?) => void` | Redirect to a same-origin `Referer`, else `/`. | | `ctx.afterResponse(cb)` | `(cb) => this` | Run work after the response is sent. | Container wiring for controllers: | Member | Signature | Description | | -------------------- | --------------- | ---------------------------------------------------------------------------- | | `@inject(...tokens)` | class decorator | Declare constructor dependencies in order; auto-wired by `container.make()`. | ## Next steps - [Routing](/docs/routing) — map URLs to controller actions and bind models. - [Middleware](/docs/middleware) — protect and transform requests before they reach actions. - [Validator](/docs/validator) — the rules reference for `FormRequest` validation. - [Responses](/docs/responses) — the full response helper API. - [Container](/docs/container) — how `@inject` and `make()` resolve your services. - [HttpContext](/docs/context) — the full request/response object reference. --- Source: https://zerotal.dev/docs/context # Requests Context Every route handler and every middleware receives one argument: the request `HttpContext`. There is no separate request object — the incoming `Request` is a property on the context (`ctx.request`), and everything you'd reach for to read it hangs off the same argument. It holds the raw request, the response being built, the matched route params and resolved model bindings (on `ctx.params`), and the helpers for reading input and shaping the reply. ```typescript // in a controller import type { HttpContext } from "zerotal"; export class PostController { async show(ctx: HttpContext) { return ctx.json({ id: ctx.params.id }); } } ``` You rarely construct one yourself — the framework creates it per request, stores it in request-scoped (`AsyncLocalStorage`) storage, and hands it to your code. For tests, build one with [`HttpContext.fake()`](#testing). ## Destructuring the context Every method on the context is bound to its instance, so you can destructure exactly what a handler needs — methods included — without losing `this`: ```typescript fragment // routes: Router.get('/posts/:post/:tab', PostController, 'show') async show({ view, params: { post, tab } }: HttpContext<{ post: Post; tab: string }>) { return view(ShowPost, { post, tab }); } ``` `view` is a bound method here, `post` is a resolved model binding, and `tab` is a raw route param — all pulled straight off the one argument. Name the whole argument instead (`async show(ctx: HttpContext)`) when you prefer `ctx.view(...)` / `ctx.params.post`; both styles work. > **Warning** — Computed getters (`took`, `subdomains`) are _not_ bound methods, so > destructuring them takes a one-time snapshot at destructure time. `took` (elapsed > ms) in particular will be frozen — read `ctx.took` directly when you want it live. ## Typed params `HttpContext` is generic over the shape of `params`. With no type argument, `ctx.params` is `Record` — the raw matched segments. Pass a type argument to describe what the route resolves, including model bindings: ```typescript fragment // raw params only — every value is a string async index(ctx: HttpContext) { const page = ctx.params.page; // string | undefined } // typed params + a resolved model binding async show(ctx: HttpContext<{ post: Post; tab: string }>) { ctx.params.post; // Post (resolved binding) ctx.params.tab; // string (raw param) } ``` The framework hands every handler the same runtime object; the type argument is a declaration _you_ make about what this route resolves — exactly as you'd annotate any function parameter. ## Route-model bindings A binding turns a raw `:param` string into a loaded model instance before your handler runs. The framework folds the instance onto `ctx.params` under the param's name (and exposes it via `ctx.model()`). Usually there is nothing to declare: a param whose name matches an auto-registered model binds on its own, so `:post` resolves through `Post` by primary key. ```typescript fragment // routes/web.ts — :post is already bound to Post Router.get("/posts/:post", PostController, "show"); // Declare one only to override the default — a different key, or a custom lookup: Router.get("/posts/:post", PostController, "show").bind("post", (slug) => Post.query().where("slug", slug).firstOrFail(), ); ``` ```typescript fragment // in PostController — ctx.params.post is the resolved Post, not the raw id async show(ctx: HttpContext<{ post: Post }>) { return ctx.json(ctx.params.post); } // the same instance, read explicitly async show(ctx: HttpContext) { const post = ctx.model("post"); return ctx.json(post); } ``` Resolution runs before the middleware pipeline, so a missing record produces a 404 rendered by the exception handler rather than a half-run handler. An unbound param stays a raw string on `ctx.params`. The full binding surface — implicit binding, custom resolvers, scoped bindings — lives in [Routing](/docs/routing). ## Reading input The scalar helpers check route params first, then the query string, and coerce to the type the method name promises. Each takes an optional fallback. ```typescript fragment // in a controller ctx.query("page", "1"); // string | undefined — query string only ctx.string("sort", "asc"); // string | undefined — param then query ctx.integer("id"); // number | undefined — param then query, parsed as int ctx.boolean("active", false); // boolean — param then query, coerced ``` ### Number parsing `integer()` reads the param-then-query value and parses it with `parseInt(raw, 10)`. It returns the `fallback` (or `undefined` when you pass none) in two cases: the key is absent, or the value is not a valid integer (`NaN`). Because parsing is base-10, `"08"` reads as `8` and a trailing-garbage value like `"42abc"` parses to `42` — validate with a [form request](/docs/validator) when you need to reject malformed input rather than coerce it. ```typescript fragment // in a controller — GET /posts?page=3 ctx.integer("page"); // 3 ctx.integer("page", 1); // 3 (fallback unused) ctx.integer("missing", 1); // 1 (absent → fallback) ctx.integer("missing"); // undefined (absent, no fallback) ctx.integer("count"); // GET ?count=abc → undefined (NaN → fallback) ``` ### Boolean coercion `boolean()` reads the param-then-query value and returns `true` only when it is one of `'1'`, `'true'`, `'yes'`, or `'on'` (compared case-insensitively). Any other present value is `false`; an absent value returns the fallback, which defaults to `false`. ```typescript fragment // in a controller ctx.boolean("active"); // ?active=true / ?active=1 / ?active=ON → true ctx.boolean("active"); // ?active=0 / ?active=no / ?active= → false ctx.boolean("active"); // absent → false (default fallback) ctx.boolean("active", true); // absent → true (custom fallback) ``` > **Note** — These coercion helpers are for raw string params. A param bound to a > model holds the model instance on `ctx.params`, so read it as `ctx.params.post` or > `ctx.model("post")`, never `ctx.integer("post")`. ### The request body `body()` parses and caches the body (JSON, form-urlencoded, or multipart fields) so repeated calls are free, and returns `{}` on an absent or invalid body, or on a JSON body with no fields (a bare number, string, boolean or `null`). A JSON array is returned as sent: ```typescript fragment const data = await ctx.body<{ title: string; body: string }>(); ``` `input()` reads a single merged value in priority order — route params → cached body → query string — without awaiting. It reads no field from an array body: ```typescript fragment ctx.input("id"); // route :id or ?id= ctx.input("q", "all"); // with fallback ``` > **Warning** — `input()` only sees body data if `await ctx.body()` (or a > [validation](/docs/validator)) ran earlier in the lifecycle; otherwise it falls through to the query > string. For guaranteed body access, `await ctx.body()` first. Outside production, a > call that comes back empty on a JSON or form request whose body was never read logs a > warning naming the key, once per route. Read a header with `header()` (case-insensitive) or pull a Bearer token with `bearerToken()`: ```typescript fragment ctx.header("x-forwarded-for"); // string | null ctx.bearerToken(); // string | null — strips the "Bearer " prefix ``` ### Uploaded files `file()` returns the first `UploadedFile` for a form field (or `null`); `files()` returns all of them. Both parse and cache the multipart body on first call. A body over the limit is refused before this runs; to let one route take a larger upload, see [Request body size](/docs/routing#request-body-size). ```typescript fragment const avatar = await ctx.file("avatar"); // UploadedFile | null const attachments = await ctx.files("attachments"); // UploadedFile[] ``` A list of files can arrive as `attachments`, `attachments[]` or `attachments[0]`, `attachments[1]`, …, depending on how the client built the form. A browser's multiple-file input uses the first and the Inertia adapter's form helper uses the second, so `files("attachments")` reads all three, in the order they were sent, and `file()` returns the first of them. An `UploadedFile` describes the upload and knows how to persist itself. Validate before storing, then hand it a disk — `store()` returns the stored path: ```typescript fragment // in a controller — single file const avatar = await ctx.file("avatar"); if (avatar) { avatar.originalName; // original filename as sent by the browser avatar.size; // bytes avatar.mimeType; // MIME type, e.g. 'image/jpeg' avatar.extension(); // 'jpg', 'png', etc. const valid = avatar.isValid({ maxSize: 2 * 1024 * 1024, // 2 MB mimes: ["image/jpeg", "image/png"], }); const path = await avatar.store("avatars", Storage.disk("s3")); } ``` ```typescript fragment // in a controller — multiple files for (const file of await ctx.files("attachments")) { await file.store("uploads", Storage.disk()); } ``` > **Danger** — `originalName` is supplied by the client and may be untrusted. > `store()` defaults to a `.` filename precisely so attacker-controlled > names never reach your filesystem — sanitise the original before displaying it. See [Storage](/docs/storage) for configuring the disks `store()` writes to. ## Building the response The response helpers set `ctx.response` for you and return nothing — they are terminal. You can also `return` a value from a controller; see [Responses](/docs/responses) for the full set. ```typescript fragment ctx.json({ user }); // 200 application/json ctx.json({ errors }, 422); // custom status ctx.view(WelcomeView, { name }); // full HTML document (prepends ) ctx.html("

fragment

"); // HTML fragment, no DOCTYPE ctx.redirect("/dashboard"); // 302 ctx.redirect("/dashboard", 303); // 303 — use after POST/PUT/DELETE ctx.back(); // redirect to the Referer (same-origin only) ctx.back(303); // same, with a 303 status ``` `view()` accepts either pre-rendered markup, or a **view component plus its props**. A view component receives the request `HttpContext` first and your props second: ```typescript fragment // resources/views/Welcome.tsx export default function Welcome(ctx: HttpContext, { title }: { title: string }) { return (

{title}

{ctx.url.pathname}

); } // in a controller ctx.view(Welcome, { title: "Hello" }); ``` Route params and model bindings reach the component through `ctx.params`; the second argument is strictly the props you pass. `markdown()` renders a Markdown string to a full HTML document via `Bun.markdown.html()`. > **Danger** — `back()` falls back to `/` whenever the `Referer` is missing or points > to a different origin, preventing open-redirect attacks through a forged `Referer` > header. Don't replace it with a raw `redirect(referer)`. ## Middleware Middleware is a class with a `handle(ctx, next)` method. It receives the same `HttpContext` and either calls `next()` to pass control down the pipeline or short-circuits by producing a response: ```typescript // app/middleware/EnsureActive.ts import type { HttpContext, NextFn } from "zerotal"; export class EnsureActive { async handle(ctx: HttpContext, next: NextFn): Promise { if (!ctx.boolean("active")) return ctx.redirect("/inactive"); return next(); } } ``` Handlers and middleware now receive the exact same object, so there's a single mental model and a single way to read params. See [Middleware](/docs/middleware) for the pipeline, ordering, and registration. ## The authenticated user `ctx.user` is **not** a built-in field. When `PersistUserMiddleware` (from [`@zerotal/auth`](/docs/authentication)) runs, it reads the session's user id, loads the matching record, and assigns it to `ctx.user`; `AuthMiddleware` reads it to guard routes. It is `undefined` for guests. ```typescript fragment if (!ctx.user) throw new UnauthorizedError(); return ctx.json({ email: ctx.user.email }); ``` The resolver that loads the user from the session id is configured from your registered auth model — see [Authentication](/docs/authentication). ## Client IP ```typescript fragment ctx.clientIp(); // string | null — the client, behind however many proxies you run ctx.ip(); // string | null — the TCP peer, from Bun's server.requestIP() ``` `clientIp()` is the one to record and to limit on. With no `app.throttle.trustedProxies` it is the socket address. With `trustedProxies: n` it reads `X-Forwarded-For` from the right: each proxy appends the address it received the request from, so the `n`-th entry from the end is the client and everything to its left is whatever the client chose to send. It is the same rule the throttles, the audit trail, the sign-in lockout and Flow use, so an address you store and the address they limit on agree. It returns `null` when the request offers no address. `ip()` is the peer, and behind a reverse proxy the peer is the proxy. It returns `null` when no Bun server reference was injected (e.g. in unit tests created with `HttpContext.fake()`). > **Warning** — `X-Forwarded-For` is written by the client as well as by your proxies. Never key > on its leftmost entry, and do not read it yourself with `ctx.header()`: set > `app.throttle.trustedProxies` once and call `clientIp()`. ## URL & matching helpers ```typescript fragment ctx.path(); // "/posts" — pathname only ctx.fullUrl(); // "https://app.test/posts?page=2" ctx.host(); // "app.test" ctx.is("/admin/*"); // glob match against the path (* excludes /, ** includes it) ctx.subdomain("tenant"); // string | null — from Router.group({ domain }) ctx.subdomains; // { tenant: "acme" } ``` `isJson()` / `wantsJson()` inspect the `Content-Type` / `Accept` headers — handy in an exception handler, or anywhere one route serves both browsers and API clients: ```typescript fragment // in a controller or middleware if (ctx.wantsJson()) { ctx.json({ message: "Unauthorized" }, 401); } else { ctx.redirect("/login", 303); } ``` ## Flash data Flash writes a value to the session for the **next** request only — ideal for post-redirect success and error messages. It requires `SessionMiddleware` and silently no-ops without it. ```typescript fragment // before redirecting ctx.flash("success", "Post saved!"); return ctx.redirect("/posts", 303); ``` ```typescript fragment // on the next request const msg = ctx.flashed("success"); // 'Post saved!' ``` The redirect response builders (`redirect().withSuccess(...)`) wrap this pattern more fluently — see [Responses](/docs/responses). ## After-response callbacks Register work to run **after** the response has been sent — fire-and-forget side effects that shouldn't delay the client. `afterResponse()` returns `this`, so calls chain. ```typescript fragment ctx.afterResponse(async () => { await analytics.track(ctx.requestId, ctx.url.pathname); }); ``` A callback's errors are logged and swallowed, so one failure never affects the response or the other callbacks. > **Note** — `afterResponse()` acquires the request-scoped container reference > synchronously at registration time, so the scope cannot be flushed before your > callback gets a chance to run. ## Accessing the context anywhere You don't have to thread `ctx` through every function. From anywhere in the async call chain, `request()` returns the current request's `HttpContext`: ```typescript import { request } from "zerotal"; request(); // the HttpContext — throws outside a request request("page", "1"); // shorthand for request().input("page", "1") ``` The rule is two lines: take `ctx` where it's handed to you (handlers, hooks, middleware); call `request()` anywhere else. Code that also runs **outside** a request — a service shared with CLI commands or queue workers — uses `HttpContext.tryGet()`, which returns `undefined` instead of throwing. ## Asking once per request `RequestContext.remember(key, factory)` runs `factory` at most once per request for a given key and hands every later caller the same answer: ```typescript fragment import { RequestContext } from "zerotal"; const settings = await RequestContext.remember(`household:${id}:settings`, () => Settings.query().where("household_id", id).first(), ); ``` This is the other half of the [N+1 detector](/docs/database#n1-detection): the detector tells you a query ran too many times, and when the answer is the same every time, "ask once" is the fix rather than eager loading. Two behaviours are deliberate, and both are the ones a hand-rolled version usually gets wrong: - **The promise is cached, not the resolved value.** Cache after the `await` and a `Promise.all` of ten readers all miss — none has resolved when the others look. Caching the promise makes the first caller's in-flight work the answer for the other nine. - **A rejected promise is evicted.** Otherwise one transient failure poisons every later read in the same request, including the retry. Outside a request it is a pass-through. A queue worker has no request to scope to, and quietly sharing a value across jobs would be worse than not caching. `RequestContext.forget(key)` drops a value when a write invalidates a read taken earlier in the same request. ## Testing `HttpContext.fake()` builds a context without a live server — perfect for unit testing controllers and middleware: ```typescript fragment const ctx = HttpContext.fake("http://localhost/posts?page=2", { method: "GET", headers: { Authorization: "Bearer token" }, }); await new PostController().index(ctx); expect(ctx.response?.status).toBe(200); ``` Pass a `body` to exercise handlers that read one, and assign `ctx.params` directly when the handler expects route params a real match would have provided: ```typescript fragment // in a test — a POST with a JSON body const ctx = HttpContext.fake("http://localhost/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "Hello", body: "World" }), }); ctx.params = { id: "42" }; ``` The signature is `HttpContext.fake(url?, init?, container?)`; all three are optional. See [Testing](/docs/testing) for the full harness, and [HTTP testing](/docs/testing/http) for the higher-level request helpers. ## References ### `HttpContext` ```typescript fragment class HttpContext = Record> { constructor(request: Request, container: ScopedResolver); } ``` The per-request object every handler and middleware receives. `TParams` types `ctx.params` — defaulting to `Record` (raw params), or the bag of raw params and resolved model bindings you declare for a route. #### Properties | Property | Type | Description | | ----------- | ----------------------- | ------------------------------------------------------------ | | `request` | `Request` | The raw Bun/Web API `Request` object. | | `response` | `Response \| undefined` | Set by handlers; read by the framework to send the reply. | | `url` | `URL` | Parsed URL (`pathname`, `searchParams`, `origin`, …). | | `params` | `TParams` | Route params, plus resolved model bindings under their name. | | `requestId` | `string` | UUID generated per request (`crypto.randomUUID()`). | | `startedAt` | `number` | `performance.now()` timestamp captured at construction. | | `locale` | `string` | Current locale (default `'en'`); set by `I18nMiddleware`. | | `took` | `number` (getter) | Whole milliseconds elapsed since `startedAt`. | | `container` | `ScopedResolver` | The request-scoped container for this request. | #### Input methods | Method | Signature | Description | | ------------- | ---------------------------------------- | ------------------------------------------------ | | `query` | `(key, fallback?): string \| undefined` | Read a query-string param. | | `string` | `(key, fallback?): string \| undefined` | Read a param then query as a string. | | `integer` | `(key, fallback?): number \| undefined` | Read a param then query, parsed base-10. | | `boolean` | `(key, fallback = false): boolean` | Coerce a param/query to a boolean. | | `input` | `(key, fallback?): T` | Merged read: params → cached body → query. | | `body` | `(): Promise` | Parse and cache the request body. | | `header` | `(key, fallback = null): string \| null` | Read a request header (case-insensitive). | | `bearerToken` | `(): string \| null` | Extract the `Authorization: Bearer` token. | | `file` | `(field): Promise` | First uploaded file for a form field. | | `files` | `(field): Promise` | All uploaded files for a form field. | | `model` | `(name): T` | Resolved route-model binding; throws if unbound. | #### Response methods | Method | Signature | Description | | ---------- | -------------------------------------------- | --------------------------------------------------- | | `json` | `(data, status = 200): void` | Set a JSON response. | | `view` | `(componentOrMarkup, props?, status?): void` | Render a full HTML document (``). | | `markdown` | `(content, options?, status = 200): void` | Render Markdown to a full HTML page. | | `html` | `(markup, status = 200): void` | Set a raw HTML fragment (no DOCTYPE). | | `redirect` | `(url, status = 302): void` | Set a redirect (`301 \| 302 \| 303 \| 307 \| 308`). | | `back` | `(status = 302): void` | Redirect to the same-origin `Referer`, else `/`. | #### Request, session & lifecycle methods | Method | Signature | Description | | --------------- | -------------------------- | ------------------------------------------------------ | | `path` | `(): string` | Request pathname (no query). | | `fullUrl` | `(): string` | Full URL including query string. | | `host` | `(): string` | Host portion of the URL. | | `is` | `(pattern): boolean` | Glob-match the path (`*` excludes `/`, `**` includes). | | `subdomain` | `(name): string \| null` | A single subdomain param from a `domain` group. | | `isJson` | `(): boolean` | True when the body is `application/json`. | | `wantsJson` | `(): boolean` | True when `Accept` includes `application/json`. | | `ip` | `(): string \| null` | Socket-level client IP, or `null`. | | `clientIp` | `(): string \| null` | Client IP behind your proxies; see Client IP. | | `flash` | `(key, value): void` | Write a value to the session for the next request. | | `flashed` | `(key): T \| undefined` | Read a value flashed in the previous request. | | `afterResponse` | `(callback): this` | Run a callback after the response is sent. | #### Static methods | Method | Signature | Description | | -------- | ---------------------------------------- | ----------------------------------------------------- | | `tryGet` | `(): HttpContext \| undefined` | The active context, or `undefined` outside a request. | | `fake` | `(url?, init?, container?): HttpContext` | Build a context for unit tests. | > **Note** — `requestId` is echoed back to the client in the `X-Request-Id` response > header by [`LoggerMiddleware`](/docs/logger), not by the framework core. The id > itself always exists on the context. ### `UploadedFile` Returned by `file()` and `files()`. | Member | Signature | Description | | ---------------- | ------------------------------------------------------------------------------------------ | ------------------------------------- | | `originalName` | `originalName: string` | Client-supplied filename (untrusted). | | `mimeType` | `mimeType: string` | Browser-reported MIME type. | | `size` | `size: number` | File size in bytes. | | `extension` | `extension(): string` | Lowercase extension without the dot. | | `isValid` | `isValid(options?: FileValidationOptions): boolean` | Check `maxSize` / `mimes` rules. | | `store` | `store(directory: string, disk: StorageDisk, filename?: string): Promise` | Write to a disk, returns the path. | | `storeAndGetUrl` | `storeAndGetUrl(directory: string, disk: StorageDisk, filename?: string): Promise` | Store and return the public URL. | ## Next steps - [Controllers](/docs/controllers) — where the context is most often used. - [Validator](/docs/validator) — validate the input you read here, with `FormRequest`. - [Responses](/docs/responses) — the full response-building API. - [Middleware](/docs/middleware) — how the context flows through the pipeline. - [Routing](/docs/routing) — route params and route-model binding. - [Storage](/docs/storage) — the disks `UploadedFile.store()` writes to. --- Source: https://zerotal.dev/docs/responses # Responses Controllers and middleware build the outgoing response by calling helper methods on the per-request `HttpContext`. After your action returns, the pipeline reads the context's `response` and sends it to the client. In a route handler you receive the request `HttpContext` directly — name it `ctx` — and call `ctx.json(...)`, `ctx.view(...)`, `ctx.redirect(...)`, and friends. Middleware receives the same context and uses the identical methods. > **Note** — Handlers and middleware receive the same `HttpContext` object. Every > helper below works on it; `ctx` is just the variable name used throughout. ## Getting Started Responses are built into `@zerotal/core` — nothing to install. Every handler receives an `HttpContext` carrying the helpers below: ```typescript import type { HttpContext } from "zerotal"; ``` ## JSON ```typescript fragment // in a controller ctx.json(data); // 200 OK — Content-Type: application/json ctx.json(data, 201); // 201 Created ctx.json({ errors }, 422); // 422 Unprocessable Content ``` `json(data, status = 200)` serialises with `Response.json`, so anything JSON-serialisable is accepted: plain objects, arrays, ORM models, `null`. ## HTML views ### Full document `view()` accepts either pre-rendered markup, or a view component plus its props. It prepends `` and sets `Content-Type: text/html`: ```typescript fragment // in a controller import { WelcomePage } from "../../resources/views/WelcomePage.tsx"; ctx.view(WelcomePage(ctx, { title: "Hello" })); // pre-rendered markup ctx.view(WelcomePage, { title: "Hello" }); // component + props ctx.view(WelcomePage, { title: "Hello" }, 201); // component, props, status ``` When you pass a component, it receives the request `HttpContext` as its first argument and your props as its second. Route params and model bindings reach the component through `ctx.params`. JSX syntax needs `"jsxImportSource": "zerotal"` in your `tsconfig.json` — set once for the whole project, and already present in scaffolded apps. See the [View](/docs/view) guide. > **Tip** — Passing the component form (`ctx.view(WelcomePage, props)`) lets the > framework hand the component the `HttpContext` for you, so you can read route > params and model bindings from `ctx.params` without wiring them up by hand. ### Raw HTML For htmx, Turbo Streams, or any partial render — no DOCTYPE prepended: ```typescript fragment // in a controller ctx.html('

Saved!

'); ctx.html(renderPartial(data), 200); ``` ### Markdown Render a Markdown string to a full HTML page using Bun's built-in `Bun.markdown.html()`. Tables, strikethrough, tasklists, autolinks, and heading IDs are enabled by default: ```typescript fragment // in a controller const content = await Bun.file("./docs/guide.md").text(); ctx.markdown(content); ctx.markdown(content, { title: "Getting Started", headings: { ids: true } }); ``` When no `title` option is given, the first heading in the document is used, falling back to `"Docs"`. ## Redirects ```typescript fragment // in a controller ctx.redirect("/dashboard"); // 302 Found ctx.redirect("/dashboard", 303); // 303 See Other ← use after POST/PUT ctx.redirect("/dashboard", 301); // 301 Permanent ctx.redirect("/dashboard", 307); // 307 Temporary (preserves method) ctx.redirect("/dashboard", 308); // 308 Permanent (preserves method) ctx.back(); // 302 to Referer (safe — same origin only) ctx.back(303); // 303 to Referer ``` `back()` reads the `Referer` header and falls back to `/` when it is missing or points to a different origin. > **Tip** — POST-Redirect-GET: use `303` after mutating actions so browsers > always issue a `GET` on the redirect target and form re-submission is > prevented. > **Danger** — `back()` only follows a `Referer` on the same origin; a > cross-origin or forged value falls back to `/`. This prevents open-redirect > attacks — never bypass it by reading the header yourself. ## File downloads Return a `Response` directly with the appropriate headers: ```typescript fragment // in a controller const file = Bun.file("./exports/report.csv"); ctx.response = new Response(file as unknown as BodyInit, { headers: { "Content-Type": "text/csv", "Content-Disposition": 'attachment; filename="report.csv"', }, }); ``` ## Custom responses Set `ctx.response` to any `Response` object — the pipeline sends it verbatim: ```typescript fragment // in a controller ctx.response = new Response("pong", { status: 200 }); ctx.response = new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "Content-Type": "application/json", "X-Custom": "value" }, }); // Stream a large body const stream = new ReadableStream({ ... }); ctx.response = new Response(stream, { headers: { "Content-Type": "text/event-stream" }, }); ``` ## Appending headers to any response Every helper assigns a fresh `Response` to `ctx.response`. To add a header, rebuild it from the existing one: ```typescript fragment // in a controller, after setting ctx.response via any helper const existing = ctx.response!; const headers = new Headers(existing.headers); headers.set("X-Request-Id", ctx.requestId); ctx.response = new Response(existing.body, { status: existing.status, headers, }); ``` ## Flash + redirect Flash a message and redirect in one step — the flashed value is available via `ctx.flashed()` on the next request. Flashing requires an active session (see [Session](/docs/session)) and silently no-ops without one: ```typescript fragment // in a controller ctx.flash("success", "Post created!"); ctx.redirect("/posts", 303); ``` In [Inertia](/docs/inertia) apps use the `inertia()` helper with `back()` or `redirect()` — no flash needed because Inertia preserves shared props across redirects. ## Content negotiation Use `wantsJson()` (true when the client sends `Accept: application/json`) to respond differently based on what the client accepts: ```typescript fragment // in a controller async destroy(ctx: HttpContext): Promise { await post.delete(); if (ctx.wantsJson()) { ctx.response = new Response(null, { status: 204 }); } else { ctx.flash("success", "Post deleted."); ctx.redirect("/posts", 303); } } ``` ## Router-level view shortcut For routes that only render a view with static or request-computed props, skip the controller entirely with `Router.view()`. A static props object is evaluated once at registration; a factory function receives the `HttpContext` per request and may be async: ```typescript fragment // routes/web.ts import { Router } from "zerotal"; Router.view("/about", AboutPage, { title: "About Us" }); Router.view("/dashboard", DashboardPage, async (ctx) => ({ user: ctx.user, stats: await fetchStats(ctx.user!.id), })); ``` ## Which helper should I use? - **`ctx.json()`** — API endpoints, fetch/XHR clients, Inertia validation errors. - **`ctx.view()`** — full server-rendered HTML pages from a JSX component. - **`ctx.html()`** — HTML fragments for htmx or Turbo Streams (no DOCTYPE). - **`ctx.markdown()`** — serve a `.md` file as a styled documentation page. - **`ctx.redirect()` / `ctx.back()`** — after a mutation, or to send the user elsewhere; pair with `flash()` for a one-request status message. - **`ctx.response = new Response(...)`** — downloads, streams, custom status codes (e.g. `204 No Content`), or any header set the helpers don't cover. ## Testing Set your suite up once as described in [Testing](/docs/testing). Every request through `TestApp` comes back as a `TestResponse`, whose assertions read as the sentence you would have written in a comment. **Assert the status by meaning, not by number**, so a failure says what went wrong rather than what integer it saw: ```typescript fragment // tests/http/posts.test.ts import { test } from "bun:test"; import { createApp } from "../helpers.ts"; test("creating a post", async () => { const app = await createApp(); const res = await app.actingAs(user).post("/posts", { title: "Hello" }); res.assertCreated(); // clearer than assertStatus(201) res.assertJsonPath("data.title", "Hello"); await app.close(); }); ``` `assertOk`, `assertCreated`, `assertNoContent`, `assertNotFound`, `assertUnauthorized`, `assertForbidden`, and `assertUnprocessable` all exist — reach for `assertStatus(n)` only when the code has no name. **Redirects and JSON need different assertions**, and picking the wrong one is how a broken route passes. `assertRedirect` checks the `Location` header; `assertJson` parses the body: ```typescript fragment // tests/http/posts.test.ts res.assertRedirect("/posts/hello"); // 3xx + Location res.assertJson({ id: 1, title: "Hello" }); // exact body match res.assertJsonPath("meta.total", 25); // one path, ignoring the rest res.assertJsonCount(3, "data"); // array length at a path ``` **Prefer `assertJsonPath` to `assertJson`** for anything with a timestamp or an id in it. An exact-match assertion on a whole body fails every time an unrelated field is added, which trains people to update tests without reading them. **Headers and cookies are part of the response contract** when a client depends on them: ```typescript fragment // tests/http/downloads.test.ts res.assertHeader("Content-Type", "text/csv"); res.assertHeader("Content-Disposition"); res.assertCookie("session"); res.assertCookieMissing("remember_me"); ``` > **Note** — `assertSee` and `assertDontSee` check the rendered body as text. > They are for HTML responses; on a JSON body they will happily match a substring > inside a field name and give you a passing test that proves nothing. ## References Response helpers on `HttpContext`: | Method | Signature | Description | | ----------- | -------------------------------------------------------------------- | --------------------------------------------------------------------- | | `json` | `json(data: unknown, status = 200): void` | Serialise `data` as a JSON response. | | `view` | `view(markup, status?)` / `view(component, props?, status?)` | Render a full HTML document (prepends ``). | | `html` | `html(markup: string \| { toString(): string }, status = 200): void` | Send a raw HTML string with no DOCTYPE. | | `markdown` | `markdown(content: string, options?, status = 200): void` | Render Markdown to a full HTML page via `Bun.markdown.html()`. | | `redirect` | `redirect(url: string, status: 301\|302\|303\|307\|308 = 302): void` | Set a `Location` redirect response. | | `back` | `back(status: 301\|302\|303\|307\|308 = 302): void` | Redirect to the same-origin `Referer`, or `/`. | | `flash` | `flash(key: string, value: unknown): void` | Stash a value for the next request (needs a session). | | `flashed` | `flashed(key: string): T \| undefined` | Read a value flashed in the previous request. | | `wantsJson` | `wantsJson(): boolean` | True when `Accept` includes `application/json`. | | `response` | `response: Response \| undefined` | The outgoing response; assign a `Response` directly for full control. | Common status codes: | Helper | Status | Typical use | | ------------------------ | ------ | ------------------------------------------------ | | `ctx.json(data)` | 200 | GET, success | | `ctx.json(data, 201)` | 201 | POST, resource created | | `ctx.json(null, 204)` | — | DELETE, no content (set `ctx.response` directly) | | `ctx.json(errors, 422)` | 422 | Validation failed | | `ctx.json(msg, 401)` | 401 | Unauthenticated | | `ctx.json(msg, 403)` | 403 | Forbidden | | `ctx.json(msg, 404)` | 404 | Not found | | `ctx.redirect(url)` | 302 | General redirect | | `ctx.redirect(url, 303)` | 303 | After POST/PUT/DELETE | | `ctx.redirect(url, 301)` | 301 | Permanent redirect | ## Negotiating by client One route, three audiences. `negotiate(ctx)` picks a branch from the `Accept` header and how the request arrived, so a handler answers a browser, an API client and the console without three copies of the logic: ```typescript fragment import { negotiate } from "zerotal/http"; await negotiate(http)({ web: () => http.redirect("/dashboard"), api: () => http.json({ ok: true }), cli: () => http.text("done"), }); ``` `NegotiateMap` is that object; `WebContext`, `ApiContext` and `CliContext` are what each branch receives. A missing branch falls through to `web`, because the browser is the audience most likely to be looking. This is what the framework's own error handler uses, which is why a 422 is a redirect-with-errors for a form post and a JSON body for a fetch — see [Errors](/docs/errors#response-format-by-client-type). ## Next steps - [Requests Context](/docs/context) — read input from the incoming request. - [View](/docs/view) — render JSX and Markdown pages. - [Inertia](/docs/inertia) — return Inertia responses for SPA frontends. - [Cookies](/docs/cookies) — attach cookies to outgoing responses. - [HttpContext](/docs/context) — the full per-request object these helpers live on. --- Source: https://zerotal.dev/docs/validator # Validation The validator checks incoming request data against rule chains and produces fully-typed output — no manual type assertions needed. It offers two entry points: `FormRequest` (class-based, recommended) and the standalone `validate()` function (for one-off use). ## Getting Started ```bash # in your project root bun add @zerotal/validator ``` The validator has no provider to register — import its classes and functions directly. Database-aware rules (`unique()`, `exists()`) do require [`DatabaseProvider`](/docs/database) to be registered; see [Database rules](#database-rules). ## Configuration Create `config/validator.ts` with the `ValidatorConfig()` helper so every field stays type-checked while defaults are filled in: ```typescript // config/validator.ts import { ValidatorConfig } from "@zerotal/validator"; export default ValidatorConfig({ stopOnFirstFailure: true, // stop after the first failure per field locale: "en", // default locale for error messages }); ``` | Field | Required | Default | Description | | -------------------- | -------- | ------- | -------------------------------------------------- | | `stopOnFirstFailure` | no | `true` | Stop validation after the first failure per field. | | `locale` | no | `"en"` | Default locale for error messages. | ## Which entry point should I use? - **`FormRequest`** — the default for HTTP handlers. Encapsulates rules and authorization in a reusable, testable class, reads the request from the active context, and throws the right error on failure. - **`validate(ctx, factory)`** — for one-off HTTP validation where a dedicated class would be overkill. Same failure behavior as `FormRequest`. - **`Validator.check(data, factory)`** — for non-HTTP code (CLI commands, services, background jobs). Returns a result object and never throws or redirects. See [Non-HTTP validation](#non-http-validation). ## FormRequest ### Defining a request ```typescript // app/requests/posts/StorePostRequest.ts import { FormRequest, RuleBuilder } from "@zerotal/validator"; export class StorePostRequest extends FormRequest { // Return true to allow, false to deny with a 403 ForbiddenError. // Access the current request via this.context. authorize(): boolean { return !!this.context.user; } // Do NOT annotate the return type — TypeScript needs to infer the narrow shape // for validate() to produce a typed result. rules(r: RuleBuilder) { return { title: r.string().min(3).max(255), body: r.string().min(10), tags: r.array(r.string()).optional(), }; } } ``` > **Warning** — Do not add an explicit return type to `rules()`. Annotating it > (e.g. as `Record`) widens the inferred type and makes > `validate()` return `Record` instead of your typed shape. ### Calling validate Call `validate()` as a static method on the class. It reads `HttpContext` from `AsyncLocalStorage` — no arguments needed. ```typescript fragment // in a controller const data = await StorePostRequest.validate(); data.title; // string — fully typed, no cast needed data.body; // string data.tags; // string[] | undefined ``` The body is read through the same cache as [`ctx.body()`](/docs/context#the-request-body), so the two work in either order, and after middleware that has already read the body. Afterwards `ctx.body()` and `ctx.input()` return the body as the client sent it, not just the validated fields. A multipart form's files are validated from the same parse that `ctx.file()` reads. On failure, `validate()` stores `errors` and `old` (previous input) in the session, then branches on the request type: | Request type | Detected by | Error thrown | HTTP result | | ------------ | ------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------- | | JSON / API | `Accept` prefers `application/json` to `text/html`, even with `X-Inertia` | `ValidationJsonError` | 422 JSON with field errors | | Inertia | `X-Inertia: true` header, `Accept` that does not prefer JSON | `ValidationRedirectError` | Redirect back; errors surfaced via shared props | | HTML form | neither | `ValidationRedirectError` | Redirect back; errors in session | `Accept` prefers JSON when `application/json` has a higher q-value than `text/html`, or the same q-value and comes first: `application/json` and `application/json, text/html` do, `text/html, application/json` and a browser's `Accept` do not. The [exception handler](/docs/errors) uses the same rule, so a client gets one format for a validation error and a 404 alike. An Inertia visit sends `Accept: text/html, application/xhtml+xml`, so it redirects; a client that keeps the `X-Inertia` header on a call asking for JSON gets the 422 it asked for. Both `ValidationJsonError` and `ValidationRedirectError` are exported from `@zerotal/validator`. The exception handler renders them appropriately — you never need to catch them yourself. ### Authorization `authorize()` runs **before** validation. Returning `false` throws a `ForbiddenError` (403) without touching the request body. ```typescript fragment // in a FormRequest subclass // Check the current user's role: authorize(): boolean { return (this.context.user as { role?: string })?.role === "admin"; } // Use Gate.allows() for policy-based auth: authorize(): boolean { return Gate.via(PostPolicy).allows("create", new Post()); } // Async authorize is also supported: async authorize(): Promise { const post = await Post.findOrFail(Number(this.context.params["id"])); return Gate.via(PostPolicy).allows("update", post); } ``` ### Accessing context inside rules Because `rules()` is an instance method, you have full access to `this.context` for rules that depend on the current user, route params, or session state: ```typescript fragment // in a FormRequest subclass rules(r: RuleBuilder) { const userId = this.context.user?.id; return { email: r.string().email() .unique("users", "email", userId), // ignore current user on update name: r.string().min(2).max(100), }; } ``` ### Preparing input An HTML form cannot leave a field out or send `null`: a blank input posts `""`. A blank optional `number()` or `date()` field already counts as absent, but a string keeps `""`, because an empty string is a value a string field can hold. So an optional email fails on a blank input: ```typescript fragment // in a FormRequest subclass rules(r: RuleBuilder) { return { assignee: r.string().trim().email().optional() }; } ``` Override `prepareForValidation()` to reshape the body before the rules see it. It runs after `authorize()` and receives the parsed body; return the object to validate. Mutating the argument and returning it is fine: ```typescript fragment // in a FormRequest subclass override prepareForValidation(body: Record) { if (body["assignee"] === "") delete body["assignee"]; return body; } ``` Now a blank field counts as absent. To clear a column instead, set the value to `null` and mark the rule `.nullable()`. The default returns the body unchanged. ## Standalone validate For simple one-off validation without a dedicated class: ```typescript fragment // in a controller import { validate } from "@zerotal/validator"; // validate(ctx, factory) reads the request body from the HttpContext and // returns the validated, typed data directly. On failure it throws — // ValidationJsonError (→ 422 JSON) or ValidationRedirectError (→ 303 back) — // which the global exception handler turns into the right response. const data = await validate(ctx, (r) => ({ title: r.string().min(3), count: r.number().integer().min(1), })); data.title; // string — fully typed, no cast needed data.count; // number ``` ## Non-HTTP validation For CLI commands, services, or background jobs — where there is no request to redirect and no response to throw — use the `Validator` facade. It returns a `{ success, data, errors }` outcome and never throws. ```typescript fragment // in a command or service import { Validator } from "@zerotal/validator"; const result = Validator.check(payload, (r) => ({ email: r.string().email(), age: r.number().min(0), })); if (!result.success) { console.error(result.errors); } else { result.data.email; // string — fully typed } ``` ## RuleBuilder types Start every rule chain with a type method on `RuleBuilder`: ```typescript fragment // in a rules() method or factory const r = new RuleBuilder(); // or the `r` param in rules() r.string(); // StringRule r.number(); // NumberRule r.boolean(); // BooleanRule r.date(); // DateRule r.file(); // FileRule — multipart/form-data uploads r.password(); // PasswordRule — strength validation // Convenience shorthands on RuleBuilder: r.required(); // r.string().required() — required string, the common case r.email(); // r.string().email() r.url(); // r.string().url() r.uuid(); // r.string().uuid() r.array(r.string()); // ArrayRule — array of strings r.object({/* … */}); // ObjectRule — nested object ``` ## Common modifiers These are available on **every** rule type: | Method | Description | | --------------------------------- | ---------------------------------------------------------------------------- | | `.required(msg?)` | Field must be present and non-empty | | `.optional()` | Field may be absent; result type becomes `T \| undefined` | | `.nullable()` | Field may be `null` | | `.default(val)` | Use `val` when field is absent; implies `.optional()` | | `.sometimes()` | Only validate when field is present in input (PATCH-friendly) | | `.bail()` | Stop after the first failing rule on this field | | `.custom(fn)` | Run a custom sync/async function; return `true`, `false`, or an error string | | `.requiredIf(field, value)` | Required when another field equals `value` | | `.requiredUnless(field, value)` | Required unless another field equals `value` | | `.requiredWith(fields[])` | Required when ANY listed field is present | | `.requiredWithout(fields[])` | Required when ANY listed field is absent | | `.requiredWithAll(fields[])` | Required when ALL listed fields are present | | `.requiredWithoutAll(fields[])` | Required when ALL listed fields are absent | | `.prohibitedIf(field, value)` | Must be absent when another field equals `value` | | `.prohibitedUnless(field, value)` | Must be absent unless another field equals `value` | | `.accepted()` | Truthy: `true`, `1`, `'1'`, `'yes'`, `'on'`, `'true'` | | `.declined()` | Falsy: `false`, `0`, `'0'`, `'no'`, `'off'`, `'false'` | ### Custom validator ```typescript fragment // in a rules() method or factory username: r.string().custom(async (value) => { const taken = await User.findBy("username", value as string); return taken ? "This username is already taken." : true; }); ``` ## String rules ```typescript fragment // in a rules() method or factory r.string() .min(3) // minimum character length .max(255) // maximum character length .size(10) // exact character length .email() // valid email address .url() // valid URL .uuid() // valid UUID v4 .ip() // valid IPv4 or IPv6 .json() // parseable JSON string .regex(/^[A-Z]+$/) // matches regex .matches(/^[A-Z]+$/, "msg") // alias for regex() .in(["a", "b", "c"]) // value in list .notIn(["x", "y"]) // value not in list .alpha() // letters only (a-z, A-Z) .alphaNum() // letters and digits .alphaDash() // letters, digits, hyphens, underscores .numeric() // digits only (optional leading minus) .digits(6) // exactly 6 digits .digitsBetween(4, 8) // between 4 and 8 digits .startsWith("https://") // must start with prefix .endsWith(".pdf") // must end with suffix .trim() // strip leading/trailing whitespace (transform) .lowercase() // convert to lowercase (transform) .uppercase() // convert to uppercase (transform) .confirmed() // value must equal `{field}_confirmation` in input .sameAs("password") // value must equal another field .present() // key must exist in input (may be empty) .prohibited() // key must be absent from input .password(); // semantic alias — chain constraints after this ``` ## Number rules ```typescript fragment // in a rules() method or factory r.number() .min(0) // minimum value (inclusive) .max(100) // maximum value (inclusive) .between(1, 10) // min and max in one call .integer() // must be a whole number .positive() // shorthand for .min(0) .notIn([0, -1]); // value not in list ``` ## Boolean rules ```typescript fragment // in a rules() method or factory r.boolean() .accepted() // truthy — for "agree to terms" checkboxes .declined(); // falsy ``` ## Date rules ```typescript fragment // in a rules() method or factory r.date() .after("2026-01-01") // strictly after date .before(new Date()) // strictly before date .afterOrEqual("2026-01-01") // on or after .beforeOrEqual("2026-12-31"); // on or before ``` ## Array rules ```typescript fragment // in a rules() method or factory r.array(r.string()) // array of strings .min(1) // minimum item count .max(10) // maximum item count .size(3); // exact item count r.array(r.number().integer()); // array of integers // Nested objects in an array: r.array(r.object({ name: r.string(), age: r.number() })); ``` ## Object rules ```typescript fragment // in a rules() method or factory r.object({ street: r.string(), city: r.string(), country: r.string().in(["US", "CA", "GB"]), zip: r .string() .regex(/^\d{5}$/) .optional(), }); ``` ## File rules Validates `File` objects from `multipart/form-data` uploads: ```typescript fragment // in a rules() method or factory avatar: r.file() .mimes(["jpg", "jpeg", "png", "webp"]) // allowed extensions .max(2048) // maximum KB .min(1) // minimum KB .optional(); ``` ## Password rules ```typescript fragment // in a rules() method or factory r.password() .min(8) // minimum length (default: 8) .mixedCase() // requires upper + lower case letters .numbers() // requires at least one digit .symbols() // requires at least one symbol .uncompromised() // must not contain spaces .confirmed(); // must equal password_confirmation field ``` ## Database rules These rules require [`DatabaseProvider`](/docs/database) to be registered; they throw at runtime otherwise. ### unique — value must not already exist in the DB The third argument ignores a record on update — pass the current record's ID, or a `UniqueOptions` object (`{ ignoreId }`) for clarity. A fourth argument overrides the error message. ```typescript fragment // in a rules() method or factory email: r.string().email().unique("users", "email"); // Ignore the current record when updating (pass the record's ID): email: r.string().email().unique("users", "email", this.context.user?.id); // Equivalent, using the options object: email: r.string().email().unique("users", "email", { ignoreId: userId }); ``` ### exists — value must exist in the DB ```typescript fragment // in a rules() method or factory userId: r.number().exists("users", "id"); roleSlug: r.string().exists("roles", "slug"); ``` > **Note** — These rules stay decoupled from the ORM: `DatabaseProvider` > registers the query executor via `registerDbRuleRunner()` during its boot, so > `@zerotal/validator` never depends directly on `@zerotal/orm`. ## Precognition When a request carries a `Precognition: true` header, `FormRequest.validate()` runs the rules without executing the controller body, then short-circuits with a `204` (no errors) or `422` (with errors). A `Precognition-Validate-Only` header (comma-separated field names) narrows the validated set to just those fields — useful for live, field-by-field client validation. ## Error handling A default message names the field the way a person reads it: `first_name` is "The first name field", whether the rule was written fluently or as a pipe string, and so are the other fields a rule depends on ("required when card number is present"). A message you pass to a rule is used exactly as written. ### JSON / API requests When `Accept` prefers `application/json` to `text/html`, validation throws `ValidationJsonError`, whether or not the request carries `X-Inertia`: ```json { "message": "The given data was invalid.", "errors": { "title": ["The title must be at least 3 characters."], "email": ["The email has already been taken."] } } ``` The response is sent as `422 Unprocessable Entity`. `ExceptionHandler` catches the error and renders this automatically. ### Inertia / HTML form requests When `Accept` does not prefer JSON (a form post, a browser, or an Inertia visit), validation throws `ValidationRedirectError`. `ExceptionHandler` converts this to a redirect back to the previous page. Errors and old input are stored in the [session](/docs/session) under the keys `'errors'` and `'old'`. Read them on the next request: ```typescript fragment // in a controller const errors = ctx.flashed>("errors"); const old = ctx.flashed>("old"); ``` In [Inertia](/docs/inertia), errors are passed automatically as the `errors` prop via shared props — no manual session reading required. ## Testing Set your suite up once as described in [Testing](/docs/testing). Validation is worth testing at the rule level, because that is where the mistakes are and it needs no request. **`Validator.check()` never throws**, so a rule set tests as a pure function — assert on the outcome rather than on a caught error: ```typescript // tests/validation/RegisterRules.test.ts import { test, expect } from "bun:test"; import { Validator } from "@zerotal/validator"; const rules = (r) => ({ email: r.string().email(), age: r.number().min(18), }); test("rejects an underage applicant", () => { const result = Validator.check({ email: "jane@example.com", age: 17 }, rules); expect(result.success).toBe(false); expect(result.errors.age).toBeDefined(); }); test("returns typed data on success", () => { const result = Validator.check({ email: "jane@example.com", age: 30 }, rules); expect(result.success).toBe(true); if (result.success) expect(result.data.email).toBe("jane@example.com"); }); ``` **Test the values that sit either side of a boundary**, not a comfortable middle. `age: 18` and `age: 17` prove `min(18)`; `age: 30` proves nothing that `age: 19` would not. **A `FormRequest` fails the HTTP request**, so test it through the route it guards. The status tells you which failure mode you got: ```typescript fragment // tests/http/register.test.ts const res = await testApp.asJson().post("/register", { email: "not-an-email" }); res.assertUnprocessable().assertInvalid("email"); // 422: Accept asked for JSON ``` > **Note** — What picks the failure mode is the request's `Accept` header, not its > body. A request whose `Accept` prefers JSON gets the `422`. Anything else is > redirected back with the errors flashed, as a form submit is, and that includes > `post()` without `asJson()`: it sends a JSON body with `Accept: */*`. Assert the > shape your route actually serves; > [HTTP Tests](/docs/testing/http#validation-whichever-shape-it-arrives-in) shows both. **A context you build by hand works too.** `validate()` and `FormRequest` accept a plain object holding just a `request`, and read the body straight off that request, since there is no body cache on it to share. A failure throws the same errors as on a real context: a `ValidationJsonError` when `Accept` prefers JSON, otherwise a `ValidationRedirectError` back to the `Referer` when it is on the request's own origin, and to `/` when it is not. With no session on the object, nothing is flashed. `HttpContext.fake()` gives you a real one. ## References ### RuleBuilder | Method | Signature | Description | | ---------- | --------------------------------------------------- | ----------------------------------------- | | `required` | `required(message?: string): StringRule` | Required string — the common entry point. | | `string` | `string(): StringRule` | Begin a string rule chain. | | `number` | `number(): NumberRule` | Begin a number rule chain. | | `boolean` | `boolean(): BooleanRule` | Begin a boolean rule chain. | | `date` | `date(): DateRule` | Begin a date rule chain. | | `file` | `file(): FileRule` | Validate a multipart/form-data upload. | | `password` | `password(): PasswordRule` | Validate password strength. | | `email` | `email(message?): StringRule` | Shorthand for `string().email()`. | | `url` | `url(message?): StringRule` | Shorthand for `string().url()`. | | `uuid` | `uuid(message?): StringRule` | Shorthand for `string().uuid()`. | | `array` | `array(item: T): ArrayRule` | Array whose items match `item`. | | `object` | `object(shape): ObjectRule` | Nested object matching `shape`. | ### Entry points | Member | Signature | Description | | ----------------- | -------------------------------------------- | ---------------------------------------------------- | | `FormRequest` | `static validate(): Promise>` | Validate the active request against the class rules. | | `FormRequest` | `authorize(): boolean \| Promise` | Allow/deny the request before validation. | | `FormRequest` | `rules(r: RuleBuilder)` | Return the field-to-rule schema (no return type). | | `validate` | `validate(ctx, factory): Promise>` | One-off HTTP validation; throws on failure. | | `Validator.check` | `check(data, factory): ValidationOutcome<…>` | Non-HTTP validation; returns a result, never throws. | ## Types | Type | What it is | | --------------------------- | -------------------------------------------------------------------------------------------------------- | | `ValidationErrors` | The error bag — field name to messages, which is what `withErrors()` and the `errors` shared prop carry. | | `FieldRuleDefinition` | One field's rules as declared. | | `InferFieldType` | The type a rule set produces, so validated data is typed rather than `unknown`. | | `PrecognitionResponseError` | What a precognition request returns when a field fails ahead of submission. | ## Next steps - [Requests Context](/docs/context#reading-input) — read the input that `FormRequest` validates. - [Errors](/docs/errors) — how `ExceptionHandler` renders validation failures. - [Authorization](/docs/authorization) — back `authorize()` with policies. - [Database](/docs/database) — register `DatabaseProvider` for `unique()` and `exists()`. - [Inertia](/docs/inertia) — where the `errors` shared prop comes from. --- Source: https://zerotal.dev/docs/session # Session `@zerotal/session` attaches a signed, per-user data store to every HTTP request. Read, write, flash, and regenerate session data from anywhere in the request pipeline without managing cookies by hand. ## Getting Started ```bash # in your project root bun add @zerotal/session ``` ## Register the provider Add `SessionProvider` to the providers array in `bootstrap/providers.ts`: ```typescript // bootstrap/providers.ts import { SessionProvider } from "@zerotal/session"; export default [ // …your other providers SessionProvider, ]; ``` Registering the provider switches on the following (it only runs in the `web` and `test` environments): - `onRegister` — binds `session.driver` (the cookie or redis driver) and the `session` accessor as lazy singletons in the container. - `onBooting` — auto-registers `SessionMiddleware` via `app.useOnce()`, so the session is loaded on every request, and warns if `session.secure` is off in production. - `onBooted` — pre-resolves both singletons so the `Session` facade can read them synchronously. > **Note** — `SessionProvider` registers only `SessionMiddleware`. CSRF protection > is a separate middleware you opt into — see [CSRF protection](#csrf-protection). ## Configuration Create `config/session.ts`. Use the `SessionConfig()` helper so every field stays type-checked while supplying the defaults: ```typescript // config/session.ts import { SessionConfig } from "@zerotal/session"; import { env } from "zerotal"; export default SessionConfig({ driver: "cookie", // 'cookie' | 'redis' lifetime: 86400, // seconds — 24 hours cookie: "zerotal_session", httpOnly: true, sameSite: "Lax", secure: env("APP_ENV") === "production", secret: env("APP_KEY", ""), // signs the session cookie }); ``` | Field | Required | Default | Description | | ---------- | -------- | ----------- | ------------------------------------------------------------ | | `driver` | no | `"cookie"` | Storage backend: `"cookie"` or `"redis"`. | | `lifetime` | no | `86400` | Session lifetime in seconds (24 hours). | | `cookie` | no | `"session"` | Name of the session cookie. | | `httpOnly` | no | `true` | Marks the session cookie HTTP-only (hidden from JS). | | `sameSite` | no | `"Lax"` | SameSite policy: `"Strict"`, `"Lax"`, or `"None"`. | | `secure` | no | `false` | Require HTTPS for the cookie. Turn on in production. | | `secret` | no | `""` | HMAC secret used to sign the cookie. Set this in production. | Add a signing secret to `.env`: ```env # .env APP_KEY=your-random-32-char-secret-here ``` > **Danger** — Without a strong `secret`, session cookies can be forged. The cookie > driver throws `SessionSecretMissingError` if constructed with an empty secret; > always set `APP_KEY` (or `session.secret`) before deploying. ## Basic usage `SessionMiddleware` attaches a `SessionManager` to every request. There are two ways to reach it: - **`ctx.session`** inside a route handler — the `SessionManager` lives on the request `HttpContext` (middleware receives the same context, so it's `ctx.session` there too). - **The `Session` facade** anywhere — controllers, services, jobs — without threading the context through. ```typescript // in a controller or service import { Session } from "@zerotal/session"; Session.set("locale", "fr"); const locale = Session.get("locale"); Session.flash("success", "Saved!"); ``` The facade resolves the current request's session via `RequestContext`, so it works in any code running during a request. It requires `SessionMiddleware` to be registered. Both `ctx.session` and `Session` expose the same methods (see the [reference](#session-api) below). ## Reading and writing ```typescript fragment // in a controller import type { HttpContext } from "zerotal"; async action(ctx: HttpContext) { // Write ctx.session.set("locale", "fr"); ctx.session.set("cart", [1, 2, 3]); // Read (returns unknown — cast to your type) const locale = ctx.session.get("locale") as string; const cart = ctx.session.get("cart") as number[]; // Check existence const hasLocale = ctx.session.has("locale"); // boolean // Read and remove in one call const once = ctx.session.pull("cart"); // Delete one key ctx.session.forget("locale"); // Wipe all session data ctx.session.flush(); // Return the current session ID const id = ctx.session.id(); } ``` Every request has a session, including the first one from a client that has no cookie yet, and every one from a client that never keeps cookies. `ctx.session.resumed()` tells them apart: it is `true` only when the request carried a session cookie the driver accepted, so the next request from the same client will bring the same ID. A session started on this request, or one whose ID was just [regenerated](#session-fixation-protection), is not resumed, and anything keyed on its ID for a later request to find will be missed. ## Flash data Flash stores a value for **one subsequent request only** — it is automatically swept after the next request. The canonical use case is POST-Redirect-GET status messages. ```typescript fragment // in a controller — survives exactly one redirect ctx.session.flash("success", "Post created!"); ctx.session.flash("errors", { title: ["Required"] }); // Or via the ctx shorthand (same thing): ctx.flash("success", "Post created!"); ctx.flash("errors", { title: ["Required"] }); // Or via the Session facade (anywhere — no context needed): Session.flash("success", "Post created!"); ``` Read on the next request: ```typescript fragment // in a controller const msg = ctx.flashed("success"); const errors = ctx.flashed>("errors"); ``` Full POST-Redirect-GET pattern: ```typescript fragment // in a controller async store(ctx: HttpContext) { await Post.create(await ctx.body()); ctx.flash("success", "Post published!"); ctx.redirect("/posts", 303); // 303 ensures the browser GETs the redirect } async index(ctx: HttpContext) { const success = ctx.flashed("success"); // available here, gone after ctx.view(PostsPage, { success }); } ``` ## Session fixation protection Always regenerate the session ID after a privilege change (login, logout, password change) to prevent session-fixation attacks: ```typescript fragment // in a controller ctx.session.regenerate(); // issues a new session ID; data is preserved // or: Session.regenerate(); ``` > **Danger** — Skipping `regenerate()` on login lets an attacker who planted a > known session ID before authentication ride the now-privileged session. ## Session drivers | Driver | Notes | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `cookie` | Default. Session data is signed and stored in a browser cookie. No server storage needed. Max ~4 KB per session. | | `redis` | Session data stored in Redis by ID. Use when sessions are large, shared across cluster nodes, or need server-side invalidation. Requires a Redis URL. | ### Which driver should I use? - **`cookie`** — the default. Reach for it unless you outgrow it: it needs no infrastructure and keeps state with the client. - **`redis`** — switch when sessions exceed the ~4 KB cookie budget, must be shared across multiple nodes, or need to be invalidated server-side (e.g. force-logout). Switch drivers via the environment without changing application code: ```env # .env.production SESSION_DRIVER=redis SESSION_REDIS=redis://localhost:6379 ``` ```typescript // config/session.ts import { SessionConfig } from "@zerotal/session"; import { env } from "zerotal"; export default SessionConfig({ // One of 'cookie' | 'redis', written literally: the field is that union and // `env()` returns a plain string. driver: "cookie", // … }); ``` > **Note** — The redis driver reads its connection URL from the `session.redis` > config key (defaulting to `redis://localhost:6379`). Wire it from an env var as > shown above. ## CSRF protection `CsrfMiddleware` defends state-changing requests against cross-site request forgery. Unlike `SessionMiddleware`, it is **not** auto-registered — add it after the session middleware, typically in the `web` middleware group: ```typescript fragment // bootstrap/app.ts (or wherever you register middleware) import { SessionMiddleware, CsrfMiddleware } from "@zerotal/session"; app.use([SessionMiddleware, CsrfMiddleware]); // In production over HTTPS, mark the XSRF cookie Secure: // app.use([SessionMiddleware, CsrfMiddleware.with({ secure: true })]); ``` On its first request the middleware stores a random token in the session. On any unsafe method (anything other than `GET`, `HEAD`, `OPTIONS`) it compares — in constant time — the session token against the `x-csrf-token` or `x-xsrf-token` request header, returning **`419`** on a mismatch. After every request it also sets a non-HttpOnly `XSRF-TOKEN` cookie, so Axios (and therefore Inertia) reads it and replays it as the `X-XSRF-TOKEN` header automatically — no manual wiring for those clients. To expose the token elsewhere (HTML meta tag, Inertia shared props), read it with `CsrfMiddleware.token()`: ```typescript // in a controller or Inertia shared-props factory import { CsrfMiddleware } from "@zerotal/session"; const token = CsrfMiddleware.token(); // reads the active request's session ``` For a plain HTML form posting via `fetch`, surface the token in a meta tag and send it as a header: ```html ``` ```typescript fragment // in your client JS const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content"); fetch("/posts", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": token ?? "", }, body: JSON.stringify({ title: "Hello" }), }); ``` > **Warning** — The token is validated from a request **header**, not a `_token` > form field. A classic `
` with no JavaScript will not pass > the header, so submit through `fetch`/Axios (Inertia does this for you). ## Accessing the session outside a handler Use the **`Session` facade** — it reaches the current request's session through `RequestContext`, so service-layer code never has to thread `ctx` through: ```typescript // in a service import { Session } from "@zerotal/session"; function rememberLocale(locale: string) { Session.set("locale", locale); } function currentLocale(): string | undefined { return Session.get("locale"); } ``` This is the recommended approach for anything that isn't a route handler. If you need the raw `HttpContext` for other reasons, `RequestContext.tryGet()` (or `RequestContext.get()` to throw when absent) still gives it to you, but for the session itself prefer the facade. ## Authenticated sessions `AuthSessionMiddleware` extends `SessionMiddleware`: after loading the session it reads `session.get("user_id")`, looks the user up with a callback you supply, and attaches the result to `ctx.user` for the rest of the request. ```typescript fragment // bootstrap/app.ts import { AuthSessionMiddleware, CookieDriver } from "@zerotal/session"; import { env } from "zerotal"; import { User } from "../app/models/User.ts"; app.use( class extends AuthSessionMiddleware { constructor() { super(new CookieDriver(env("APP_KEY", "")), (id) => User.find(id)); } }, ); ``` ## Testing Pre-seed session data with `withSession()`, then assert on the response with `assertSessionHas()`: ```typescript fragment // in a test import { createTestApp } from "@zerotal/testing"; const res = await testApp.withSession({ locale: "fr", cart: [1, 2, 3] }).get("/checkout"); res.assertOk(); ``` ```typescript fragment // in a test const res = await testApp.post("/locale", { locale: "fr" }); res.assertSessionHas("locale"); res.assertSessionHas("locale", "fr"); ``` ```typescript fragment // in a test — assert a flash key was written before a redirect const res = await testApp.actingAs(user).post("/posts", { title: "Hello" }); res.assertRedirect("/posts"); res.assertSessionHas("success"); // flash key was written ``` ## References ### Session API In a handler the session is `ctx.session`; the `Session` facade exposes the same methods anywhere. The facade is generic (`Session.get(key)`), while `ctx.session.get` returns `unknown`. | Method | Signature | Description | | ------------------------------------------------------ | --------------------------------------- | ---------------------------------------- | | `ctx.session.get(key)` / `Session.get(key)` | `(key: string) => unknown` | Read a value (`undefined` if absent). | | `ctx.session.set(key, value)` / `Session.set(...)` | `(key: string, value: unknown) => void` | Write a value. | | `ctx.session.has(key)` / `Session.has(key)` | `(key: string) => boolean` | Check whether a key exists. | | `ctx.session.pull(key)` / `Session.pull(key)` | `(key: string) => unknown` | Read a value and remove it in one call. | | `ctx.session.forget(key)` / `Session.forget(key)` | `(key: string) => void` | Delete a key. | | `ctx.session.flush()` / `Session.flush()` | `() => void` | Delete all keys. | | `ctx.session.flash(key, value)` / `Session.flash(...)` | `(key: string, value: unknown) => void` | Write a one-request-only value. | | `ctx.session.regenerate()` / `Session.regenerate()` | `() => void` | Issue a new session ID (data preserved). | | `ctx.session.id()` / `Session.id()` | `() => string` | Return the current session ID. | | `ctx.session.resumed()` / `Session.resumed()` | `() => boolean` | Whether the client returned the session. | ### HttpContext helpers | Method | Signature | Description | | ----------------------- | --------------------------------------- | --------------------------------------------- | | `ctx.flash(key, value)` | `(key: string, value: unknown) => void` | Shorthand for `ctx.session.flash()`. | | `ctx.flashed(key)` | `(key: string) => T \| undefined` | Read a value flashed in the previous request. | ### CsrfMiddleware | Member | Signature | Description | | ---------------------------- | -------------------------------------------- | --------------------------------------------------- | | `CsrfMiddleware.token(ctx?)` | `(ctx?: HttpContext) => string \| undefined` | Read the current request's CSRF token from session. | | `CsrfMiddleware.with(opts)` | `(opts: { secure?: boolean }) => Middleware` | Configure the middleware (e.g. a `Secure` cookie). | ### Errors Session errors extend `SessionError`, which extends the framework's `ZerotalError`. Most surface at boot rather than per request — they are configuration faults, and failing loudly at startup beats silently losing sessions. | Error | Code | Raised when | | ---------------------------- | --------------------------- | ---------------------------------------------------------- | | `SessionError` | `E_SESSION` | Base class — catch this to handle any session failure. | | `SessionSecretMissingError` | `E_SESSION_SECRET_MISSING` | No `SESSION_SECRET` is configured. Raised at boot. | | `SessionDriverMissingError` | `E_SESSION_DRIVER_MISSING` | The configured driver name matches nothing registered. | | `SessionCookieOverflowError` | `E_SESSION_COOKIE_OVERFLOW` | The serialised session exceeds the 4 KB a cookie can hold. | `SessionCookieOverflowError` is the one you meet in real use. The `cookie` driver stores the whole session in the cookie itself, so a user object, or a long list of validation errors flashed back to a form, can push it past a hard browser limit. The check runs when the response is ready, after your handler has returned, so there is nothing to catch around `session.set()`. The error's message names the three biggest session keys and their sizes. In development and tests the request answers with the error. In production it is logged and the response goes out without the cookie, so nothing written to the session on that request (a flash, errors, old input) reaches the next one. The fix is nearly always to store an identifier rather than the object, or to move to a server-side driver where the cookie holds only the session id: ```typescript fragment // in a controller const reportId = crypto.randomUUID(); await Cache.set(`report:${reportId}`, hugeObject, 600); http.session.set("reportId", reportId); ``` ## Types `SessionDriver` is the storage contract — implement it to keep sessions somewhere the built-ins do not reach. `SessionPayload` is what a driver loads and saves: the id and the data bag. `SessionAccessor` is the request-scoped handle `ctx.session` exposes. ## Next steps - [Middleware](/docs/middleware) — where `SessionMiddleware` and `CsrfMiddleware` sit in the pipeline. - [HttpContext](/docs/context) — the `ctx` object that carries the session. - [Authentication](/docs/authentication) — build on regenerated, user-scoped sessions. - [Cookies](/docs/cookies) — the lower-level cookie API the cookie driver builds on. --- Source: https://zerotal.dev/docs/cookies # Cookies Most state you'd reach for cookies for is better handled by the [session](/docs/session) — it stores data in a **signed, `HttpOnly`** cookie for you. When you need to read or set a raw cookie directly, you work with the standard `Request`/`Response` headers on the [HTTP context](/docs/context). ## Which should I use? - **Session** — the default. User state, flash messages, anything sensitive or tamper-prone. The [session](/docs/session) driver signs and encrypts it for you. - **Raw cookie** — small, non-sensitive client preferences the browser must read too (a theme toggle, a dismissed-banner flag). Reach for the manual approach below only here. > **Danger** — A plain `Set-Cookie` value is fully client-visible and editable. > Zerotal signs the session cookie so it can't be tampered with; for a tamper-proof > value of your own, store it in the session or sign it yourself with > [`Url.sign`](/docs/encryption#signed-urls) or [encryption](/docs/encryption) rather > than trusting a raw cookie. ## Reading a cookie Cookies arrive in the request's `Cookie` header. Read and parse it from the context: ```ts fragment // in a controller import type { HttpContext } from "zerotal"; function readCookie(ctx: HttpContext, name: string): string | undefined { const header = ctx.request.headers.get("Cookie") ?? ""; for (const part of header.split(";")) { const [k, ...v] = part.trim().split("="); if (k === name) return decodeURIComponent(v.join("=")); } return undefined; } const theme = readCookie(ctx, "theme") ?? "light"; ``` ## Setting a cookie Set the response with a `ctx` helper, then append a `Set-Cookie` header to it. Use `append` (not `set`) so multiple cookies can be sent in one response: ```ts fragment // in a controller ctx.json({ ok: true }); // assigns ctx.response ctx.response!.headers.append( "Set-Cookie", `theme=dark; Path=/; Max-Age=${60 * 60 * 24 * 365}; SameSite=Lax`, ); ``` > **Note** — `ctx.json()` returns `void` — it sets `ctx.response` for you. Reach for > the response object via `ctx.response` after calling a response helper; don't > assign its return value. ### Recommended attributes | Attribute | Why | | ------------------- | ------------------------------------------------------------------ | | `Path=/` | Make the cookie apply site-wide. | | `HttpOnly` | Hide it from JavaScript — use for anything sensitive. | | `Secure` | Only send over HTTPS. Enable in production. | | `SameSite=Lax` | Sensible CSRF-resistant default; use `Strict` for extra isolation. | | `Max-Age=` | Lifetime. Omit for a session cookie that clears on browser close. | To **delete** a cookie, set it again with `Max-Age=0`: ```ts fragment // in a controller ctx.response!.headers.append("Set-Cookie", "theme=; Path=/; Max-Age=0"); ``` ## Framework-managed cookies You rarely set cookies by hand — two parts of the framework manage their own: - **Session cookie** — the [session](/docs/session) driver stores the whole session in a single cookie, **signed with HMAC-SHA256** and flagged `HttpOnly`, `SameSite=Lax` (and `Secure` in production). Its name (`cookie`) and lifetime (`lifetime`) come from `config/session.ts`. Put user state in the session rather than rolling your own signed cookie. - **`XSRF-TOKEN` cookie** — [`CsrfMiddleware`](/docs/csrf) sets this readable (non-`HttpOnly`) cookie after every request so Axios/Inertia can echo it back as the `X-XSRF-TOKEN` header. ## Types `CookieOptions` is what every cookie-setting call accepts — `maxAge`, `path`, `domain`, `httpOnly`, `secure`, `sameSite`. It is exported so a helper that sets a cookie in more than one place can take the same shape. ## Next steps - [Session](/docs/session) — signed, `HttpOnly` cookie-backed state (the usual choice). - [CSRF Protection](/docs/csrf) — the `XSRF-TOKEN` cookie. - [HTTP Context](/docs/context) — the request/response objects you read and write. - [Encryption](/docs/encryption) — sign or encrypt your own cookie values. --- Source: https://zerotal.dev/docs/csrf # CSRF Protection Cross-site request forgery (CSRF) protection ensures that mutating requests (POST/PUT/PATCH/DELETE) originate from your own app, not a malicious third-party page. Zerotal's `CsrfMiddleware` (from `@zerotal/session`) handles this with a per-session token and zero client config for Axios/Inertia. ```typescript // in a controller or middleware setup import { CsrfMiddleware } from "@zerotal/session"; ``` > **Note** — `CsrfMiddleware` ships inside `@zerotal/session`; if the > [session](/docs/session) package is already installed, there is nothing extra > to add. Otherwise run `bun add @zerotal/session`. ## Getting Started CSRF protection ships inside `@zerotal/session` — installing the session package is all it takes, and `SessionProvider` wires the middleware for you. ```typescript import { CsrfMiddleware } from "@zerotal/session"; ``` ## How it works 1. On the first request, the middleware generates a random token (`crypto.randomUUID()`) and stores it in the [session](/docs/session). 2. On every response it sets a readable `XSRF-TOKEN` cookie (non-`HttpOnly`, `SameSite=Lax`, `Path=/`). 3. On a **mutating** request it requires that token back in an `X-CSRF-TOKEN` or `X-XSRF-TOKEN` header, compared in constant time. 4. A missing or wrong token returns **419** (`{ "message": "CSRF token mismatch." }`). `GET`, `HEAD`, and `OPTIONS` are treated as safe and skip the check. Because the cookie is readable by JavaScript, **Axios and Inertia attach the `X-XSRF-TOKEN` header automatically** — first-party SPA forms work with no extra wiring. > **Danger** — The `XSRF-TOKEN` cookie intentionally omits the `HttpOnly` flag so > JavaScript can read it. This is by design (it carries no auth, only the CSRF > token), but never store a session secret or credential in a non-`HttpOnly` > cookie. ## Enabling it Register `CsrfMiddleware` **after** `SessionMiddleware` — it reads and writes the session. In production over HTTPS, set `secure: true` so the cookie carries the `Secure` flag: ```typescript fragment // bootstrap/app.ts import { SessionMiddleware, CsrfMiddleware } from "@zerotal/session"; app.use([ SessionMiddleware, CsrfMiddleware, // HTTP / development // CsrfMiddleware.with({ secure: true }) // HTTPS / production ]); ``` `CsrfMiddleware.with({ ... })` returns a zero-argument middleware class with your options baked in, so it drops straight into the `app.use([...])` array. | Option | Required | Default | Description | | -------- | -------- | ------- | ------------------------------------------------- | | `secure` | no | `false` | Add the `Secure` flag to the `XSRF-TOKEN` cookie. | > **Warning** — Register `CsrfMiddleware` after `SessionMiddleware`. Without an > active session the token has nowhere to live and every mutating request fails > with a 419. ## Submitting the token ### Axios / Inertia No work needed — the `XSRF-TOKEN` cookie is read and sent back as `X-XSRF-TOKEN` on every mutating request. ### Manual fetch / classic forms Expose the token server-side and send it in the header (or a hidden field your handler reads). `CsrfMiddleware.token()` returns the current session's token: ```typescript fragment // in an Inertia shared-props factory import { CsrfMiddleware } from "@zerotal/session"; Inertia.share({ csrf_token: () => CsrfMiddleware.token() }); // …or embed it in an HTML meta tag for a classic page: // ``` ```typescript fragment // client-side fetch await fetch("/posts", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content, }, body: JSON.stringify(data), }); ``` > **Tip** — `CsrfMiddleware.token()` defaults to the active request context, so it > works inside a no-argument shared-prop factory. Pass an explicit `HttpContext` > only when you call it outside the in-flight request. ## Which approach should I use? - **Axios or Inertia SPA** — do nothing. The cookie-to-header round trip is automatic; the token is never your concern. - **Hand-written `fetch` or a classic server-rendered form** — expose the token with `CsrfMiddleware.token()` (meta tag or shared prop) and send it back in the `X-CSRF-TOKEN` header or a hidden field. - **Stateless bearer-token API** — skip CSRF entirely (see below). ## Pure-API routes CSRF protection guards **session-cookie** auth. Stateless APIs authenticated with [bearer tokens](/docs/authentication#api-token-authentication) don't need it — a token in the `Authorization` header can't be sent ambiently by a browser. Apply `CsrfMiddleware` to your web/session routes and leave it off bearer-token API groups. ## Testing Set your suite up once as described in [Testing](/docs/testing). CSRF protection is the rare feature whose test is mostly about proving a request **fails**. **A rejected request is `419`, not `403`.** That status is specific enough to be worth asserting by number — a `403` in this test means your authorization denied the request and CSRF never ran: ```typescript fragment // tests/http/csrf.test.ts import { test } from "bun:test"; import { createApp } from "../helpers.ts"; test("an unsafe request without a token is refused", async () => { const app = await createApp(); const res = await app.post("/posts", { title: "Hello" }); res.assertStatus(419); await app.close(); }); ``` **Safe methods are exempt**, so a `GET` proves nothing about your CSRF setup. If that is the only request in the test, the middleware could be absent entirely and the suite would stay green: ```typescript fragment // tests/http/csrf.test.ts test("GET is never challenged", async () => { (await app.get("/posts")).assertOk(); // passes with or without CSRF — not a CSRF test }); ``` To test the **success** path, seed the session with a token you choose and send the same value on the header the middleware reads: ```typescript fragment // tests/http/csrf.test.ts const token = "test-csrf-token"; const res = await app .withSession({ _csrf_token: token }) .post("/posts", { title: "Hello" }, { "X-CSRF-Token": token }); res.assertCreated(); ``` The middleware accepts either `X-CSRF-Token` or `X-XSRF-Token`, and stores the value under the `_csrf_token` session key — seeding it directly is both simpler and less brittle than scraping the token out of a rendered form. > **Note** — Exempting a route (a webhook receiver, say) is worth a test of its > own asserting the request succeeds _without_ a token. That is the one case > where a missing-token request passing is the correct outcome, and it should be > deliberate rather than accidental. ## References | Member | Signature | Description | | ---------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------- | | `CsrfMiddleware` | `class CsrfMiddleware extends BaseMiddleware` | Validates the token on mutating requests and sets the `XSRF-TOKEN` cookie. | | `.with()` | `static with(options: Partial): new () => CsrfMiddleware` | Bake `secure` into a zero-arg middleware class for `app.use([...])`. | | `.token()` | `static token(ctx?: HttpContext): string \| undefined` | Read the current request's CSRF token; defaults to the active context. | | `CsrfOptions` | `{ secure?: boolean }` | Options accepted by `.with()`. | ## Next steps - [Session](/docs/session) — where the CSRF token is stored. - [Cookies](/docs/cookies) — the `XSRF-TOKEN` and session cookies. - [Authentication](/docs/authentication) — session vs. bearer-token auth. - [Middleware](/docs/middleware) — how `CsrfMiddleware` runs in the pipeline. --- Source: https://zerotal.dev/docs/errors # Error Handling Zerotal centralises error handling through an `ExceptionHandler` class: every unhandled exception flows through it, and the framework picks the response format automatically based on the client type (browser vs. API) and the environment (dev vs. production). ## Default behaviour In development, an unhandled error shows a styled stack-trace page in the browser and a JSON body for API clients. In production, the browser sees a plain "Internal Server Error" page and API clients get `{ message: 'Internal Server Error' }` — no internals are leaked. HTTP errors (`NotFoundError`, `ForbiddenError`, etc.) always produce a status-code-appropriate response regardless of environment. > **Note** — The client type is decided by the `Accept` header. A request whose > `Accept` prefers `application/json` to `text/html` gets JSON, with or without > `X-Inertia`: a higher q-value, or the same q-value and listed first, so > `application/json, text/html` gets JSON and `text/html, application/json` does not. > Otherwise anything that includes `text/html` (regular browsers and Inertia visits) > gets the HTML page. [Validation](/docs/validator) makes the same choice between a > 422 and a redirect. ## Built-in HTTP errors Throw any of these from a controller, middleware, or model and the framework turns it into the correct HTTP response automatically. Each carries a default message and a stable `code`: ```typescript // in a controller import { NotFoundError, ForbiddenError, UnauthorizedError } from "zerotal"; // 404 throw new NotFoundError(); throw new NotFoundError("Article not found"); // 403 throw new ForbiddenError(); throw new ForbiddenError("You cannot edit this post"); // 401 throw new UnauthorizedError(); ``` For any other status, throw `HttpError` directly: ```typescript // in a controller import { HttpError } from "zerotal"; throw new HttpError("Payment required", 402, "E_PAYMENT_REQUIRED"); ``` The constructor is `new HttpError(message, status, code?, headers?)` — when you omit `code` it defaults to `E_HTTP_`. The full set exported from `zerotal`: | Class | Status | Default `code` | | -------------------------- | ------ | ------------------------ | | `BadRequestError` | 400 | `E_BAD_REQUEST` | | `UnauthorizedError` | 401 | `E_UNAUTHORIZED` | | `ForbiddenError` | 403 | `E_FORBIDDEN` | | `NotFoundError` | 404 | `E_NOT_FOUND` | | `MethodNotAllowedError` | 405 | `E_METHOD_NOT_ALLOWED` | | `ConflictError` | 409 | `E_CONFLICT` | | `GoneError` | 410 | `E_GONE` | | `UnprocessableEntityError` | 422 | `E_UNPROCESSABLE_ENTITY` | | `TooManyRequestsError` | 429 | `E_TOO_MANY_REQUESTS` | | `ServiceUnavailableError` | 503 | `E_SERVICE_UNAVAILABLE` | > **Tip** — `MethodNotAllowedError(allowed)`, `TooManyRequestsError(retryAfter)`, > and `ServiceUnavailableError(reason, retryAfter)` populate the `Allow` and > `Retry-After` response headers for you when you pass those arguments. ## Errors the framework raises The errors above are the ones you throw. These the framework throws at you, and each is written to name the fix rather than only the symptom. Most surface at boot, before a request is ever served: | Class | `code` | Raised when | | ---------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `BootCheckError` | `E_BOOT_CHECK_FAILED` | The boot-time doctor found one or more wiring problems. | | `ConfigValidationError` | `E_CONFIG_VALIDATION_FAILED` | Config validation refused a production boot, listing every fatal issue by namespace. | | `FacadeBindingMissingError` | `E_FACADE_BEFORE_BOOT` | A facade was used after boot but nothing provides its binding — almost always a `ServiceProvider` missing from `bootstrap/providers.ts`. | | `ContextOutsideRequestError` | `E_CONTEXT_OUTSIDE_REQUEST` | `RequestContext` was read with no request in scope, such as from module-level code or a background task. Renders as a 500. | `BootCheckError` carries the whole list rather than the first failure it hit. Its `failures` array holds one `BootCheckFailure` per culprit — the `token`, the `provider` that declared it in `static provides`, and the `reason` — so a single restart tells you everything there is to fix. These four are not re-exported from `zerotal`, because throwing them yourself is not the point. Catch one by class from `@zerotal/core/errors`, or match on `code` the way you would any other framework error. ## Custom exception classes Extend `ZerotalError` for domain errors, or `HttpError` for HTTP errors. The `ZerotalError` constructor is `(message, code, status = 500, context?)`: ```typescript // app/exceptions/PaymentFailedError.ts import { ZerotalError, HttpError } from "zerotal"; // Domain error — pass status 402 as the third argument export class PaymentFailedError extends ZerotalError { constructor(public readonly chargeId: string) { super(`Payment failed for charge ${chargeId}`, "E_PAYMENT_FAILED", 402); } } // HTTP shortcut — HttpError takes (message, status, code?) export class QuotaExceededError extends HttpError { constructor() { super("Quota exceeded", 429, "E_QUOTA_EXCEEDED"); } } ``` ```typescript fragment // in a controller throw new PaymentFailedError(charge.id); ``` ## Custom exception handler Create a handler in `app/exceptions/Handler.ts` extending `ExceptionHandler`, then register it in `bootstrap/app.ts` with `app.withExceptionHandler(Handler)`. The framework calls `report()` first, then `render()`, for every unhandled exception: ```typescript fragment // app/exceptions/Handler.ts import { ExceptionHandler, NotFoundError, ForbiddenError } from "zerotal"; import type { HttpContext } from "zerotal"; import { PaymentFailedError } from "./PaymentFailedError.ts"; export class Handler extends ExceptionHandler { // report() runs first — use it to log to Sentry, Datadog, etc. override async report(err: unknown, ctx?: HttpContext): Promise { if (err instanceof NotFoundError) return; // skip expected errors if (err instanceof ForbiddenError) return; await Sentry.captureException(err, { extra: { path: ctx?.path() } }); // Call super to keep the default console logging. await super.report(err, ctx); } // render() turns an error into a Response. override async render(err: unknown, ctx: HttpContext): Promise { if (err instanceof PaymentFailedError) { if (ctx.wantsJson()) { return Response.json({ message: err.message, chargeId: err.chargeId }, { status: 402 }); } ctx.flash("error", "Your payment could not be processed."); return new Response(null, { status: 303, headers: { Location: "/billing" } }); } // Fall back to the framework default for everything you don't handle. return super.render(err, ctx); } } ``` ```typescript fragment // bootstrap/app.ts import { Application } from "zerotal"; import providers from "./providers.ts"; import { Handler } from "../app/exceptions/Handler.ts"; export default Application.create({ providers }).withExceptionHandler(Handler); ``` > **Warning** — Always call `super.render(err, ctx)` as the final fallback. If you > forget it, any error your `render()` doesn't explicitly handle falls through > without a response. ## Silencing expected errors `report()` is for errors you want tracked externally. Errors that are normal user behaviour (404, 403, validation) should not page anyone. The base handler already silences the ones the framework raises to answer the client: every `HttpError` below 500 (a `ForbiddenError`, a `ConflictError`, a `NotFoundError`), whatever `abort()` throws with a 4xx, and by name `ValidationRedirectError`, `ValidationJsonError`, `ValidationError` and `PrecognitionResponse`. They never reach `console.error`. An error that only repeats a status from somewhere else is still reported. An `HttpClientError` thrown by `.throw()` on a 401 from an upstream API is answered with a 401, but the request did not refuse anyone: something it depends on failed. The same goes for an API client's or an AI provider's error, and for any other error you give a `status` of your own. Throw an `HttpError`, or call `abort()`, when the 4xx is the answer you mean to give. That means the framework's `HttpError` or a subclass of it: a class of your own that is only named `HttpError` is reported like any other error. To silence your own classes, list them on the `dontReport` array instead of filtering by hand: ```typescript fragment // app/exceptions/Handler.ts import { ExceptionHandler } from "zerotal"; import { CardDeclinedError } from "./CardDeclinedError.ts"; import { PaymentFailedError } from "./PaymentFailedError.ts"; export class Handler extends ExceptionHandler { protected override dontReport = [CardDeclinedError, PaymentFailedError]; } ``` > **Tip** — Prefer `dontReport` over a manual `instanceof` chain in `report()`. > The base `report()` checks it for you, so any error whose class (or class name) > is in the silent list is skipped before logging. ## Response format by client type The base handler negotiates the response from the `Accept` header and the environment: | Situation | Browser | API client (`Accept: application/json`) | | ---------------------- | ----------------------------- | ----------------------------------------------------- | | `NotFoundError` | Styled 404 HTML page | `{ message: 'Not Found', code: 'E_NOT_FOUND' }` | | `ForbiddenError` | Styled 403 HTML page | `{ message: 'Forbidden', code: 'E_FORBIDDEN' }` | | Unhandled error (dev) | Full stack-trace page | `{ message: '...', code: 'E_INTERNAL' }` | | Unhandled error (prod) | "Internal Server Error" page | `{ message: 'Internal Server Error' }` | | `ValidationError` | 303 redirect + flashed errors | `{ message: 'Validation failed', errors: {...} }` 422 | ## Validation errors The validation system throws automatically — you don't catch anything. It throws `ValidationRedirectError` (a 303 redirect for browser clients) or `ValidationJsonError` (a 422 JSON body for API clients), and both flow straight through the handler: ```typescript fragment // in a controller // Browser → 303 redirect back with flashed errors // API → 422 JSON: { message: 'Validation failed', errors: {...} } const data = await StorePostRequest.validate(); ``` A check the validator cannot make, such as one that needs the database, can throw `ValidationError` from `@zerotal/core/errors` and get the same answer. A client whose `Accept` prefers JSON gets a `422` with your message and every message per field. Anything else, a request with no `Accept` included, is redirected back with the first message per field flashed as `errors` and the submitted body as `old`: ```typescript fragment // in a controller import { ValidationError } from "@zerotal/core/errors"; if (await User.where("email", email).exists()) { throw new ValidationError("That address is taken", { email: ["is already registered"] }); } ``` See the [Validator](/docs/validator) guide for details. ## Error codes Every `ZerotalError` carries a machine-readable `code` string alongside the HTTP `status`. Use it on the client to distinguish errors that share a status: ```typescript fragment // the API client receives: // { "message": "Payment failed for charge ch_xxx", "code": "E_PAYMENT_FAILED" } if (error.code === "E_PAYMENT_FAILED") { showPaymentFailedUI(error.chargeId); } ``` ## afterResponse and errors Errors thrown inside `ctx.afterResponse()` callbacks are logged but never sent to the client — the response has already been delivered by the time these fire, so a failing callback can't crash the request. ## The development error page, and diagnoses Outside production, an unhandled error renders a full-page overlay: the message, the stack split into application and framework frames, source context around the failing line, the request, and a **Copy for AI** button that puts the whole thing on the clipboard as Markdown. Some errors are exact about _what_ happened and useless about _what to do_. `no such table: assets` is the canonical one — the message is precise, and every frame in the stack is inside the SQL driver, because that is where the failure surfaced rather than where it came from. The answer is somewhere else entirely: you have migrations you have not run. So a package that owns an error class can contribute a **diagnosis**, rendered above the stack. ### Missing tables and columns `@zerotal/orm` registers one. When a query fails because a table or column does not exist, the overlay checks the migration state and answers one of two ways: - **Migrations are pending** — it names them and offers a **Run migrations** button. Pressing it runs exactly what `bun zt migrate` would, then reloads the page. - **Nothing is pending** — it offers **no button**, because running every pending migration when there are none changes nothing and leaves you back where you started. Instead it says whether any migration on disk so much as mentions the missing name: if none does, the migration that would create it was probably never written. It works on SQLite, PostgreSQL and MySQL — matched on the driver's error code where there is one (`42P01`, `42703`, `1146`, `1054`) and on the message otherwise. `bun zt doctor` asks the same question before anything breaks, and warns when migrations are pending — see [Migrations](/docs/migrations#running-migrations). The overlay is reactive by nature: it needs a request to have already failed, which means somebody has already lost the thread of what they were doing. > **The button exists only in development.** The endpoint behind it refuses unless [`devSurfacesEnabled()`](/docs/deployment) is true, and that gate **fails closed**: an unset `APP_ENV` does not qualify. The route is not even registered otherwise. > > It also requires a single-use token minted into the page, and passes the same origin check the WebSocket endpoints use. A dev server on `localhost:3000` is reachable by any site you have open in another tab, and "run every pending migration" is not something a random page should be able to trigger. ### Writing your own `registerErrorDiagnoser` takes a function that either recognises an error or returns `null`. Register it from a provider's `onRegister()`: ```typescript import { registerErrorDiagnoser } from "zerotal"; registerErrorDiagnoser((error) => { if (!/ECONNREFUSED .*:6379/.test(error.message)) return null; return { title: "Redis refused the connection.", detail: "The cache and queue drivers are both configured to use it. Start it with `docker compose up redis`, or switch `cache.driver` to `memory` while you work.", items: ["cache.driver = redis", "queue.driver = redis"], }; }); ``` The function is an `ErrorDiagnoser`, and what it returns is an `ErrorDiagnosis`. Diagnosers run in registration order and the **first** one to return a result wins, so recognise only errors you genuinely own — a diagnoser that claims an error it cannot explain replaces a real stack trace with a wrong answer. One that throws is skipped rather than taking the error page down with it. | Field | Meaning | | -------- | ------------------------------------------------------------------- | | `title` | One line: what is actually wrong. | | `detail` | A short paragraph: why, and what to do. | | `items` | Supporting specifics — file names, config keys. Rendered as a list. | | `action` | A button. See below. | An `action` is a `DiagnosisAction`: a `label`, a same-origin `url` to `POST` to, a `token`, and an optional `pendingLabel`. > **An `action` changes server state from a page rendered by a GET.** Whoever registers the endpoint owns its safety, and the type only carries the values to the page. The endpoint must refuse outside development _on its own terms_ rather than trusting that the overlay is dev-only, require the token, and check the origin. If you cannot do all three, ship the diagnosis without a button — a `title` and `detail` that name the fix are most of the value. Offer a button only when you are confident it helps. A button that runs and changes nothing is worse than no button, because it teaches people not to trust the panel. ## References `ExceptionHandler` is the class you subclass; the named errors are exported from `zerotal`. | Member | Signature | Description | | -------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `report` | `report(err: unknown, ctx?: HttpContext): Promise` | Called first; log or forward the error. Override to add tracking. | | `render` | `render(err: unknown, ctx: HttpContext): Promise` | Turns an error into a `Response`. Override per error class, call `super`. | | `dontReport` | `protected dontReport: Array unknown>` | Error classes to skip in `report()`. | | `ZerotalError` | `new ZerotalError(message, code, status = 500, context?)` | Base framework error with a `code`, `status`, and optional `context`. | | `HttpError` | `new HttpError(message, status, code?, headers?)` | Error mapped directly onto an HTTP response; `code` defaults to `E_HTTP_`. | | Method (on `HttpContext`) | Signature | Description | | ------------------------- | ------------------------- | --------------------------------------------------------- | | `wantsJson` | `wantsJson(): boolean` | `true` when the client expects a JSON response. | | `path` | `path(): string` | The request path, handy for error context. | | `flash` | `flash(key, value): void` | Stash data for the next request (e.g. before a redirect). | ## Next steps - [Validator](/docs/validator) — the validation errors that flow through the handler. - [Logger](/docs/logger) — where `report()` writes by default. - [HTTP context](/docs/context) — the `ctx` passed to `report()` and `render()`. - [Telemetry](/docs/telemetry) — forward reported errors to an external tracker. --- Source: https://zerotal.dev/docs/logger # Logger `zerotal/logger` is Zerotal's structured logger. It gives you a multi-channel `LogManager` (console, file, daily-rotating, stack, null), a global `Log` facade you can call anywhere, HTTP access logging via `LoggerMiddleware`, and automatic logging of framework signals (slow queries, N+1, failed jobs, auth events, request errors) by subscribing to the [FrameworkEvents](/docs/events) instrumentation bus. ## Getting Started The logger ships as part of `@zerotal/core` — there is nothing extra to install. Import it from the `zerotal/logger` subpath: ```ts import { Log, LogProvider } from "zerotal/logger"; ``` ## Register the provider Add `LogProvider` to the providers array in `bootstrap/providers.ts`: ```ts // bootstrap/providers.ts import { LogProvider } from "zerotal/logger"; const providers = [ // …your other providers LogProvider, ]; export default providers; ``` Registering the provider switches on the following, in lifecycle order: - `onRegister` — binds the `LogManager` under the `log` container token as a lazy singleton. - `onBooting` — wires the singleton into `LoggerMiddleware` (`setManager`) and registers it via `app.useOnce()`, so request access logging is active with no manual `.use()`. - `onBooted` — subscribes to the [FrameworkEvents](/docs/events) bus (slow queries, N+1, failed jobs, scheduled tasks, auth events, request errors). - `onStopping` — unsubscribes every handler, so nothing leaks between boots or test suites. > **Note** — `LogProvider` runs in every environment (`web`, `console`, > `worker`, `test`, `repl`), so `Log` is available in HTTP requests, commands, > queue workers, and the REPL alike. ## Where logs go by default Two places, always, with no config file at all: - **The terminal**, so you can watch what is happening. - **A dated file** — `storage/logs/YYYY-MM-DD.log`, one per day, kept for 14 days. They are independent on purpose. Quietening the terminal must not cost you the record, because the record is what you read after the process exited, after the scrollback rolled over, on a machine nobody was watching. Both are properties of the logger rather than channels you route to, so pointing `default` at a file channel no longer silences your terminal. > **Note** — The file trail is off when `APP_ENV=test`. The path is relative to > the working directory, so a suite that boots an app would otherwise grow a > `storage/logs` directory wherever it happened to run. Ask for it explicitly > (`file: { path: "./tmp/logs" }`) if a test needs it. ## Configuration Create `config/logging.ts` and use the `LoggingConfig()` helper, which deep-merges your options over the defaults so you only specify what you change: ```ts // config/logging.ts import { LoggingConfig } from "zerotal/logger"; export default LoggingConfig({ // Quiet terminal, full trail on disk, a month of history. console: { level: "warn" }, file: { days: 30 }, }); ``` | Field | Required | Default | Description | | ------------- | -------- | ------------------------- | ------------------------------------------------------------------ | | `console` | no | `{ format: "pretty" }` | The terminal sink. `false` silences it. | | `file` | no | `./storage/logs`, 14 days | The dated file trail. `false` turns it off. | | `default` | no | `"app"` | Name of the channel that `Log.info()` (and friends) also write to. | | `channels` | no | `{}` | Named map of extra destinations, discriminated by `driver`. | | `slowQueryMs` | no | `1000` | Queries slower than this (ms) are auto-logged at `warn`. | ### The two sinks ```ts fragment // config/logging.ts export default LoggingConfig({ console: { level: "info", format: "json" }, // or false file: { path: "./var/log/app", days: 30, level: "debug" }, // or false }); ``` `console` takes `level` (default `debug`) and `format` (`"pretty"` or `"json"`). `file` takes `path`, `days`, and `level` — which also defaults to `debug`, so the trail records everything even when the console is filtered. That asymmetry is the point: you decide what to _watch_ without deciding what to _keep_. Turning the file off is reasonable in a container that ships stdout to a collector: ```ts fragment // config/logging.ts export default LoggingConfig({ file: false }); ``` ### Named channels Channels are _extra_ destinations layered on top of the two sinks, for routing a subsystem somewhere specific: ```ts fragment // config/logging.ts export default LoggingConfig({ channels: { audit: { driver: "daily", path: "./storage/logs/audit", days: 90 }, }, }); // elsewhere Log.channel("audit").info("permission granted", { userId, ability }); ``` An entry routed to a channel still reaches the console and the trail — with one exception that keeps output honest: a channel that already covers a sink suppresses that baseline for its own entries. A `console` channel does not print twice; a `single`/`daily` channel does not write the same entry to two files. A `stack` inherits the coverage of its members. `null` is not an exception. It discards its own writes; it does not suppress the record. ## Channel drivers Each channel is a `{ driver: … }` entry under `channels`, discriminated by its `driver` field: | Driver | Config fields | Behaviour | | --------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `console` | `level?`, `format?` | Writes to `process.stdout`. `format: 'pretty'` (default) for coloured terminal lines; `format: 'json'` for one JSON object per line. | | `single` | `level?`, `path` | Appends JSON lines to one file at `path`. Creates parent directories as needed; write errors are swallowed. | | `daily` | `level?`, `path`, `days?` | One date-stamped JSON file (`YYYY-MM-DD.log`) per day under `path/`. When `days` is set, files older than that many days are pruned. | | `stack` | `level?`, `channels` | Fan-out: each entry is written to every listed child channel simultaneously. | | `null` | — | Discards everything. Use in test environments. | > **Warning** — The `daily` driver only prunes old files when you set `days`. Omit > `days` and files accumulate indefinitely. A `stack` referencing an unknown child > channel throws at construction time. ### Switching destinations per environment The two sinks already cover the common case, so this is for the extras: ```ts fragment // config/logging.ts export default LoggingConfig({ // Machine-readable terminal output in production, human-readable locally. console: { format: process.env.APP_ENV === "production" ? "json" : "pretty" }, // Keep a year of audit history in production only. ...(process.env.APP_ENV === "production" ? { channels: { audit: { driver: "daily", path: "./storage/logs/audit", days: 365 } } } : {}), }); ``` ### Writing your own channel A channel is one method. Implement `LogChannel` and register it as a driver when the five built-ins do not reach where you need entries to go — a hosted log service, a socket, a table: ```typescript import type { LogChannel, LogEntry } from "zerotal/logger"; class WebhookChannel implements LogChannel { constructor(private readonly url: string) {} async write(entry: LogEntry): Promise { // Failures are swallowed on purpose: a logging sink that throws turns a // warning into an outage, and the entry it was carrying is lost either way. await fetch(this.url, { method: "POST", body: JSON.stringify(entry) }).catch(() => {}); } } ``` The built-ins implement the same interface and are exported, so a custom channel can wrap one rather than reimplement it — `StackChannel` is itself only a fan-out over other channels. ### Types | Type | What it is | | --------------- | ------------------------------------------------------------------------------ | | `LogLevel` | `"debug" \| "info" \| "warn" \| "error" \| "fatal"` — the severity ladder. | | `LogEntry` | One record: level, message, context, scope, timestamp, and any captured error. | | `LogChannel` | The one-method sink contract: `write(entry): Promise`. | | `BoundLogger` | A logger pinned to a channel and/or a fixed context bag. | | `ChannelConfig` | The discriminated union of the five driver configs below. | | `LoggerOptions` | What `LoggingConfig()` accepts. | | `TableData` | Rows for `Log.table()`. | The five built-in channels are exported under their own names — `ConsoleChannel`, `SingleChannel`, `DailyChannel`, `StackChannel`, `NullChannel` — each matching the `driver` value in the table above. ## The Log facade `Log` is a static proxy over the `LogManager` singleton. Use it anywhere — controllers, services, commands, event listeners: ```ts fragment // in a controller or service import { Log } from "zerotal/logger"; Log.debug("User lookup started", { userId: 42 }); Log.info("Order created", { orderId: order.id, total: order.total }); Log.warn("Rate limit close", { ip, remaining: 2 }); Log.error("Payment failed", { orderId }, err); Log.fatal("Database unreachable", { host: dbHost }, err); ``` Every level shares the same signature: ```ts fragment // signature — all five levels Log.info(message: string, context?: Record, err?: unknown): void ``` - `context` — arbitrary key/value data merged into the structured log entry. - `err` — an `Error` instance (message + stack captured) or any value (stringified). ## Targeting a specific channel `Log.channel(name)` returns a `BoundLogger` that writes to the named channel instead of the configured default: ```ts fragment // in a controller or service import { Log } from "zerotal/logger"; const auditLog = Log.channel("daily"); auditLog.info("Admin action", { adminId: user.id, action: "delete_user", targetId }); ``` This lets specific modules write to a dedicated channel without changing `default` for the whole application. ## Adding persistent context `Log.withContext(extra)` returns a `BoundLogger` (writing to the default channel) that merges `extra` into every entry. Useful in long-running jobs or to tag a group of log lines with a shared identifier: ```ts fragment // in a queue job import { Log } from "zerotal/logger"; const logger = Log.withContext({ jobId: job.id, queue: job.queue }); logger.info("Job started"); logger.warn("Retrying step", { step: "charge_card", attempt: 2 }); logger.info("Job finished", { durationMs }); // All three entries carry jobId and queue automatically ``` ## Scopes: which subsystem is talking `Log.scope(name)` returns a `BoundLogger` that tags every entry with the part of the system it came from. The console channel renders the tag as a padded column, so a boot log reads down the page instead of across it: ```text 01:27:48.682 INFO [APP] Application booted {"durationMs":486,"environment":"web","providers":2} 01:27:50.310 INFO [FLOW] Compiled 4 page(s), 2 from cache, 3 bind-injected, 8 using runtime 01:27:50.314 INFO [ROUTER] Registered 2 static asset routes {"dir":"…/public"} 01:27:50.320 INFO [APP] Server listening on http://localhost:3000 {"port":3000} ``` The tag is a real field, not decoration — file and JSON channels keep it as `scope`, so a log file can be filtered down to one subsystem. The framework uses this for its own output. Everything a running Zerotal app reports — boot, routing, the Flow compiler, the queue, the scheduler, page registry generation — is an ordinary log entry on your configured channels, at a level you can filter and in a file you can ship. Nothing writes to the terminal behind the logger's back, which means a `daily` channel captures the framework's own account of a boot, not just your application's. The one deliberate exception is the CLI itself. `zt dev`'s banner and its `[zerotal:dev]` build/restart lines come from the supervisor process that watches your files, not from the application, and they are interactive terminal output rather than a record of anything. They stay on stdout. ## How context is rendered On the console, context is written as `key=value` pairs rather than a JSON blob. The keys are dimmed so the values carry the eye, and strings stay exactly as you passed them: ```text 03:19:56.531 INFO [ROUTER] Registered 2 static asset routes dir=C:\Projects\app\public 03:19:56.537 INFO [APP] Server listening on http://localhost:3000 port=3000 ``` Literal strings matter more than they sound. `JSON.stringify` escapes every backslash, so the same line used to read `{"dir":"C:\\Projects\\app\\public"}` — a path you cannot copy, in a format that spends its width on punctuation. A value containing whitespace is quoted (`dir="C:\Program Files\app"`) so the pairs stay separable; nothing else is escaped. Nested objects and arrays fall back to compact JSON, which is what they are. When the pairs would run past the edge of your terminal, they fold onto a continuation line indented under the message instead: ```text 07:02:37.464 INFO [FLOW] Compiled 0 page(s), 0 from cache, 3 bind-injected, 8 using runtime ↳ compiled=0 cached=0 injected=3 runtime=8 ms=82 07:02:37.469 INFO [ROUTER] Registered 2 static asset routes dir=C:\Projects\app\public ``` A short bag stays on the message line — one event reading as one line is worth keeping. A long one is laid out here rather than left to the terminal, which would break it mid-pair at whatever column it ran out of room and bury the message it belongs to. Lines are filled greedily with whole pairs, so a `key=value` is never split across two of them, and only the first continuation carries the `↳`. The width comes from the terminal; piped or redirected output assumes a page. This applies to the console only. File and JSON channels are unchanged — they write the full `LogEntry` as one JSON line, which is what a collector wants. ## Tables: structured data you can actually read Past three or four keys, inline context stops being readable — `{"compiled":0,"cached":0,"injected":3,"runtime":8,"ms":124}` is a wall the eye slides off. `table()` logs the same data and asks the console to draw it in columns: ```ts fragment Log.table("Compile summary", { compiled: 0, cached: 2, injected: 3, runtime: 8, ms: 124 }); ``` ```text 02:03:19.263 INFO [FLOW] Compile summary ┌──────────┬─────┐ │ compiled │ 0 │ │ cached │ 2 │ │ injected │ 3 │ │ runtime │ 8 │ │ ms │ 124 │ └──────────┴─────┘ ``` Pass a list of objects instead and each key becomes a column, with a header. A third argument sets the level, which defaults to `info`: ```ts fragment Log.table( "Pages rendering through the runtime", [ { page: "ListsPage", blocker: " is a component", at: "lists.tsx:83:10" }, { page: "IndexPage", blocker: "key={d.href} is not static", at: "index.tsx:96:15" }, ], "warn", ); ``` ```text 02:03:19.263 WARN [FLOW] Pages rendering through the runtime ┌───────────┬────────────────────────────┬─────────────────┐ │ page │ blocker │ at │ ├───────────┼────────────────────────────┼─────────────────┤ │ ListsPage │ is a component │ lists.tsx:83:10 │ │ IndexPage │ key={d.href} is not static │ index.tsx:96:15 │ └───────────┴────────────────────────────┴─────────────────┘ ``` Numeric columns right-align so digits line up, a row missing a key gets a blank cell rather than shifting the table, and an over-long cell is truncated instead of wrapping into noise. Strings render literally, so a Windows path reads as `C:\Projects\app\public` rather than the double-escaped form `JSON.stringify` produces. The table is presentation only. The rows are ordinary context, so a `daily` or `single` channel writes exactly what any other level method would have written — a list ends up under a `rows` key — and a JSON collector never sees a box-drawing character. `renderTable(data)` is exported if you want the same lines somewhere other than a log. ## Log entry shape Every structured entry written by any channel has this shape: ```ts // zerotal/logger — LogEntry interface LogEntry { level: "debug" | "info" | "warn" | "error" | "fatal"; channel: string; scope?: string; // subsystem tag, e.g. "app", "flow", "queue" display?: "table"; // rendering hint for human-facing channels; ignored by JSON message: string; timestamp: string; // ISO 8601 app?: string; env?: string; hostname: string; pid: number; requestId?: string; // set automatically inside HTTP requests context?: Record; error?: string; stack?: string; } ``` `requestId` is populated automatically when the log call is made within a request context (i.e. inside a middleware or controller) — no manual threading required. ## Log levels Entries below a channel's configured `level` are silently dropped (a channel with no `level` defaults to `debug`, letting everything through): | Level | Numeric | Typical use | | ------- | ------- | ------------------------------------------------------ | | `debug` | 0 | Verbose diagnostic detail; development only | | `info` | 1 | Normal operational events | | `warn` | 2 | Recoverable issues, rate-limit proximity, slow queries | | `error` | 3 | Caught exceptions, request errors | | `fatal` | 4 | Unrecoverable failures, process about to exit | ## HTTP access logging `LoggerMiddleware` is registered automatically by `LogProvider`. It times every request, sets an `X-Request-Id` response header, and emits one line per request. By default it writes a coloured text line straight to `process.stdout`: ```text GET /posts ......................................... 200 42ms ``` Set the format to `json` (via the `LOG_FORMAT` env var) to route the entry through the configured `LogManager` channels instead, at `info`/`warn`/`error` by status: ```bash # in your project root LOG_FORMAT=json bun run start ``` > **Note** — In text mode the access line goes directly to stdout, not through the > default channel. Use `LOG_FORMAT=json` when you want request lines persisted to > your file/daily channels. To drop access logging entirely, omit `LogProvider` > and register your own middleware. ## Automatic framework signals Once `LogProvider.onBooted()` runs, it subscribes to the [FrameworkEvents](/docs/events) bus and logs these signals automatically: | Event | Level | Condition | | ----------------------- | -------------- | --------------------------------------------------- | | `QueryExecuted` | `warn` | Query duration ≥ `slowQueryMs` | | `NPlusOneDetected` | `warn` | An N+1 access pattern is detected | | `TransactionRolledBack` | `warn` | A database transaction is rolled back | | `MigrationRan` | `info`/`error` | A migration completes (or fails) | | `JobRan` | `warn`/`error` | A queued job is retried (`warn`) or fails (`error`) | | `MessageFailed` | `error` | A mail send fails | | `TaskRan` | `info`/`error` | A scheduled task ran (or failed its run) | | `TaskFailed` | `error` | A scheduled task throws | | `LoginSucceeded` | `info` | A user authenticates | | `LoginFailed` | `warn` | An authentication attempt fails | | `LoggedOut` | `info` | A user logs out | | `AuthorizationDenied` | `warn` | An ability check is denied | | `RequestHandled` | `warn`/`error` | A request returns a 4xx (`warn`) or 5xx (`error`) | | `RequestFailed` | `warn`/`error` | A thrown 4xx answer (`warn`) or fault (`error`) | A 4xx the framework throws to answer the client (a `ForbiddenError`, a `ConflictError`, an `abort(422)`) is logged as one warning that names the error, without a stack. Anything else is logged at `error` with the stack of the throw: a 5xx, and an error that only repeats an upstream status, such as an `HttpClientError` from a 401, even though the client is answered with that 4xx. [Silencing expected errors](/docs/errors#silencing-expected-errors) lists which errors count. A throw answered below 400 (a form's validation redirect, a passing precognition check) is not logged, as a returned 2xx or 3xx is not. > **Tip** — Requests to internal paths (`/__zerotal/`, `/__flow/`, `/__dev/`) > are skipped, so the dev tooling doesn't flood your logs. ## Testing Set your suite up once as described in [Testing](/docs/testing). Asserting on a log usually means asserting on a side-effect nobody else observes, so the logger gives you a tap. **`LogManager.tap()` receives every entry** after enrichment and before it reaches a channel, and returns an unsubscribe function: ```typescript fragment // tests/logging/AuditTrail.test.ts import { test, expect, afterEach } from "bun:test"; import { LogManager, type LogEntry } from "zerotal/logger"; let stop: (() => void) | undefined; afterEach(() => stop?.()); test("a failed charge is logged with the order id", async () => { const entries: LogEntry[] = []; stop = LogManager.tap((entry) => entries.push(entry)); await chargeOrder(order); // fails internally const failure = entries.find((e) => e.level === "error"); expect(failure?.message).toContain("Charge failed"); expect(failure?.context?.orderId).toBe(order.id); }); ``` **Unsubscribe in `afterEach`, not at the end of the test.** Taps are static and process-wide, so one left installed keeps collecting entries from every later test in the run — the array grows, the assertions get slower, and a `find()` starts matching something from a different test. **Silence the logger in the suite** so a passing run stays readable. The `null` driver discards everything: ```typescript fragment // tests/helpers.ts .useConfig({ logging: { default: "null", channels: { null: { driver: "null" } } }, }) ``` The tap still fires with `null` as the default channel — it runs before the channel write — so you get quiet output and assertable logs at the same time. > **Note** — Assert on `entry.context` rather than on the formatted message. > The message is prose and will be reworded; the context is structured data and > is what a log search actually queries. ## References `Log` and every `BoundLogger` returned by `channel()`/`withContext()` share the same surface: | Method | Signature | Description | | ------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `debug` | `(message: string, context?: Record, err?: unknown) => void` | Write a `debug`-level entry to the bound channel. | | `info` | `(message: string, context?: Record, err?: unknown) => void` | Write an `info`-level entry. | | `warn` | `(message: string, context?: Record, err?: unknown) => void` | Write a `warn`-level entry. | | `error` | `(message: string, context?: Record, err?: unknown) => void` | Write an `error`-level entry. | | `fatal` | `(message: string, context?: Record, err?: unknown) => void` | Write a `fatal`-level entry. | | `channel` | `(name: string) => BoundLogger` | Bind a logger to a specific channel (`Log` only). | | `withContext` | `(extra: Record) => BoundLogger` | Bind a logger that merges `extra` into every entry (`Log` only). | ## Next steps - [Events](/docs/events) — the FrameworkEvents bus the logger subscribes to. - [DevTools](/docs/devtools) — per-request log capture in the debug panel. - [Commands](/docs/commands) — using `Log` inside scheduled commands. - [Telemetry](/docs/telemetry) — distributed tracing alongside structured logs. --- Source: https://zerotal.dev/docs/view # View Zerotal's view layer is a JSX server-side rendering engine built into `@zerotal/core` — the same package that provides `ctx.view()`. It compiles JSX to plain HTML strings at request time: no virtual DOM, no hydration, and no client JavaScript unless you opt in. ## Getting Started The view runtime ships inside `@zerotal/core`, so there is no package to install or provider to register — you only point the TypeScript JSX transform at it. Set it once in `tsconfig.json` and every `.tsx` file in the project is covered: ```json // tsconfig.json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "zerotal" } } ``` Scaffolded projects already have this — `bun create zerotal` writes it into the template's `tsconfig.json`, so the JSX examples below compile as-is. ## Basic usage Components are plain TypeScript functions that return `SafeHtml`. Type them with `FC` for the standard `(props, children) => SafeHtml` shape: ```tsx // resources/views/Card.tsx import type { FC } from "zerotal/view"; interface CardProps { title: string; children?: unknown; } export const Card: FC = ({ title, children }) => (

{title}

{children}
); ``` All string children are HTML-escaped automatically. To embed pre-rendered HTML, use the [`safe()` helper or `Raw` component](#embedding-raw-html). > **Tip** — Prefer native HTML attribute names (`class`, `for`, `tabindex`, …). > React-style `className` and `htmlFor` are accepted and mapped to `class`/`for`, > but native names are idiomatic here. > **Warning** — SSR only, no client interactivity. The runtime emits plain HTML > strings; event-handler props like `onClick` are not serialized and are silently > dropped. For interactive UI, reach for [Flow](/docs/flow) (server-driven) > or [Inertia](/docs/inertia) (React/Vue) instead. ## Attributes The runtime renders attributes from props with a few rules: ```tsx fragment // in a component // → ``` - **Boolean `true`** renders the bare attribute (`disabled`); **`false`, `null`, and `undefined`** omit it entirely — ideal for conditional attributes. - Only **string** and **number** values are rendered as `key="value"` (both escaped). - `className` → `class` and `htmlFor` → `for` are mapped; every other key is used verbatim. - **No object values.** `style` must be a string (`style="color:red"`), not an object — non-string, non-number values are dropped. - `key` is ignored in output (it's a JSX hint, not an HTML attribute). ## How children render Children are rendered by type, which is the engine's security boundary: | Child value | Output | | --------------------------------------- | --------------------------------------- | | `SafeHtml` (from JSX / `safe()`) | Passed through unescaped | | `string` | **HTML-escaped** (treated as untrusted) | | `number` | Stringified (inert — no escaping) | | `true` / `false` / `null` / `undefined` | Renders nothing | | `Array` | Each item rendered and concatenated | Two consequences worth remembering: ```tsx fragment // in a component { user && ; } { /* false/null → nothing, so guards just work */ } { count; } { /* 0 renders "0" — numbers are never blank */ } ``` Void elements (`
`, ``, ``, `
`, ``, …) render without a closing tag automatically. ## Rendering in a controller Call `view()` from a controller action to set the response. It accepts any value whose `.toString()` returns HTML — a `SafeHtml` instance from JSX is the normal case: ```tsx fragment // app/controllers/PostController.tsx import { view } from "zerotal"; import type { HttpContext } from "zerotal"; import { Post } from "../models/Post.ts"; import { PostList } from "../resources/views/PostList.tsx"; export class PostController { async index(ctx: HttpContext) { const posts = await Post.query().latest().get(); view(); } } ``` ### Passing a component and props You can also hand `view()` (or `ctx.view()`) the **component itself** plus its props. The component receives the request `HttpContext` as its first argument and your props as its second; route params and model bindings reach it through `ctx.params`: ```tsx // resources/views/Welcome.tsx import type { HttpContext } from "zerotal"; export default function Welcome(ctx: HttpContext, { title }: { title: string }) { return (

{title}

{ctx.url.pathname}

); } ``` ```ts fragment // routes/index.ts — the HttpContext is injected; you only pass the extra props import { Router } from "zerotal"; import Welcome from "../resources/views/Welcome.tsx"; Router.get("/", () => view(Welcome, { title: "Welcome to Zerotal" })); ``` The component may be async — `view()` awaits it before setting the response. > **Warning** — JSX renders synchronously. A JSX expression evaluates to > `SafeHtml` right away, so components used inline (``) can't be > `async`. If you need to load data while rendering, use the component + props > form above (which awaits an async component), or do the loading in the > controller or a [`Router.view`](#controller-less-pages) props factory and pass > the resolved data in as props. ### Which view form should I use? | You have… | Use | | ------------------------------------------------------------- | --------------------------------------- | | Already-rendered JSX, data loaded synchronously | `view()` | | An async component, or want the `HttpContext`/params injected | `view(Page, props)` | | A page with no controller at all | [`Router.view`](#controller-less-pages) | | A page resolved from the filesystem | [File-based pages](#file-based-pages) | ## Layouts Bind a shared layout to page components so every page doesn't need to manually wrap its content. `defineLayout(Layout)` returns a `wrap(Page)` factory; the wrapped page merges the layout's props (minus `children`) with its own: ```tsx // resources/views/layouts/AppLayout.tsx interface AppLayoutProps { title: string; children?: unknown; } export function AppLayout({ title, children }: AppLayoutProps) { return ( {title} — My App {children} ); } ``` ```tsx fragment // resources/views/About.tsx import { defineLayout } from "zerotal/view"; import { AppLayout } from "./layouts/AppLayout.tsx"; const wrap = defineLayout(AppLayout); // AboutPage receives { title } (from AppLayout) merged with its own props export const AboutPage = wrap<{ heading: string }>(({ heading }) => (

{heading}

We build things.

)); ``` ```ts fragment // routes/index.ts import { Router } from "zerotal"; import { AboutPage } from "../resources/views/About.tsx"; Router.view("/about", AboutPage, { title: "About Us", heading: "Hello" }); ``` `Router.view()` calls the component and responds with the HTML string. ## Controller-less pages For server-rendered pages that don't need a controller, register the component directly with `Router.view()`. The third argument is the props — a **static object**, or a **per-request factory** that receives the `HttpContext` and may be async: ```ts fragment // routes/index.ts // Static props — evaluated once at registration (marketing / info pages): Router.view("/about", AboutPage, { title: "About Us" }); // Dynamic props — resolved per request, can be async: Router.view("/dashboard", DashboardPage, async (ctx) => ({ user: ctx.user, posts: await Post.query().where("user_id", ctx.user!.id).get(), })); // No props: Router.view("/privacy", PrivacyPage); ``` The returned registration is chainable: ```ts fragment // routes/index.ts Router.view("/terms", TermsPage) .name("terms") // name the route for url() generation .withLayout(AppLayout); // wrap the output in a layout component ``` ## File-based pages Server-rendered file-route pages are **opt-in**. Register the resolver before your routes are scanned — in `bootstrap/app.ts`, or a provider's `onRegister()`: ```ts // bootstrap/app.ts import { registerViewFileRouteResolver } from "@zerotal/core/view"; registerViewFileRouteResolver(); ``` That is what makes the two conventions below work: a page's default export is rendered to HTML rather than treated as a plain handler, and `_layout` files are discovered. Without it neither applies — the default export is registered as an ordinary file handler and `_layout` discovery is switched off. It is opt-in because it claims every `.tsx` route file's default export, which an app using file routes for plain handlers has not asked for, and because `_layout` discovery walks the directory tree for every scanned route. With it registered, a page file's **default export** becomes a `GET` route. The page is a function of `(http, params)` and may be async: ```tsx fragment // app/views/posts/[slug].tsx → GET /posts/:slug import type { HttpContext } from "zerotal"; import { Post } from "../../models/Post.ts"; export default async function PostPage(http: HttpContext, params: { slug: string }) { const post = await Post.query().where("slug", params.slug).firstOrFail(); return (

{post.title}

{post.excerpt}

); } // Optional — wrap every page in this directory with a layout: export { AppLayout as layout } from "../layouts/AppLayout.tsx"; ``` In a `.tsx`/`.jsx` file the default-exported function is detected as a page automatically. If your page lives in a plain `.ts` file, mark it with `definePage()` so the resolver recognizes it: ```ts // app/views/greet.ts import { definePage } from "zerotal/view"; export default definePage((http, params) => `

Hello ${params.name}

`); ``` ### Directory layouts — `_layout.tsx` With the resolver registered, a `_layout.tsx` beside your pages wraps every page in that directory and below. The nearest one wins, so a section can override the root: ```tsx fragment // app/views/_layout.tsx → wraps every page under app/views export default (http: HttpContext, { children }: { children?: unknown }) => ( {children} ); ``` ``` app/views/ _layout.tsx ← wraps everything below index.tsx admin/ _layout.tsx ← wraps only the admin pages users.tsx ``` It is read by its **default export** — the opposite of `_middleware.ts`, which is read by a named `middleware` export. Both refuse to boot on the other's spelling rather than silently applying nothing, so a mistake here is a startup error naming the file, not a page that quietly renders without its chrome. A page can opt out with `export const layout = null`, or override with `export { SomeLayout as layout }`. ## Embedding raw HTML When you have pre-rendered markup (e.g. from a Markdown renderer) use `safe()` or `` to bypass escaping: ```tsx fragment // in a component import { safe, Raw } from "zerotal/view"; // Option 1 — safe(): wrap a string as SafeHtml inline
{safe(markdownToHtml(post.body))}
// Option 2 — Raw component: composable, e.g. passed as a child
// Option 3 — dangerouslySetInnerHTML on an element (best for a single element)
``` `dangerouslySetInnerHTML` replaces the element's children entirely. > **Danger** — All three bypass escaping. Only pass HTML you trust or have > sanitized; rendering untrusted markup this way is an XSS hole. ## Escaping outside JSX `esc()` escapes a value for use in raw string templates, where automatic JSX escaping isn't available: ```ts fragment // in a helper import { esc } from "zerotal/view"; const snippet = `

Hello, ${esc(user.name)}!

`; ``` ## Fragments Use `Fragment` (or the `<>...` shorthand) to return multiple root elements: ```tsx // in a component import { Fragment } from "zerotal/view"; const Items = ({ items }: { items: string[] }) => ( <> {items.map((item) => (
  • {item}
  • ))} ); ``` ## Testing Set your suite up once as described in [Testing](/docs/testing). A view is a function returning a node that stringifies, so most of it tests without a server. **Render the component and assert on the string.** No request, no router, no browser: ```typescript fragment // tests/views/PostCard.test.ts import { test, expect } from "bun:test"; import { PostCard } from "../../resources/views/PostCard.tsx"; test("renders the title and author", () => { const html = String(PostCard({ post: { title: "Hello", author: "Jane" } })); expect(html).toContain("Hello"); expect(html).toContain("Jane"); }); ``` **Escaping is the test that matters.** Every view that renders user input has one job beyond looking right, and it is the job that becomes a security incident: ```typescript fragment // tests/views/PostCard.test.ts test("escapes markup in user-supplied text", () => { const html = String(PostCard({ post: { title: "" } })); expect(html).not.toContain(""); expect(html).toContain("<script>"); }); ``` Write the same test for anything passed through `safe()` or `` — those opt out of escaping deliberately, so the test documents that the value is trusted and fails if someone later routes user input into it. **Through a route, assert the rendered text** rather than the markup around it. `assertSee` survives a class rename; a full-HTML comparison does not: ```typescript fragment // tests/http/posts.test.ts const res = await app.get("/posts"); res.assertOk(); res.assertSee("Hello"); res.assertDontSee("Draft"); // unpublished posts stay hidden ``` > **Note** — `assertSee` matches anywhere in the body, so a short string can > match an attribute or a class name and pass for the wrong reason. Assert on > something distinctive enough to only appear in the content you mean. ## References ### Helpers | Export | Signature | Description | | ----------------- | -------------------------------------------------- | -------------------------------------------------------------------- | | `safe(html)` | `(html: string) => SafeHtml` | Wrap a trusted HTML string as `SafeHtml` so it isn't re-escaped. | | `Raw({ html })` | `(props: { html: string }) => SafeHtml` | Component form of `safe()` — composable as a child. | | `esc(value)` | `(value: unknown) => string` | Escape a value for raw string templates (not needed inside JSX). | | `Fragment` | `(props: { children?: unknown }) => SafeHtml` | Group multiple roots; `<>…` is shorthand. | | `defineLayout(L)` | `(Layout) => (Page) => Component` | Bind a layout to pages; returns a `wrap(Page)` factory. | | `definePage(fn)` | `(fn: (http, params) => SafeHtml \| string) => fn` | Mark a `(http, params)` function as a file-route page (`.ts` files). | ### Response and routing helpers | Member | Signature | Description | | ------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------- | | `view` | `view(markup, status?): void` | Set a pre-rendered view as the current response. | | `view` | `view(component, props?, status?): void \| Promise` | Render a component called with the `HttpContext` and your `props`. | | `Router.view` | `Router.view(path, component, props?, middleware?): ViewRegistration` | Register a controller-less GET route that renders a view component. | ### Types | Export | Description | | ---------------- | ------------------------------------------------------------------------------------------------------------------------- | | `SafeHtml` | Opaque wrapper for already-escaped HTML — the return type of every JSX expression. | | `Html` | Alias for `SafeHtml` — useful in controller return-type annotations. | | `FC

    ` | Functional component type — `(props: P & { children?: unknown }) => SafeHtml`. | | `Children` | Type for the `children` prop. | | `HttpContext` | The request context a view component or controller action receives; route params and model bindings live on `ctx.params`. | ## Types `ViewComponent` is what `view()` accepts — a function taking the request context and your props, returning markup. `ViewLayout` is the wrapper form a layout takes. Both are exported so a helper that returns a component, or a registry that holds several, can be typed. ## Next steps - [Flow](/docs/flow) — server-driven interactive components over WebSocket. - [Inertia](/docs/inertia) — React/Vue SPA pages backed by your controllers. - [Routing](/docs/routing) — `Router.view()` and file-based page routing. - [Responses](/docs/responses) — `view()` and the other response helpers. - [Controllers](/docs/controllers) — move view logic into controller actions. --- Source: https://zerotal.dev/docs/assets # Assets Zerotal compiles and serves your frontend assets — CSS and JavaScript — with Bun's native bundler, so there's no separate build tool to configure. Each stack (Flow, View, Inertia) has its own pipeline and hot-reload behaviour; all three use [Tailwind CSS v4](https://tailwindcss.com/docs/v4-beta). Asset compilation is built into the framework — there's no package to install or provider to register for the pipeline itself. You only add Tailwind and wire up a static route, then `bun zt dev` handles build-and-reload for you. > **Note** — Projects ship a `zt.ts` entry and a `zt` package script, > so commands are written `bun zt ` (e.g. `bun zt dev`). ## Getting Started Asset building is part of `@zerotal/core` — nothing to install and no provider to register. `bun zt dev` builds on change, and `bun zt css:build` produces a production bundle: ```bash # in your project root bun zt dev # watch and rebuild bun zt css:build # one production build ``` Tailwind is the only optional piece; [add it](#tailwind-css) when you want it. ### Which build command should I use? Pick by stack — the dev server runs the right pipeline automatically: - **Flow or View** (server-rendered, one stylesheet): `bun zt css:build` for production. Dev rebuilds are wired up by `FlowProvider`. - **Inertia** (React or Vue SPA, JS + CSS bundle): `bun zt inertia:build` for production. Dev rebuilds are wired up by `InertiaProvider`. - **Any stack, development**: `bun zt dev` — initial build, file watch, rebuild on save, and a browser reload over WebSocket. ## Tailwind CSS Install Tailwind v4 and Bun's native Tailwind plugin: ```bash # in your project root bun add -d tailwindcss bun-plugin-tailwind ``` Create `resources/css/app.css`: ```css /* resources/css/app.css */ @import "tailwindcss"; /* Extend Tailwind's theme with @theme */ @theme { --color-brand: oklch(0.6 0.2 260); --font-sans: "Inter", sans-serif; } ``` That's it — no `tailwind.config.js`, no PostCSS config, no purge list. Tailwind v4 detects your templates automatically via content scanning. > **Tip** — Why `bun-plugin-tailwind` and not PostCSS? > Bun has native CSS support built in. `bun-plugin-tailwind` is a first-party > Bun plugin that processes Tailwind v4 without PostCSS as an intermediary — > it's faster and requires no extra peer dependencies. PostCSS is not needed. ### How the build finds Tailwind Zerotal looks for `bun-plugin-tailwind` in your project's `node_modules` at build time. When it's installed, the plugin runs inside Bun's bundler and processes every `@import "tailwindcss"` directive natively — no PostCSS, no extra peer dependencies. When it isn't, the build falls back to spawning `bunx @tailwindcss/cli` as a subprocess, which needs only `tailwindcss`. Your stylesheet is built either way; installing the plugin keeps the work in-process and faster. ## CSS builds for Flow and View Flow and View apps ship a single compiled stylesheet — the entry lives in `resources/`, the built output in `public/`: ```text # project layout (Flow / View) resources/ css/ app.css ← Tailwind entry point public/ css/ app.css ← Built output (git-ignored) ``` ### Linking the built CSS Reference the built stylesheet with a plain `` pointing at `/css/app.css`. In a Flow layout it goes in the `static head`; in a View controller it's a tag in the returned HTML: ```html ``` ### Dev mode ```bash # in your project root bun zt dev ``` When `resources/css/app.css` exists, `FlowProvider.onBooted()` registers a combined CSS/JS build hook. The `DevOrchestrator` then: 1. Runs an initial CSS build before starting the server 2. Watches `resources/css/` for changes 3. Rebuilds CSS on every save (using `bun-plugin-tailwind` if installed, falling back to `bunx @tailwindcss/cli`) 4. Signals the browser to reload over WebSocket (`/__dev/ws`) The browser receives the reload signal and does a full page refresh — the updated CSS is served from `public/css/app.css`. > **Note** — The same `onBooted` hook also bundles `resources/js/app.js` → > `public/js/app.js` when that entry exists, so Flow apps with a small client > bundle get the same watch-and-rebuild treatment as their CSS. ### Production build ```bash # in your project root bun zt css:build ``` Override the defaults with flags: ```bash # in your project root bun zt css:build --input resources/css/app.css --output public/css --minify ``` | Flag | Short | Default | Description | | ---------- | ----- | ----------------------- | ---------------------------- | | `--input` | `-i` | `resources/css/app.css` | Path to the CSS entry point. | | `--output` | `-o` | `public/css` | Output directory. | | `--minify` | `-m` | `true` | Minify the output. | All flags default to sensible values; the short form with no flags is sufficient for most apps. ### Static file serving Add `Router.static` to serve `public/` at the root: ```typescript fragment // routes/index.ts Router.static("/", "public"); ``` Or target `public/css/` specifically: ```typescript fragment // routes/index.ts Router.static("/css", "public/css"); ``` Every file present when the server starts is registered as its own route and served without entering JavaScript, which is why a static asset costs essentially nothing per request. The trade-off is that the list is fixed at startup, so a file written afterwards has no route. That is fine for a deployed app, where the build finishes before the server boots. Where it isn't — a directory whose contents change while the server runs — pass `eager: false` to fall back to a per-request disk lookup. Dev mode applies that fallback to every static directory automatically, which is how a freshly-built chunk is served the moment it lands. #### A catch-all route and a file that is not there A single-page app has a catch-all route (`/*`) that renders the shell for any path no page claims. A catch-all would otherwise also answer for a script, stylesheet, source map or wasm file that does not exist, with the HTML shell and a `200`, and the browser reports that as _Expected a JavaScript module script but the server responded with a MIME type of text/html_. That is what a stale tab gets when it asks for a chunk a deploy removed, and what a dev rebuild's brand-new chunk got before the lookup above ran ahead of the catch-all. So a catch-all looks for the file on disk first (in dev, and for `eager: false` directories), and answers a missing `.js`, `.mjs`, `.css`, `.map` or `.wasm` with a plain `404`. Navigations, and paths with any other extension, still reach the catch-all, and a route you registered for a specific path always wins over it. ### The asset helper Hard-coding `/css/app.css` into a template works right up until you move the build output or serve it from a CDN prefix. `asset()` builds the URL for you from the configured `app.assets.prefix`, so the template stops caring where the file actually lives: ```typescript import { asset } from "zerotal/assets"; asset("app.css"); // → "/css/app.css" ``` Reach for it in layouts and templates you write by hand — the Flow scaffold uses it for exactly this. You do not need it for Inertia's `resources/app.html`, which already gets its URLs rewritten for you. In dev it also appends `?v=`, so a rebuilt file is refetched rather than served from cache. In production it returns the clean path unchanged — a deployed build is immutable, so cache invalidation belongs to your deploy (a CDN purge, or the Inertia asset version described below) rather than to a query string that would change on every boot. ## JavaScript builds for Inertia The React and Vue stacks share one build pipeline — same bundler, dev reload, and output. The only differences are the page file extension (`.tsx` vs `.vue`) and the JS entry point. ### Inertia directory layout ```text # project layout (Inertia) resources/ app.html ← HTML shell template css/ app.css ← Tailwind entry (imported in app.tsx) js/ app.tsx ← JS entry point env.d.ts ← ambient module decls (*.css, *.vue, images) pages.generated.ts ← auto-generated page registry (do not edit) Layouts/ AppLayout.tsx ← (.vue for Vue) pages/ ← page components live here by default home.tsx ← (.vue for Vue) Posts/ Index.tsx Show.tsx public/ assets/ app.js ← Built bundle (git-ignored) app.css ← Extracted CSS (git-ignored) chunk-*.js ← Per-page chunks (code splitting, git-ignored) ``` ### JS entry point `resources/js/app.tsx` is the bundler's entry point. It imports your CSS (so Tailwind runs as part of the JS build) and boots the Inertia client, resolving each page from the generated registry: ```typescript fragment // resources/js/app.tsx (React) import { createInertiaApp, type ResolvedComponent } from "@inertiajs/react"; import { createRoot } from "react-dom/client"; import { pages } from "./pages.generated.ts"; import "../css/app.css"; // ← imports CSS into the JS bundle createInertiaApp({ resolve: async (name): Promise => { const page = pages[name]; if (!page) throw new Error(`Inertia page not found: "${name}"`); return (await page()).default as ResolvedComponent; }, setup({ el, App, props }) { createRoot(el).render(); }, }); ``` ```typescript fragment // resources/js/app.tsx (Vue) import { createInertiaApp } from "@inertiajs/vue3"; import { createApp, h, type DefineComponent } from "vue"; import { pages } from "./pages.generated.ts"; import "../css/app.css"; createInertiaApp({ resolve: async (name): Promise => { const page = pages[name]; if (!page) throw new Error(`Inertia page not found: "${name}"`); return (await page()).default as DefineComponent; }, setup({ el, App, props, plugin }) { createApp({ render: () => h(App, props) }) .use(plugin) .mount(el as Element); }, }); ``` Tailwind is processed because `app.tsx` imports `app.css`, and `Bun.build()` passes all CSS through `bun-plugin-tailwind` before emitting `public/assets/app.css`. For Vue, the build also runs `@vue/compiler-sfc` via the Inertia Vue plugin so `.vue` single-file components compile. > **Warning** — `tsconfig.json` must set the right JSX runtime. React pages need > `"jsxImportSource": "react"` and Vue pages need `"jsxImportSource": "vue"`. > Using a server-JSX runtime instead (`"zerotal"` for views, `"@zerotal/flow"` for Flow) produces a runtime > "Invalid hook call" / null-dispatcher error. ### Inertia dev mode ```bash # in your project root bun zt dev ``` `InertiaProvider.onBooted()` registers Inertia's build routine under its own name. Each view layer registers its own, and every one of them runs on a change — an Inertia app that also installs `@zerotal/monitor` gets Flow alongside it, and both bundles keep rebuilding. The orchestrator: 1. Runs `generatePageRegistry()` + `Bun.build()` on startup 2. Watches `resources/js/` (which includes `resources/js/pages/`) and `resources/css/` 3. Regenerates the page registry and rebuilds the bundle on changes 4. Signals the browser over WebSocket at `/__dev/ws` Code splitting is enabled (`splitting: true`), so each page becomes its own lazy-loaded chunk. Only the entry bundle (with the shared framework runtime) is loaded on first navigation; each subsequent page chunk is fetched on demand. A rebuild that changes the shape of the module graph — adding a page, adding an import — emits chunk filenames the previous build never had. Those are served as soon as they are written: in dev the server falls back to a disk lookup for any path its startup scan didn't already know about, so a fresh chunk never 404s while waiting for a restart. #### Asset cache-busting in dev To stop the browser serving a stale bundle after a rebuild, dev mode busts the cache two ways (no-op in production): - **Versioned URLs.** The served HTML rewrites local `/assets/*.js` and `*.css` URLs to `?v=`. After a rebuild the mtime changes → the URL changes → the browser fetches fresh; when nothing changed the URL is stable, so the browser keeps using its cached copy. This works even on frontend-only rebuilds, where the server is never restarted. - **A per-build token on `asset()`.** URLs built by the [`asset()` helper](#the-asset-helper) instead carry `?v=` — one token for the whole build, reissued on every rebuild and handed to the server over the same channel that triggers the browser reload. Templates that call `asset()` therefore bust every URL at once, rather than file by file. - **`Cache-Control: no-cache`** is set on static assets served from `public/`, so the browser always revalidates. In production, asset URLs are served as-is. Use `ASSET_VERSION` (surfaced as `inertia.version`) to set the Inertia asset version — on a mismatch the client triggers a full reload (HTTP 409), which is how you invalidate clients after a deploy. ### Inertia production build ```bash # in your project root bun zt inertia:build bun zt inertia:build --production # minified, no source maps ``` The build: 1. Regenerates `pages.generated.ts` 2. Runs `Bun.build()` with `splitting: true` (plus minify / no source maps for `--production`) 3. Outputs all assets to `public/assets/` 4. Deletes what the previous build left behind Run it before `bun zt serve` in production (it is wired to the `build` script in the scaffolded `package.json`). #### Why the output directory needs sweeping Code-splitting names each shared chunk after its content — `chunk-3f9a2c.js` — so a rebuild that changes one page emits a new set of chunk names and abandons the old ones. Nothing overwrites them. Left alone, a long dev session buries the output directory in hundreds of dead chunks, all of them registered as static routes at startup and all of them shipped in the next deploy. Every build that splits therefore sweeps up after itself, in dev and in production alike. It removes two things and nothing else: files the previous build recorded as its own output, and files named the way the bundler names chunks. Anything else in the directory is left untouched, which matters because an output directory is often `public/`, where your images and favicon live alongside the bundle. The record of what each build wrote is kept in `.zerotal/build/`, outside the served directory. A directory that has been collecting chunks since before this existed is cleaned by the next build, since chunks are recognised by name and not only by the record. ## Controlling how files are loaded `url()` references in your CSS are resolved at build time, and Bun inlines small files as `data:` URIs. That is the right default for an icon and the wrong one for a font: the bytes move **into the stylesheet**, which blocks first paint. Nine woff2 subsets can turn a 36 KB stylesheet into 260 KB that must download before anything renders — the opposite of what `font-display: swap` is for, and expensive on exactly the connections that need it most. Set a per-extension loader to emit them as separate files instead: ```typescript fragment // config/app.ts export default AppConfig({ assets: { entrypoint: "resources/css/app.css", loader: { ".woff2": "file", ".woff": "file" }, }, }); ``` `file` copies the asset to `outDir` and rewrites the `url()` to point at it, so the stylesheet stays small and the fonts load in parallel. The other accepted values are `dataurl` (force inlining), `base64`, `text`, `json`, and `toml`. ## Hot reload Both pipelines above are driven by the same dev process. `bun zt dev` builds once, spawns the server as a child process, and watches the filesystem; what happens on a change depends on which directory the change landed in: ```text # bun zt dev process model ┌──────────────────────────────────────────────────────┐ │ bun zt dev │ │ │ │ Process 1: DevOrchestrator │ │ ├─ Initial build (CSS or JS+CSS) │ │ ├─ Spawn Process 2 (server) │ │ └─ Watch filesystem │ │ │ │ │ ├─ Backend change (app/, routes/, bootstrap/) │ │ │ └─ Rebuild, then kill + respawn (150 ms) │ │ │ │ │ └─ Frontend change (resources/css/, js/) │ │ └─ Rebuild assets (80 ms debounce) │ │ └─ Write "reload:" to │ │ Process 2 stdin │ │ │ │ Process 2: Zerotal server (--dev-worker) │ │ ├─ Serves app routes │ │ ├─ Sends "version:" on every WS connect │ │ ├─ Broadcasts "reload" to WS clients │ │ └─ WebSocket at /__dev/ws │ │ │ │ │ ▼ │ │ Browser (JS client) │ │ connects on load │ │ reloads on "reload" message │ │ reloads when the token changed │ │ reconnects on close (1 s delay) │ └──────────────────────────────────────────────────────┘ ``` ### What triggers a restart, and what only rebuilds | Changed path | Action | | ------------------------------------------ | -------------------------------------- | | `app/`, `routes/`, `bootstrap/`, `config/` | Server restart (150 ms) | | `resources/css/`, `resources/js/` | Asset rebuild + browser reload (80 ms) | | `public/` | Ignored (output dir) | | `node_modules/`, `.git/` | Ignored | Inertia pages live under `resources/js/pages/`, so they're covered by the `resources/js/` watch and rebuild rather than restart. ### Browser client Under `--dev-worker`, `DevReloadMiddleware` injects this script into every `text/html` response, so live reload works for any view layer — Flow, View, plain HTML — with no wiring on your part: ```html ``` The two signals cover two different situations. A frontend change pushes `reload` down a socket that is already open. A backend change cannot: it restarts the server, and the restart closes every socket, so a reload pushed at that moment reaches nobody — the tab does not reconnect for another second. The build token closes that gap. The server states its token whenever a socket opens; the tab remembers the first one it sees and reloads when a reconnect reports a different one. That is how a rebuild triggered by a backend edit still reaches the browser. Inertia is the one exception to where the script comes from: it bakes the same client into its cached HTML template at boot rather than receiving it from the middleware, because injecting into the response body means buffering it, and `Inertia.stream()` exists precisely to avoid that. The middleware skips any page that already carries a `/__dev/ws` client, so the two never collide. ## Styling Zerotal is unopinionated about CSS — the Tailwind pipeline above is the default, but nothing forces it. For state-driven classes inside Flow components, see [reactive classes and attributes](/docs/flow#reactive-classes-and-attributes); the patterns below are the styling techniques you'll reach for most, whichever stack you picked. ### CSS Modules Bun's bundler understands CSS Modules out of the box. Import a `.module.css` file and use the generated class names — styles are scoped to the component, so names never collide across files: ```tsx fragment // app/components/Button.tsx import styles from "./Button.module.css"; export function Button({ label }: { label: string }) { return ; } ``` ```css /* app/components/Button.module.css */ .button { padding: 0.5rem 1rem; border-radius: 0.375rem; background: var(--color-brand); font-weight: 600; } ``` ### Component libraries For ready-made, themeable UI, reach for **flow-ui** — Zerotal's first-party, shadcn-style component set built on the same Tailwind tokens, so it follows your theme automatically: ```bash # in your project root bun zt flow:add button card dialog ``` Browse the full catalogue in [Components](/docs/components). Any npm component library also works with the Bun bundler — common choices: | Library | Install | | ----------- | ---------------------------------------- | | shadcn/ui | `bunx shadcn@latest init` | | Radix UI | `bun add @radix-ui/react-dialog` | | Headless UI | `bun add @headlessui/react` | | DaisyUI | `bun add -d daisyui` (a Tailwind plugin) | ### Web fonts Load fonts from a CDN for a quick start, or self-host them in `public/` for one fewer network round-trip (and to keep requests on your own domain). Pair a self-hosted face with `--font-sans` in your `@theme` block so Tailwind's `font-sans` utility picks it up: ```html ``` ```css /* resources/css/app.css — self-hosted alternative */ @font-face { font-family: "Inter"; src: url("/assets/fonts/Inter.woff2") format("woff2"); font-weight: 100 900; font-display: swap; } ``` ## Testing Set your suite up once as described in [Testing](/docs/testing). Assets are built artifacts, so the useful tests are about what a request receives — not about the bundler. That boundary is worth holding. Tailwind emitting the right rules and Bun bundling the right modules are already covered by those tools' own suites, and a test that asserts on the _content_ of built CSS breaks every time a class is added. What is genuinely yours to verify is the wiring: that the page points at the asset, that the asset is served, and that a deploy invalidates the old one. **Assert the page references the asset**, which catches a build config that silently stopped emitting it: ```typescript fragment // tests/http/assets.test.ts import { test } from "bun:test"; import { createApp } from "../helpers.ts"; test("the layout links the built stylesheet", async () => { const app = await createApp(); const res = await app.get("/"); res.assertSee("/assets/app.css"); await app.close(); }); ``` **Assert it is actually served**, because a reference to a missing file is a `404` the page will not tell you about: ```typescript fragment // tests/http/assets.test.ts const css = await app.get("/assets/app.css"); css.assertOk(); css.assertHeader("Content-Type", "text/css"); ``` These two belong together. Each passes on its own while the pair is broken — a page can link a path nothing serves, and a served file can go unreferenced — so testing only one leaves the failure that actually reaches users uncovered. **Cache-busting is worth one test** if you rely on it for deploys. In dev the URL carries a `?v=` token that changes on rebuild; in production `ASSET_VERSION` drives the Inertia version header: ```typescript fragment // tests/http/assets.test.ts test("asset URLs carry a version in dev", async () => { const res = await app.get("/"); expect(res.text()).toMatch(/\/assets\/app\.css\?v=/); }); ``` > **Warning** — These tests need a build to have run. A suite in CI that never > runs `bun zt css:build` will fail them for a reason unrelated to the code — > either build in the pipeline before testing, or scope these to a suite you run > after building. The cleanest arrangement is to build once as a CI step before the test job, the way you would before starting the server. Failing that, keep asset tests in their own file and run it as a separate command after the build, so a missing artifact fails one obvious job rather than scattering unrelated failures through the whole suite. ### Unit-testing the asset helper `asset()` is a pure function of the configured prefix, so its behaviour can be pinned down without a request at all. This is the cheapest place to catch a misconfigured CDN prefix: ```typescript fragment // tests/unit/asset.test.ts import { asset } from "zerotal/assets"; test("asset() resolves against the configured prefix", () => { expect(asset("app.css")).toBe("/css/app.css"); }); ``` ### Inertia stale-bundle reloads Inertia apps carry an asset version on every page object, and a request whose `X-Inertia-Version` no longer matches the server's is answered with a `409` and an `X-Inertia-Location` header, which is what makes a browser holding yesterday's bundle do a full reload after a deploy. That flow only fires when the version actually changes between builds, so it is worth one test: ```typescript fragment // tests/http/assets.test.ts test("a stale bundle is told to reload", async () => { const res = await app.get("/dashboard", { "X-Inertia": "true", "X-Inertia-Version": "stale-version", }); res.assertStatus(409); res.assertHeader("X-Inertia-Location"); }); ``` ## References ### Commands | Command | Effect | | ----------------------------------- | ----------------------------------------------- | | `bun zt serve` | Serve the app; assets are built once at boot | | `bun zt dev` | Dev server with hot reload | | `bun zt css:build` | Production CSS build (Flow/View) | | `bun zt inertia:build` | Development JS+CSS build (Inertia) | | `bun zt inertia:build --production` | Production JS+CSS build (Inertia) | | `bun zt route:list` | List all routes (including static asset routes) | Which build command belongs to your app follows from the view layer, not from preference: `css:build` covers Flow and View, which ship server-rendered HTML and need only a stylesheet; `inertia:build` covers Inertia, which additionally bundles page components into JavaScript. Running the wrong one leaves the app without the output it looks for at boot. ### Files | File | Purpose | | --------------------------------- | --------------------------------- | | `resources/css/app.css` | Tailwind entry (all stacks) | | `resources/app.html` | HTML shell (Inertia only) | | `resources/js/app.tsx` | JS entry (Inertia only) | | `resources/js/pages/` | Inertia page components (default) | | `resources/js/pages.generated.ts` | Auto-generated page registry | | `public/css/app.css` | Built CSS output (Flow/View) | | `public/assets/app.js` | Built JS output (Inertia) | | `public/assets/app.css` | Built CSS output (Inertia) | Everything under `resources/` is source you edit; everything under `public/` is build output. `public/` is regenerated, so nothing hand-written should live there and the whole directory is safe to delete and rebuild. ### Configuration | Key | Controls | | ------------------- | ------------------------------------------------------ | | `app.assets.prefix` | URL prefix `asset()` resolves against — point at a CDN | | `ASSET_VERSION` | Inertia asset version; a mismatch forces a full reload | ```typescript import { asset } from "zerotal/assets"; asset("app.css"); // → "/css/app.css" ``` See [the asset helper](#the-asset-helper) for what it does in dev versus production, and [what triggers a restart](#what-triggers-a-restart-and-what-only-rebuilds) for the watcher's rules. ## Next steps - [Flow](/docs/flow) — the zero-config server-rendered SPA stack. - [Inertia](/docs/inertia) — controllers, pages, shared props, and SSR. - [Middleware & versioning](/docs/inertia/middleware) — the asset-version flow in full. - [Components](/docs/components) — themeable flow-ui components for your UI. - [View](/docs/view) — classic SSR with JSX controllers. - [Deployment](/docs/deployment) — run the production asset build before serving. --- Source: https://zerotal.dev/docs/components # Components `@zerotal/flow-ui` ships 53 themeable components for [Flow](/docs/flow). They are built on accessible headless primitives and design tokens, so they follow your theme (light / dark) out of the box. Add them with the CLI (copy the source into your app) or import them straight from the package. The handful that ship inside `@zerotal/flow` itself (`Link`, `Modal`, `Flash`, `Table` and the headless primitives) are in [Flow's built-in components](/docs/flow/components). The catalogue covers what an application actually needs rather than only the obvious primitives: | Group | Components | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Forms | `Field`, `Input`, `InputGroup`, `InputOTP`, `Textarea`, `Select`, `Combobox`, `Checkbox`, `RadioGroup`, `Switch`, `Slider`, `Toggle`, `ToggleGroup`, `Label`, `Calendar`, `DatePicker` | | Buttons & actions | `Button`, `ButtonGroup`, `DropdownMenu`, `ContextMenu`, `Menubar` | | Overlays | `Dialog`, `AlertDialog`, `Sheet`, `Popover`, `HoverCard`, `Tooltip`, `Command` | | Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Pagination`, `Tabs` | | Data | `Table`, `Chart`, `Item`, `Avatar`, `Badge` | | Feedback | `Toaster`, `Alert`, `Progress`, `Spinner`, `Skeleton`, `Empty` | | Layout & content | `Card`, `Accordion`, `Collapsible`, `ScrollArea`, `Resizable`, `Carousel`, `AspectRatio`, `Separator`, `Prose`, `Kbd` | ## Where the work happens The components follow one rule, and it is worth stating before the API: **the server renders, the client reacts.** Anything that answers to a pointer or a keystroke — dragging a slider, paging a calendar, filtering a palette, pressing a toggle, hovering a chart — runs entirely in the browser through Alpine. Those interactions have to land inside a frame, and a network round-trip cannot make that promise. Putting them on the server produces the specific ugliness of a control that lags its own input: a slider whose readout does not move while you drag it, a segmented button that stays unpressed until the reply arrives. The server's job is the first paint and the data. It renders the initial state so the page is correct and complete before any script runs, and it hears about a change once — when there is something to persist. A date picker syncs the day you chose, not the six months you browsed to find it. In practice that means most components bind rather than call: ```tsx fragment {/* live while dragging, synced on release */} {/* presses instantly, syncs after */} {/* months page client-side, day syncs once */} ``` Where a component genuinely needs the server — a calendar laying out records, a table of rows — it says so, and paging is a real navigation because the next page means different data. ## Getting Started ```bash # in your project root bun add @zerotal/flow-ui ``` ## Register the provider `FlowUiProvider` is a scaffolding-only provider: it registers the `flow:*` CLI commands. The components themselves are plain functions with no runtime service, so you only need the provider to use the CLI. Add it to the providers array in `bootstrap/providers.ts`: ```ts // bootstrap/providers.ts import { FlowUiProvider } from "@zerotal/flow-ui"; const providers = [ // …your other providers FlowUiProvider, ]; export default providers; ``` Registering the provider switches on the following: - `onBooted` — registers the `flow:list`, `flow:add`, and `flow:init` console commands (only when the `commands` binding is present, so web/test boots stay unaffected). ## Set up the theme Run `flow:init` once per app. It drops the shared `cn` / `gva` utilities into `app/flow/components/ui/lib/` and wires the design-token theme into your Tailwind entry CSS: ```bash # in your project root bun zt flow:init ``` > **Note** — `flow:init` is idempotent: it skips files that already exist and only adds the `@import "@zerotal/flow-ui/theme.css";` line if it is missing. Pass `--css ` to target a Tailwind entry other than `resources/css/app.css`. ### Without a build step Components are written against design tokens — `bg-card`, `text-muted-foreground`, `border-input`, `bg-primary` — so _defining_ those tokens themes the whole kit at once. `theme.css` does that for a real Tailwind build. When you have no build step, `flowUiHead()` does the same job as a `` payload: it loads Tailwind v4's browser build from a pinned jsDelivr URL (with a subresource integrity hash), gives it the identical token mapping as a `