@quickback-dev/cli 0.10.8 → 0.10.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  export const DOCS = {
4
4
  "changelog": {
5
5
  "title": "Changelog",
6
- "content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. The filename is the action name AND the URL segment.\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now a targeted error signal.** When a table carries `ownerId` but no isolation column AND no explicit `firewall:`, the compiler raises a specific error: `\\`ownerId\\` is business-logic ownership, not access control — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-read-views)\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `?view={name}` (or `/views/{name}`)\n\n**Pre-record access ordering on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now Enforced Server-Side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\n// \"Org owner OR platform admin\"\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or`/`and` combinators. See [Access - userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"short\",\n }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access - Role Hierarchy](/compiler/definitions/access#role-hierarchy) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now receive a **security-scoped database** instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nThe scoped DB uses duck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **automatically cascades** to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade UPDATE statements.\n\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- KV and R2 storage integrations\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial Release\n\n- **Quickback Compiler** — TypeScript-first backend compiler\n- **Four Security Pillars** — Firewall, Access, Guards, Masking\n- **`defineTable()`** — Schema + security configuration in a single file\n- **Templates** — Cloudflare Workers, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\n- **Better Auth Integration** — Organizations, roles, sessions\n- **Drizzle ORM** — Schema-first with automatic migrations\n- **Cloudflare D1** — Split database support (auth + features)"
6
+ "content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reject reserved keys inside `access.record` at compile time\n\n`access.record` is a flat field map evaluated as implicit AND between\nentries — keys must be column names. Putting `and: [...]` (or `or` /\n`roles` / `userRole`) inside `record` was a real-world footgun: the\nruntime treated the literal string `\"and\"` as a column lookup, the\npredicate failed on every row, and the caller got a silent `403` /\nempty list with nothing pointing at the misuse. The TypeScript type\ncouldn't catch this — `RecordConditions` is an open-ended index\nsignature, so any key parses.\n\nThe compiler now walks every access node attached to a resource (CRUD\nops, `read.access`, view access, masking `show` / `query`, action\naccess) and throws a clear migration error when `record` contains a\nreserved key:\n\n- `and` / `or` inside `record` → use the top-level `and` / `or`\n sibling: `{ and: [{ record: { ... } }, { record: { ... } }] }`\n- `roles` / `userRole` inside `record` → put them at the access node\n alongside `record`: `{ roles: [...], record: { ... } }`\n\nThe error names the exact origin (`crud.update.access`,\n`actions.focus.access.or[1]`, etc.) so the fix lands in the right place.\n\n---\n\n## v0.10.9 — April 29, 2026\n\n### Role hierarchy now expands in record-based action access\n\n`auth.roleHierarchy: ['member', 'admin', 'owner']` plus\n`access: { roles: ['member+'] }` on a record-based action used to\nsilently 403 valid callers. The standalone-action route generator\ninlined the expanded role list as a JSON literal, but the\nrecord-based generator read the access config back through the\nruntime `actions['name'].access` import — the user's source, where\nthe unexpanded `'member+'` shorthand still lived. The runtime did\nliteral string matching against `ctx.roles`, so an `owner` calling\nthe action got `['member+'] !== 'owner'` and was rejected.\n\nFixed: record-based action routes now inline the expanded list the\nsame way standalone routes do. `input` and `execute` still flow\nthrough the runtime import (closures aren't serializable); only the\naccess config is lifted to a JSON literal so the compile-time\nexpansion actually reaches the matcher.\n\nA regression test (`role-hierarchy-action-routes.test.ts`) locks the\nbehavior in — it asserts that `member+` never reaches the route\noutput and that the access config is no longer read from\n`actions[name].access` at runtime.\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit support on postgres targets, plus a generated-API quality pass\n\n**Audit on PG.** Until this release, `audit_events` only existed on cloudflare-d1 — projects on Neon (or any postgres target) silently skipped audit logging on `unsafe:` and `PUBLIC`-role actions, and hard delete was hard-blocked. Postgres has no equivalent of D1's separate-database binding model, but it has native schemas — so the audit table now lives in a dedicated `audit` schema in the same database as features (`drizzle.pgSchema('audit')`). The `hasSecurityAudit` gate accepts D1 OR any PG dialect; the `auditDatabaseId` requirement only fires for D1 (which still uses the separate-binding model). The recruitment example wires `auditDatabaseId` so the recompile path stays green.\n\n**`auditDatabaseId` is now a compile-time requirement** (D1 only). Previously, projects with unsafe/PUBLIC actions but no audit id silently produced a `database_id = \"local-audit\"` placeholder in production `wrangler.toml`; Cloudflare's worker upload step then rejected it with code 10021 *after* assets and migrations had already run. The compile-time error names the exact `wrangler d1 create <project>-audit` command and the `auditDatabaseId` config key where the returned id goes.\n\n### Five fixes from a Loop integration ticket pass\n\n**Action input → OpenAPI / MCP.** `defineAction({ input: z.object({...}) })` schemas now flow into `requestBody` on the OpenAPI operation and `inputSchema.properties` / `_bodyFields` on the MCP tool list. Simple `z.object` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation — full-fidelity output with no static translator to maintain. Pre-fix, every action came out as a no-arg endpoint, which gutted typed SDK generation and made MCP useless for actions that take parameters.\n\n**OpenAPI fidelity.** Three surgical fixes that strict validators (zod, openapi-typescript, openapi-fetch) had been complaining about:\n- Response schemas now emit `required[]` for every non-nullable column, so generated SDKs treat them as guaranteed-present rather than optional.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`, narrowing to literal unions.\n- `id` only claims `format: \"uuid\"` when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }` — strict validators stop rejecting responses against their own spec.\n\n**Mask auto-detector now checks the column exists.** The auto-mask predicate used to be unconditionally `show: { or: 'owner', roles: ['admin'] }` — including for tables with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`). The generated mask function would reference a non-existent column and fail under TypeScript checks. The auto-detector now verifies the resolved owner column exists in the parsed schema before emitting the `or` clause; when it doesn't, the rule falls back to roles-only and the compiler emits a warning so the behavior is transparent.\n\n**Error code consistency.** The generated CRUD layer was emitting raw codes (`'UNAUTHORIZED'`, `'NOT_NULL_VIOLATION'`, `'UNIQUE_VIOLATION'`, `'INSERT_FAILED'`, `'UPDATE_FAILED'`) that were never in the `QuickbackErrorCode` enum, so consumers couldn't switch exhaustively on `code`. New `database` layer + `DB_NOT_NULL_VIOLATION` / `DB_UNIQUE_VIOLATION` / `DB_INSERT_FAILED` / `DB_UPDATE_FAILED` / `NOT_FOUND` codes are now in the enum, the routes use `AuthErrors.missing()` / `DatabaseErrors.*()` helpers throughout, and the OpenAPI `Error` component emits `code` as a closed enum sourced from the canonical `QUICKBACK_ERROR_CODES` list. Generated SDKs can now `switch` on `code` without a default branch swallowing unknown values. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n**Dropped dead `auditFields` preamble from action route generators.** The audit wrapper's `Proxy` already hard-stamps `createdAt` / `createdBy` / `modifiedAt` / `modifiedBy` on every INSERT and `modifiedAt` / `modifiedBy` on every UPDATE — the `auditFields` const the route preamble built was never read. Dropped from `standalone.ts` / `record-based.ts` and from the `ActionExecutorParams` JSDoc. Migrated 7 example handlers (drop `modifiedAt: auditFields!.modifiedAt` from `.set` payloads — the wrapper handles it). Note: `.onConflictDoUpdate({ set })` is *not* intercepted by the wrapper, so `upsertBatch`-style handlers keep an explicit `modifiedAt: now`.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. The filename is the action name AND the URL segment.\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now a targeted error signal.** When a table carries `ownerId` but no isolation column AND no explicit `firewall:`, the compiler raises a specific error: `\\`ownerId\\` is business-logic ownership, not access control — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-read-views)\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `?view={name}` (or `/views/{name}`)\n\n**Pre-record access ordering on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now Enforced Server-Side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\n// \"Org owner OR platform admin\"\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or`/`and` combinators. See [Access - userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"short\",\n }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access - Role Hierarchy](/compiler/definitions/access#role-hierarchy) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now receive a **security-scoped database** instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nThe scoped DB uses duck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **automatically cascades** to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade UPDATE statements.\n\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- KV and R2 storage integrations\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial Release\n\n- **Quickback Compiler** — TypeScript-first backend compiler\n- **Four Security Pillars** — Firewall, Access, Guards, Masking\n- **`defineTable()`** — Schema + security configuration in a single file\n- **Templates** — Cloudflare Workers, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\n- **Better Auth Integration** — Organizations, roles, sessions\n- **Drizzle ORM** — Schema-first with automatic migrations\n- **Cloudflare D1** — Split database support (auth + features)"
7
7
  },
8
8
  "compiler/claude-code-skill": {
9
9
  "title": "AI Developer Tools",
@@ -15,7 +15,7 @@ export const DOCS = {
15
15
  },
16
16
  "compiler/cloud-compiler/cli": {
17
17
  "title": "CLI Reference",
18
- "content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Create a Project\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` - Cloudflare Workers + D1 + Better Auth (free)\n- `bun` - Bun + SQLite + Better Auth (free)\n- `turso` - Turso/LibSQL + Better Auth (pro)\n\n**Example:**\n```bash\nquickback create cloudflare my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` - Project configuration\n- `quickback/features/` - Your table definitions\n- Example todos feature with full security configuration\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### Initialize Structure\n\n```bash\nquickback init\n```\n\nCreates the Quickback folder structure in an existing project:\n```\nquickback/\n features/\n quickback.config.ts\n```\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./quickback/.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\",\n \"tier\": \"free\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Create a new project\nquickback create cloudflare my-app\ncd my-app\n\n# 2. Define your tables in quickback/features/\n# (Already has example todos feature)\n\n# 3. Compile\nquickback compile\n\n# 4. Run\nnpm run dev\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx:\n```bash\nnpx @quickback-dev/cli create cloudflare my-app\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
18
+ "content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Create a Project\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` - Cloudflare Workers + D1 + Better Auth (free)\n- `supabase` - Hono + Supabase Postgres + Supabase Auth (free)\n- `blog` - Single-tenant blog (PUBLIC reads, admin writes) (free)\n- `empty` - Cloudflare scaffold, no example features (free)\n- `multi-tenant` - Full SaaS with orgs, teams, billing (pro)\n\n**Example:**\n```bash\nquickback create cloudflare my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` - Project configuration\n- `quickback/features/` - Your table definitions\n- Example todos feature with full security configuration\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### Initialize Structure\n\n```bash\nquickback init\n```\n\nCreates the Quickback folder structure in an existing project:\n```\nquickback/\n features/\n quickback.config.ts\n```\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./quickback/.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\",\n \"tier\": \"free\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Create a new project\nquickback create cloudflare my-app\ncd my-app\n\n# 2. Define your tables in quickback/features/\n# (Already has example todos feature)\n\n# 3. Compile\nquickback compile\n\n# 4. Run\nnpm run dev\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx:\n```bash\nnpx @quickback-dev/cli create cloudflare my-app\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
19
19
  },
20
20
  "compiler/cloud-compiler/endpoints": {
21
21
  "title": "Endpoints",
@@ -95,7 +95,7 @@ export const DOCS = {
95
95
  },
96
96
  "compiler/definitions/masking": {
97
97
  "title": "Masking - Field Redaction",
98
- "content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `creditCard` | ************1234 |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n crud: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n crud: {\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n },\n});\n```"
98
+ "content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `creditCard` | ************1234 |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n crud: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n crud: {\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n },\n});\n```"
99
99
  },
100
100
  "compiler/definitions/read": {
101
101
  "title": "Read - Unified Read Pipeline",
@@ -127,7 +127,7 @@ export const DOCS = {
127
127
  },
128
128
  "compiler/getting-started": {
129
129
  "title": "Getting Started",
130
- "content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Install the CLI\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Create a Project\n\n```bash\nquickback create cloudflare my-app\ncd my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth (free)\n- `bun` — Bun + SQLite + Better Auth (free)\n- `turso` — Turso/LibSQL + Better Auth (pro)\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // draft | open | closed\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. CRUD — Write operations\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no CRUD routes ship until you opt in with `crud: { … }`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **CRUD Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Log in (first time only)\nquickback login\n\n# Compile your definitions\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/api/auth/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/api/auth/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
130
+ "content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Install the CLI\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Create a Project\n\n```bash\nquickback create cloudflare my-app\ncd my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth (free)\n- `blog` — Single-tenant blog (PUBLIC reads, admin writes) (free)\n- `empty` — Cloudflare scaffold, no example features (free)\n- `multi-tenant` — Full SaaS with orgs, teams, billing (pro)\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // draft | open | closed\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. CRUD — Write operations\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no CRUD routes ship until you opt in with `crud: { … }`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **CRUD Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Log in (first time only)\nquickback login\n\n# Compile your definitions\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/api/auth/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/api/auth/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
131
131
  },
132
132
  "compiler/getting-started/patterns": {
133
133
  "title": "Common Patterns",
@@ -137,21 +137,17 @@ export const DOCS = {
137
137
  "title": "Blog Template",
138
138
  "content": "The blog template creates a single-tenant backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts via Better Auth's admin plugin.\n\nThis template uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, no `organizationId` columns. Roles come from `user.role` instead of org membership.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Single-tenant config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nKey difference from the multi-tenant templates: `organizations: false` disables the Better Auth organization plugin. See [Single-Tenant Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n crud: {\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `role: \"admin\"` (set via Better Auth's admin plugin)\n- **`owner`** firewall scope tracks who created each post via `ownerId`\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions.ts)\n\nThe template includes publish/unpublish actions with guard conditions:\n\n```typescript\n\nexport default defineActions(posts, {\n publish: {\n description: \"Publish a draft post\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n },\n unpublish: {\n description: \"Revert a published post to draft\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"published\" } },\n },\n sideEffects: \"sync\",\n },\n});\n```\n\nThese actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Database\n\nThe blog template uses a single D1 database (no split databases):\n\n```bash\nnpx wrangler d1 create my-site\n```\n\nCopy the database ID from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site\"\ndatabase_id = \"paste-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n crud: {\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] } },\n },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Single-Tenant Mode](/compiler/config/single-tenant) — How single-tenant mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
139
139
  },
140
- "compiler/getting-started/template-bun": {
141
- "title": "Bun Template",
142
- "content": "The Bun template creates a backend running on Bun with a local SQLite database and Better Auth. No cloud account needed — ideal for local development and prototyping.\n\n## Create the Project\n\n```bash\nquickback create bun my-app\ncd my-app\n```\n\nAliases: `quickback create local my-app`\n\nThis scaffolds a project with:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── todos/\n│ ├── todos.ts # Schema + security (defineTable)\n│ └── actions.ts # Custom actions\n├── src/ # Compiled output (generated)\n├── data/ # SQLite database files\n├── package.json\n├── tsconfig.json\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"bun\", config: {} },\n database: {\n name: \"better-sqlite3\",\n config: { path: \"./data/app.db\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nThe Bun template includes the same `todos` feature as the [Cloudflare template](/compiler/getting-started/template-cloudflare) with all four security pillars configured.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nbun install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Run Migrations\n\n```bash\nnpm run db:migrate\n```\n\nThis creates the SQLite database in `data/app.db` and applies all migrations.\n\n### 5. Create Environment File\n\nCreate a `.env` file in your project root:\n\n```bash\n# Runtime\nNODE_ENV=development\nPORT=3000\n\n# Auth\nBETTER_AUTH_SECRET=your-secret-key-change-in-production\nBETTER_AUTH_URL=http://localhost:3000\n```\n\n**Note:** Generate a strong random string for `BETTER_AUTH_SECRET` in production. You can use `openssl rand -hex 32`.\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:3000` with hot reload.\n\n## Database\n\nThe Bun template uses `better-sqlite3` with a local SQLite file stored in `data/app.db`. The generated database module automatically:\n\n- Creates the `data/` directory if it doesn't exist\n- Enables WAL mode for better concurrent performance\n- Enables foreign key constraints\n\n```\ndata/\n└── app.db # SQLite database file\n```\n\nUnlike the Cloudflare template, Bun uses a **single database** for both auth and feature tables. Migrations are in a single directory:\n\n```\nquickback/drizzle/\n├── meta/\n│ ├── _journal.json\n│ └── 0000_snapshot.json\n└── 0000_initial.sql\n```\n\n## Available Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `dev` | `bun run --hot src/index.ts` | Start dev server with hot reload |\n| `start` | `bun run src/index.ts` | Start production server |\n| `build` | `bun build src/index.ts --outdir ./dist --target bun` | Build for production |\n| `db:migrate` | `npx drizzle-kit migrate` | Apply database migrations |\n| `type-check` | `tsc --noEmit` | Run TypeScript type checking |\n\n## Switching to Cloudflare\n\nWhen you're ready to deploy to production, you can switch to the Cloudflare template by updating your `quickback.config.ts`:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\nThe compiler regenerates the entire `src/` directory for the new runtime target. Your feature definitions stay the same.\n\n## Next Steps\n\n- [Add a new feature](/compiler/definitions/schema) — Define your own tables with security\n- [Configure access control](/compiler/definitions/access) — Set role-based permissions\n- [Add custom actions](/compiler/definitions/actions) — Business logic beyond CRUD\n- [Cloudflare template](/compiler/getting-started/template-cloudflare) — Deploy to production"
143
- },
144
140
  "compiler/getting-started/template-cloudflare": {
145
141
  "title": "Cloudflare Template",
146
142
  "content": "The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.\n\n## Create the Project\n\n```bash\nquickback create cloudflare my-app\ncd my-app\n```\n\nAliases: `quickback create cf my-app`\n\nThis scaffolds a project with:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── todos/\n│ ├── todos.ts # Schema + security (defineTable)\n│ └── actions.ts # Custom actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\n### Example Feature (todos.ts)\n\nThe template includes a `todos` feature with all four security pillars configured:\n\n```typescript\n\nexport const todos = sqliteTable(\"todos\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n description: text(\"description\"),\n completed: integer(\"completed\", { mode: \"boolean\" }).default(false),\n priority: text(\"priority\").default(\"medium\"),\n dueDate: integer(\"due_date\", { mode: \"timestamp\" }),\n organizationId: text(\"organization_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(todos, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"description\", \"completed\", \"priority\", \"dueDate\"],\n updatable: [\"title\", \"description\", \"completed\", \"priority\", \"dueDate\"],\n immutable: [\"id\", \"organizationId\", \"ownerId\"],\n },\n masking: {\n description: {\n type: \"redact\",\n show: { roles: [\"owner\", \"admin\"] },\n },\n },\n read: {\n access: { roles: [\"owner\", \"admin\", \"member\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"admin\", \"member\"] } },\n update: { access: { roles: [\"owner\", \"admin\", \"member\"] } },\n delete: { access: { roles: [\"owner\", \"admin\"] }, mode: \"soft\" },\n },\n});\n```\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\nThis sends your definitions to the Quickback compiler and generates the full `src/` directory, migrations, and configuration files.\n\n### 4. Create D1 Databases\n\nThe Cloudflare template uses **dual database mode** by default — separate databases for auth and application data.\n\n```bash\n# Create the auth database\nnpx wrangler d1 create my-app-auth\n\n# Create the features database\nnpx wrangler d1 create my-app-features\n```\n\nCopy the database IDs from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"paste-auth-id-here\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"paste-features-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\nThis applies migrations to both databases locally.\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Wrangler Configuration\n\nThe compiler generates a `wrangler.toml` with all required bindings:\n\n```toml\nname = \"my-app\"\nmain = \"src/index.ts\"\ncompatibility_date = \"2025-03-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n[observability]\nenabled = true\n\n[placement]\nmode = \"smart\"\n\n# Auth database\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"your-auth-db-id\"\n\n# Features database\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"your-features-db-id\"\n\n# Key-value storage\n[[kv_namespaces]]\nbinding = \"KV\"\nid = \"your-kv-id\"\n```\n\n### Optional Bindings\n\nDepending on your configuration, the compiler may also generate bindings for:\n\n| Binding | Type | When Generated |\n|---------|------|----------------|\n| `R2_BUCKET` | R2 Bucket | `fileStorage` configured |\n| `AI` | Workers AI | `embeddings` configured on any feature |\n| `VECTORIZE` | Vectorize Index | `embeddings` configured |\n| `EMBEDDINGS_QUEUE` | Queue | `embeddings` configured |\n| `WEBHOOKS_DB` | D1 | Webhooks enabled |\n| `WEBHOOKS_QUEUE` | Queue | Webhooks enabled |\n| `BROADCASTER` | Service | `realtime` configured |\n\n## Dual Database Mode\n\nBy default, the Cloudflare template separates auth tables from application tables:\n\n- **`AUTH_DB`** — Better Auth tables (`users`, `sessions`, `accounts`, `organizations`, `members`)\n- **`DB`** — Your feature tables (`todos`, etc.)\n\nThis keeps auth data isolated and allows independent scaling. Each database gets its own migration directory:\n\n```\nquickback/drizzle/\n├── auth/ # Auth migrations\n│ ├── meta/\n│ └── 0000_*.sql\n└── features/ # Feature migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n## Deploying to Production\n\n### 1. Apply Remote Migrations\n\n```bash\nnpm run db:migrate:remote\n```\n\n### 2. Deploy to Cloudflare\n\n```bash\nnpm run deploy\n```\n\nThis runs `wrangler deploy` to push your worker to Cloudflare's edge network.\n\n## Available Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `dev` | `wrangler dev` | Start local dev server |\n| `deploy` | `npm run db:migrate:remote && wrangler deploy` | Deploy to production |\n| `db:migrate:local` | Runs auth + features migrations locally | Apply migrations to local D1 |\n| `db:migrate:remote` | Runs auth + features migrations remotely | Apply migrations to production D1 |\n\n## Next Steps\n\n- [Add a new feature](/compiler/definitions/schema) — Define your own tables with security\n- [Configure access control](/compiler/definitions/access) — Set role-based permissions\n- [Add custom actions](/compiler/definitions/actions) — Business logic beyond CRUD\n- [Environment variables](/compiler/config/variables) — Configure secrets and bindings"
147
143
  },
148
144
  "compiler/getting-started/template-empty": {
149
145
  "title": "Empty Scaffolding Templates",
150
- "content": "The empty templates create a project with only the configuration file — no example features. Use these when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n| `empty-bun` | Bun | better-sqlite3 | `quickback create empty-bun my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\n# Cloudflare Workers\nquickback create empty my-app\n\n# Bun / local development\nquickback create empty-bun my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n### Cloudflare (empty)\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\n### Bun (empty-bun)\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"bun\", config: {} },\n database: {\n name: \"better-sqlite3\",\n config: { path: \"./data/app.db\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nBoth use multi-tenant mode (`organizations: true`) by default. Change to `organizations: false` for [single-tenant mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n ],\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"owner\", \"admin\", \"member\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"admin\"] } },\n update: { access: { roles: [\"owner\", \"admin\"] } },\n delete: { access: { roles: [\"owner\", \"admin\"] }, mode: \"soft\" },\n },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the full templates:\n\n- **Cloudflare**: [Cloudflare Template setup](/compiler/getting-started/template-cloudflare#setup-steps)\n- **Bun**: [Bun Template setup](/compiler/getting-started/template-bun#setup-steps)\n\nThe only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
146
+ "content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nMulti-tenant mode (`organizations: true`) is the default. Change to `organizations: false` for [single-tenant mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: { mode: \"optional\" },\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n crud: {\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
151
147
  },
152
148
  "compiler/getting-started/templates": {
153
149
  "title": "Templates",
154
- "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\n## Available Templates\n\n### Full-Featured Templates\n\nThese templates include an example feature (todos) with full security configuration.\n\n| Template | Runtime | Database | Auth | Tenant | Command |\n|----------|---------|----------|------|--------|---------|\n| `cloudflare` | Cloudflare Workers | D1 (SQLite) | Better Auth | Multi-tenant | `quickback create cloudflare my-app` |\n| `bun` | Bun | better-sqlite3 | Better Auth | Multi-tenant | `quickback create bun my-app` |\n| `turso` | Bun | LibSQL (Turso) | Better Auth | Multi-tenant | `quickback create turso my-app` |\n\n### Starter Templates\n\nPurpose-built templates with opinionated defaults for common use cases.\n\n| Template | Runtime | Database | Tenant | Command |\n|----------|---------|----------|--------|---------|\n| `blog` | Cloudflare Workers | D1 | Single-tenant | `quickback create blog my-site` |\n\nThe **blog** template creates a single-tenant blog/CMS backend with:\n- Public read access (no auth required for `list` and `get`)\n- Admin-only write access (create, update, delete, publish/unpublish)\n- A `posts` feature with title, slug, content, status, and publish date\n- [Single-tenant mode](/compiler/config/single-tenant) (`organizations: false`)\n\n### Empty Scaffolding\n\nStart from scratch with just the config file — no example features. Add your own definitions.\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n| `empty-bun` | Bun | better-sqlite3 | `quickback create empty-bun my-app` |\n\nThese create the project structure with `quickback.config.ts` only — no `features/` directory. Run `quickback init` inside the project to scaffold your first feature.\n\n## What Each Template Includes\n\nFull-featured and starter templates scaffold a complete project with:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Example feature(s) with security configuration\n- **Deployment scripts** — `npm run deploy` for Cloudflare, `npm start` for Bun\n\nEmpty templates include only:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`package.json`** — Dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare (Recommended for Production)\n\nBest for production deployments. Runs on Cloudflare's global edge network with zero cold starts. Includes D1 (SQLite at the edge), KV storage, and R2 file storage.\n\n- Free tier available (Workers free plan)\n- Global edge deployment\n- Built-in KV, R2, Queues, Vectorize\n- Dual database mode (separate auth and features DBs)\n\n### Bun (Best for Local Development)\n\nBest for local development and prototyping. Runs on Bun with a local SQLite file. No cloud account needed.\n\n- No cloud setup required\n- Fast local iteration\n- SQLite file stored in `data/` directory\n- Easy to switch to Cloudflare later\n\n### Turso (Best for Multi-Region)\n\nBest when you need SQLite with multi-region replication. Uses LibSQL via Turso's managed service.\n\n- Multi-region database replication\n- SQLite compatibility\n- Managed backups and branching\n\n### Blog (Single-Tenant CMS)\n\nBest for personal sites, blogs, or any app with a single tenant. Uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, roles come from `user.role`.\n\n- Public JSON API for content\n- Admin-only editing via Better Auth admin plugin\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty (Start from Scratch)\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n- Config-only scaffolding\n- Available for both Cloudflare and Bun runtimes\n- Add features with `quickback init` or by hand\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Template |\n|-------|----------|\n| `cf` | `betterauth-d1-cloudflare` |\n| `local` | `betterauth-sqlite-bun` |\n| `saas` | `b2bsaas-cloudflare` |\n| `minimal` | `api-minimal-bun` |\n| `scaffold` | `empty-cloudflare` |\n\n## After Creating a Project\n\n```bash\n# 1. Create the project\nquickback create cloudflare my-app\ncd my-app\n\n# 2. Log in to the compiler\nquickback login\n\n# 3. Compile your definitions\nquickback compile\n\n# 4. Run locally\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Bun Template](/compiler/getting-started/template-bun)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Single-Tenant Mode](/compiler/config/single-tenant)"
150
+ "content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\n## Available Templates\n\n### Full-Featured Templates\n\nThese templates include an example feature (todos) with full security configuration.\n\n| Template | Runtime | Database | Auth | Tenant | Command |\n|----------|---------|----------|------|--------|---------|\n| `cloudflare` | Cloudflare Workers | D1 (SQLite) | Better Auth | Multi-tenant | `quickback create cloudflare my-app` |\n| `multi-tenant` | Cloudflare Workers | D1 (SQLite) | Better Auth | Multi-tenant + orgs | `quickback create multi-tenant my-app` |\n\n### Starter Templates\n\nPurpose-built templates with opinionated defaults for common use cases.\n\n| Template | Runtime | Database | Tenant | Command |\n|----------|---------|----------|--------|---------|\n| `blog` | Cloudflare Workers | D1 | Single-tenant | `quickback create blog my-site` |\n\nThe **blog** template creates a single-tenant blog/CMS backend with:\n- Public read access (no auth required for `list` and `get`)\n- Admin-only write access (create, update, delete, publish/unpublish)\n- A `posts` feature with title, slug, content, status, and publish date\n- [Single-tenant mode](/compiler/config/single-tenant) (`organizations: false`)\n\n### Empty Scaffolding\n\nStart from scratch with just the config file — no example features. Add your own definitions.\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nThese create the project structure with `quickback.config.ts` only — no `features/` directory. Run `quickback init` inside the project to scaffold your first feature.\n\n## What Each Template Includes\n\nFull-featured and starter templates scaffold a complete project with:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Example feature(s) with security configuration\n- **Deployment scripts** — `npm run deploy` for Cloudflare, `npm start` for Bun\n\nEmpty templates include only:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`package.json`** — Dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare (Recommended for Production)\n\nBest for production deployments. Runs on Cloudflare's global edge network with zero cold starts. Includes D1 (SQLite at the edge), KV storage, and R2 file storage.\n\n- Free tier available (Workers free plan)\n- Global edge deployment\n- Built-in KV, R2, Queues, Vectorize\n- Dual database mode (separate auth and features DBs)\n\n### Blog (Single-Tenant CMS)\n\nBest for personal sites, blogs, or any app with a single tenant. Uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, roles come from `user.role`.\n\n- Public JSON API for content\n- Admin-only editing via Better Auth admin plugin\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty (Start from Scratch)\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n- Config-only scaffolding\n- Cloudflare Workers + D1 runtime\n- Add features with `quickback init` or by hand\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Template |\n|-------|----------|\n| `cf` | `betterauth-d1-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `scaffold` | `empty-cloudflare` |\n\n## After Creating a Project\n\n```bash\n# 1. Create the project\nquickback create cloudflare my-app\ncd my-app\n\n# 2. Log in to the compiler\nquickback login\n\n# 3. Compile your definitions\nquickback compile\n\n# 4. Run locally\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Single-Tenant Mode](/compiler/config/single-tenant)"
155
151
  },
156
152
  "compiler": {
157
153
  "title": "Quickback Compiler",
@@ -199,7 +195,7 @@ export const DOCS = {
199
195
  },
200
196
  "compiler/targets/hono-api/using-the-api/errors": {
201
197
  "title": "Errors",
202
- "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |"
198
+ "content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n### Database\n\nSurfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or `UNIQUE` constraint hit at the storage layer (e.g. an FK target was deleted concurrently, or a unique column collided with another tenant's row). All four codes share the same `layer: \"database\"` so consumers can switch on the layer alone and treat the rest as one bucket.\n\n```json\n{\n \"error\": \"Duplicate value\",\n \"layer\": \"database\",\n \"code\": \"DB_UNIQUE_VIOLATION\",\n \"details\": { \"column\": \"email\" },\n \"hint\": \"A record with this \\\"email\\\" already exists\"\n}\n```\n\n**Error codes:**\n\n| Code | Status | Description |\n|------|--------|-------------|\n| `DB_NOT_NULL_VIOLATION` | 400 | Required column was null at write time |\n| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |\n| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |\n| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |\n\nThe `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |"
203
199
  },
204
200
  "compiler/targets/hono-api/using-the-api": {
205
201
  "title": "Using the API",
@@ -207,7 +203,7 @@ export const DOCS = {
207
203
  },
208
204
  "compiler/targets/hono-api/using-the-api/openapi": {
209
205
  "title": "OpenAPI Spec",
210
- "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: 'src/lib/api-types.gen.ts', // emit straight into your client app\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. Skipped automatically when `openapi.generate` is `false`.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```"
206
+ "content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. Simple `z.object({...})` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: 'src/lib/api-types.gen.ts', // emit straight into your client app\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. Skipped automatically when `openapi.generate` is `false`.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```"
211
207
  },
212
208
  "compiler/targets/hono-api/using-the-api/query-params": {
213
209
  "title": "Query Parameters",
@@ -509,7 +505,6 @@ export const TOPIC_LIST = [
509
505
  "compiler/getting-started",
510
506
  "compiler/getting-started/patterns",
511
507
  "compiler/getting-started/template-blog",
512
- "compiler/getting-started/template-bun",
513
508
  "compiler/getting-started/template-cloudflare",
514
509
  "compiler/getting-started/template-empty",
515
510
  "compiler/getting-started/templates",