@quickback-dev/cli 0.9.6 → 0.10.1
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.
- package/README.md +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +35 -30
- package/dist/docs/content.js.map +1 -1
- package/dist/examples/recruitment.tar.gz +0 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +14 -14
- package/src/examples/recruitment.tar.gz +0 -0
package/dist/docs/content.js
CHANGED
|
@@ -67,7 +67,7 @@ export const DOCS = {
|
|
|
67
67
|
},
|
|
68
68
|
"changelog": {
|
|
69
69
|
"title": "Changelog",
|
|
70
|
-
"content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\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](/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](/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](/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/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/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/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)"
|
|
70
|
+
"content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\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/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](/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](/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](/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/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/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/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)"
|
|
71
71
|
},
|
|
72
72
|
"cms/actions": {
|
|
73
73
|
"title": "Actions",
|
|
@@ -99,7 +99,7 @@ export const DOCS = {
|
|
|
99
99
|
},
|
|
100
100
|
"cms/record-layouts": {
|
|
101
101
|
"title": "Record Layouts",
|
|
102
|
-
"content": "# Record Layouts\n\nThe CMS record detail page groups fields into collapsible sections. By default, fields are auto-grouped by naming heuristics (Identity, Contact Info, Financial, etc.). With **record layouts**, you control the exact grouping.\n\nThere are two layers:\n\n1. **Code-defined layouts** — developers configure named layouts in `defineTable()`\n2. **User-created views** — end-users create and save custom views via the CMS UI\n\n## Code-Defined Layouts\n\nAdd a `layouts` property to your `defineTable()` config:\n\n```typescript\nexport default defineTable(contacts, {\n firewall: {
|
|
102
|
+
"content": "# Record Layouts\n\nThe CMS record detail page groups fields into collapsible sections. By default, fields are auto-grouped by naming heuristics (Identity, Contact Info, Financial, etc.). With **record layouts**, you control the exact grouping.\n\nThere are two layers:\n\n1. **Code-defined layouts** — developers configure named layouts in `defineTable()`\n2. **User-created views** — end-users create and save custom views via the CMS UI\n\n## Code-Defined Layouts\n\nAdd a `layouts` property to your `defineTable()` config:\n\n```typescript\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n crud: { /* ... */ },\n layouts: {\n default: {\n sections: [\n { label: \"Contact Info\", columns: 2, fields: [\"name\", \"email\", \"phone\", \"mobile\"] },\n { label: \"Address\", columns: 2, fields: [\"address1\", \"address2\", \"city\", \"state\", \"zip\"] },\n { label: \"Internal Notes\", collapsed: true, fields: [\"notes\", \"internalNotes\"] }\n ]\n },\n compact: {\n sections: [\n { label: \"Summary\", fields: [\"name\", \"status\", \"email\"] }\n ]\n }\n }\n});\n```\n\nEach layout has an ordered list of sections. Each section specifies:\n\n| Property | Type | Default | Description |\n|----------|------|---------|-------------|\n| `label` | string | required | Section header text |\n| `fields` | string[] | required | Column names to display |\n| `columns` | `1 \\| 2` | `1` | Number of columns for field layout |\n| `collapsed` | boolean | `false` | Whether the section starts collapsed |\n\nFields not assigned to any section are collected into an \"Other Fields\" section at the bottom.\n\n### Layout Switcher\n\nWhen a table has multiple named layouts, a dropdown appears in the record detail header. Selections persist per table using `localStorage`.\n\nIf only one layout is defined, it's used automatically without showing a dropdown.\n\n## User-Created Custom Views\n\nEnd-users can create their own record layouts via the CMS UI. These are stored in the database and can be shared with other organization members.\n\n### Creating a View\n\n1. Open any record detail page\n2. Click the **+ View** button in the header\n3. In the view builder dialog:\n - Name your view\n - Add sections and assign fields from a dropdown\n - Set columns (1 or 2) and collapsed state per section\n - Optionally share with your organization\n4. Click **Create View**\n\nThe new view appears in the layout dropdown alongside code-defined layouts.\n\n### Editing and Deleting Views\n\n- Click the **gear icon** next to the dropdown to edit the current custom view\n- Click the **trash icon** to delete it (with confirmation)\n- Code-defined layouts cannot be edited or deleted from the CMS\n\n### Access Control\n\n| Operation | Who Can Do It |\n|-----------|---------------|\n| Create a view | Any member, admin, or owner |\n| Edit/delete own views | The creator |\n| Edit/delete any view | Admins and owners |\n| View shared views | All organization members |\n\n### Setting Up the Custom View Feature\n\nTo enable user-created views, add a `customView` table to your Quickback project:\n\n```typescript\n// quickback/features/cms/custom-view.ts\n\nexport const customView = sqliteTable(\"custom_view\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n tableName: text(\"table_name\").notNull(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n layoutConfig: text(\"layout_config\").notNull(),\n isShared: integer(\"is_shared\", { mode: \"boolean\" }).default(false),\n});\n\nexport default defineTable(customView, {\n displayColumn: \"name\",\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n access: { roles: [\"owner\", \"admin\", \"member\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"admin\", \"member\"] } },\n update: {\n access: {\n or: [\n { roles: [\"owner\", \"admin\"] },\n { roles: [\"member\"], record: { createdBy: { equals: \"$userId\" } } }\n ]\n }\n },\n delete: {\n access: {\n or: [\n { roles: [\"owner\", \"admin\"] },\n { roles: [\"member\"], record: { createdBy: { equals: \"$userId\" } } }\n ]\n },\n mode: \"hard\"\n }\n },\n guards: {\n createable: [\"tableName\", \"name\", \"description\", \"layoutConfig\", \"isShared\"],\n updatable: [\"name\", \"description\", \"layoutConfig\", \"isShared\"]\n }\n});\n```\n\nCompile your project to generate the API endpoints. The CMS will automatically detect the `customView` table and enable the view builder UI.\n\n## Fallback Behavior\n\n| Scenario | Result |\n|----------|--------|\n| No `layouts` config, no custom views | Auto-grouping by naming heuristics |\n| `layouts` config defined | Uses \"default\" layout or first available |\n| Multiple layouts | Dropdown for switching, persisted per table |\n| Custom views created | Appear in dropdown below code-defined layouts |\n\n## Next Steps\n\n- **[Table Views](/cms/table-views)** — Column projections for list views\n- **[Schema Format](/cms/schema-format)** — Full TypeScript type reference\n- **[Database Schema](/compiler/definitions/schema)** — defineTable() configuration reference"
|
|
103
103
|
},
|
|
104
104
|
"cms/schema-format": {
|
|
105
105
|
"title": "Schema Format Reference",
|
|
@@ -111,11 +111,11 @@ export const DOCS = {
|
|
|
111
111
|
},
|
|
112
112
|
"cms/security": {
|
|
113
113
|
"title": "Security",
|
|
114
|
-
"content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## Gating CMS Access to Platform Admins\n\nBy default the CMS is available to any authenticated user (subject to their org role). To restrict the entire CMS to Better Auth platform admins (`user.role === \"admin\"`), set:\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't access the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.\n4. **`custom_view` CRUD** — the CMS-internal saved-views table uses `userRole: [\"admin\"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.\n5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still renders \"Access Denied\".\n\nYour resource CRUD endpoints keep whatever `crud.access.roles` you defined — they're the app's data API and unaffected by the CMS gate.\n\n## The Four Layers\n\nQuickback enforces security through four complementary layers:\n\n| Layer | Purpose | CMS Behavior |\n|-------|---------|-------------|\n| **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |\n| **CRUD Access** | Per-operation role requirements | Buttons hidden when role lacks permission |\n| **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |\n| **Masking** | Sensitive field redaction | Masked values with lock icons per role |\n\n## Role-Based Access\n\nThe CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:\n\n- **owner** — Full access to all operations and data\n- **admin** — Elevated access, typically all CRUD and most actions\n- **member** — Standard access with restrictions on sensitive data and destructive actions\n\n### CRUD Button Visibility\n\nCRUD operation buttons are shown or hidden based on the current role's access:\n\n```typescript\ncrud: {\n create: { access: { roles: ['admin', 'owner'] } },\n read: { access: { roles: ['member', 'admin', 'owner'] } },\n update: { access: { roles: ['admin', 'owner'] } },\n delete: { access: { roles: ['owner'] } },\n}\n```\n\nWith the config above:\n\n- **Members** see the table (read) but no Create, Edit, or Delete buttons\n- **Admins** see Create and Edit buttons but no Delete\n- **Owners** see all buttons\n\nThe row action menu also adapts — Edit and Delete entries only appear when the role has the corresponding permission.\n\n## Guards\n\nGuards control which fields appear in create and edit forms, and which cells are editable in Data Table mode.\n\n### Createable Fields\n\nFields listed in `guards.createable` appear in the create form. Fields not in this list are hidden from the form entirely:\n\n```typescript\nguards: {\n createable: ['name', 'email', 'phone', 'status'],\n}\n```\n\n### Updatable Fields\n\nFields listed in `guards.updatable` are editable in the edit form and in Data Table inline editing:\n\n```typescript\nguards: {\n updatable: ['name', 'email', 'phone'],\n}\n```\n\n### Immutable Fields\n\nFields in `guards.immutable` can be set during creation but cannot be changed afterward. In edit mode, they appear as disabled inputs with a lock icon:\n\n```typescript\nguards: {\n immutable: ['accountCode', 'type'],\n}\n```\n\n### Protected Fields\n\nFields in `guards.protected` can only be updated via specific actions. They appear as disabled inputs with the message \"Updated via actions only\":\n\n```typescript\nguards: {\n protected: {\n status: ['approve', 'void'], // Updated by approve or void actions\n balance: ['applyPayment'], // Updated by applyPayment action\n },\n}\n```\n\n## Masking\n\nMasking rules redact sensitive data based on the user's role. The CMS applies masking client-side for display and the API enforces it server-side in responses.\n\n### Masking Types\n\n| Type | Example Input | Masked Output |\n|------|--------------|---------------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | `Confidential notes` | `------` |\n\n### Configuration\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin', 'owner'] } },\n phone: { type: 'phone', show: { roles: ['admin', 'owner'] } },\n ssn: { type: 'ssn', show: { roles: ['owner'] } },\n}\n```\n\nWith the above config:\n\n- **Members** see masked values for email, phone, and SSN\n- **Admins** see unmasked email and phone, but masked SSN\n- **Owners** see all values unmasked\n\n### Visual Indicator\n\nMasked fields display a lock icon next to the redacted value, making it clear that the field contains hidden data:\n\n```\nEmail: [lock] j***@acme.com\nSSN: [lock] ***-**-6789\n```\n\n## Views\n\nViews provide column-level projections per role. Only authorized views appear in the toolbar dropdown.\n\n```typescript\
|
|
114
|
+
"content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## Gating CMS Access to Platform Admins\n\nBy default the CMS is available to any authenticated user (subject to their org role). To restrict the entire CMS to Better Auth platform admins (`user.role === \"admin\"`), set:\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't access the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.\n4. **`custom_view` CRUD** — the CMS-internal saved-views table uses `userRole: [\"admin\"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.\n5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still renders \"Access Denied\".\n\nYour resource CRUD endpoints keep whatever `crud.access.roles` you defined — they're the app's data API and unaffected by the CMS gate.\n\n## The Four Layers\n\nQuickback enforces security through four complementary layers:\n\n| Layer | Purpose | CMS Behavior |\n|-------|---------|-------------|\n| **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |\n| **CRUD Access** | Per-operation role requirements | Buttons hidden when role lacks permission |\n| **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |\n| **Masking** | Sensitive field redaction | Masked values with lock icons per role |\n\n## Role-Based Access\n\nThe CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:\n\n- **owner** — Full access to all operations and data\n- **admin** — Elevated access, typically all CRUD and most actions\n- **member** — Standard access with restrictions on sensitive data and destructive actions\n\n### CRUD Button Visibility\n\nCRUD operation buttons are shown or hidden based on the current role's access:\n\n```typescript\ncrud: {\n create: { access: { roles: ['admin', 'owner'] } },\n read: { access: { roles: ['member', 'admin', 'owner'] } },\n update: { access: { roles: ['admin', 'owner'] } },\n delete: { access: { roles: ['owner'] } },\n}\n```\n\nWith the config above:\n\n- **Members** see the table (read) but no Create, Edit, or Delete buttons\n- **Admins** see Create and Edit buttons but no Delete\n- **Owners** see all buttons\n\nThe row action menu also adapts — Edit and Delete entries only appear when the role has the corresponding permission.\n\n## Guards\n\nGuards control which fields appear in create and edit forms, and which cells are editable in Data Table mode.\n\n### Createable Fields\n\nFields listed in `guards.createable` appear in the create form. Fields not in this list are hidden from the form entirely:\n\n```typescript\nguards: {\n createable: ['name', 'email', 'phone', 'status'],\n}\n```\n\n### Updatable Fields\n\nFields listed in `guards.updatable` are editable in the edit form and in Data Table inline editing:\n\n```typescript\nguards: {\n updatable: ['name', 'email', 'phone'],\n}\n```\n\n### Immutable Fields\n\nFields in `guards.immutable` can be set during creation but cannot be changed afterward. In edit mode, they appear as disabled inputs with a lock icon:\n\n```typescript\nguards: {\n immutable: ['accountCode', 'type'],\n}\n```\n\n### Protected Fields\n\nFields in `guards.protected` can only be updated via specific actions. They appear as disabled inputs with the message \"Updated via actions only\":\n\n```typescript\nguards: {\n protected: {\n status: ['approve', 'void'], // Updated by approve or void actions\n balance: ['applyPayment'], // Updated by applyPayment action\n },\n}\n```\n\n## Masking\n\nMasking rules redact sensitive data based on the user's role. The CMS applies masking client-side for display and the API enforces it server-side in responses.\n\n### Masking Types\n\n| Type | Example Input | Masked Output |\n|------|--------------|---------------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | `Confidential notes` | `------` |\n\n### Configuration\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin', 'owner'] } },\n phone: { type: 'phone', show: { roles: ['admin', 'owner'] } },\n ssn: { type: 'ssn', show: { roles: ['owner'] } },\n}\n```\n\nWith the above config:\n\n- **Members** see masked values for email, phone, and SSN\n- **Admins** see unmasked email and phone, but masked SSN\n- **Owners** see all values unmasked\n\n### Visual Indicator\n\nMasked fields display a lock icon next to the redacted value, making it clear that the field contains hidden data:\n\n```\nEmail: [lock] j***@acme.com\nSSN: [lock] ***-**-6789\n```\n\n## Views\n\nViews provide column-level projections per role. Only authorized views appear in the toolbar dropdown.\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin', 'owner'] },\n },\n financial: {\n fields: ['id', 'name', 'balance', 'creditLimit', 'paymentTerms'],\n access: { roles: ['admin', 'owner'] },\n },\n },\n}\n```\n\nMembers only see the \"summary\" view option. Admins and owners see both \"summary\" and \"financial\". The \"All Fields\" option is always available.\n\n## Firewall\n\nThe firewall layer handles tenant isolation — ensuring users can only access data within their organization. This is enforced entirely server-side:\n\n- `organization_id` columns are filtered automatically by the API\n- `owner` mode restricts records to the creating user\n- The CMS never sees data outside the user's organization scope\n\nThe CMS does not display firewall config in its UI because there is nothing for the user to control. Tenant isolation is transparent and automatic.\n\n## Actions\n\nAction visibility is controlled by access conditions on each action:\n\n```typescript\nactions: {\n approve: {\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'pending' } },\n },\n cms: { destructive: true, confirm: true },\n },\n}\n```\n\nThe CMS evaluates both the role requirement and the record condition. In this example, the \"Approve\" action only appears for admins and owners, and only on records where `status === \"pending\"`.\n\nDestructive actions (`cms.destructive: true`, or named `void`/`delete`) receive special warning styling with red text and an alert icon. Actions with `cms.hidden: true` are hidden from the CMS entirely (API-only).\n\n## Next Steps\n\n- **[Actions](/cms/actions)** — Action dialogs and input forms\n- **[Table Views](/cms/table-views)** — View projections and toolbar\n- **[Inline Editing](/cms/inline-editing)** — How guards affect editability"
|
|
115
115
|
},
|
|
116
116
|
"cms/table-views": {
|
|
117
117
|
"title": "Table Views",
|
|
118
|
-
"content": "# Table Views\n\nThe CMS provides two view modes for every table: **Table** mode for browsing and navigating records, and **Data Table** mode for spreadsheet-style inline editing. Switch between them with the toolbar toggle.\n\n## Table Mode\n\nTable mode is the default browse experience:\n\n- **Click rows** to navigate to the record detail view\n- **Row action menus** (three-dot icon) with view, edit, delete, and custom actions\n- **Column headers** are sortable — click to toggle ascending/descending\n- **Search bar** for full-text search across all fields\n- **Responsive columns** that adapt to available space\n\nEach row shows the most relevant columns for the table. Foreign key columns display human-readable labels (resolved via `_label` fields) instead of raw UUIDs. Boolean columns render as colored Yes/No badges. Enum columns use color-coded pills.\n\n### Row Actions\n\nThe three-dot menu on each row provides:\n\n| Action | Visibility | Description |\n|--------|-----------|-------------|\n| View details | Always | Navigate to the record detail page |\n| Edit | When role has `update` access | Navigate to the edit form |\n| Custom actions | Filtered by role + record state | Run actions like approve, void, post |\n| Delete | When role has `delete` access | Delete with confirmation |\n\nActions are filtered by the current role's CRUD permissions and the action's access conditions. For example, an \"approve\" action that requires `status === \"pending\"` only appears on pending records.\n\n## Data Table Mode\n\nData Table mode provides an Excel/Google Sheets-like editing experience:\n\n- **Cell selection** with a blue focus ring\n- **Keyboard navigation** using arrow keys, Tab, Enter, and Escape\n- **Type-to-edit** — start typing to enter edit mode on the selected cell\n- **Row numbers** displayed in the leftmost column\n- **Hint bar** at the bottom showing keyboard shortcuts\n\n### Editable Fields\n\nWhich cells are editable is determined by the table's guards:\n\n- Fields in `guards.updatable` are editable\n- Fields in `guards.immutable` are read-only (shown with a disabled style)\n- Fields in `guards.protected` are read-only (marked \"Updated via actions only\")\n- Audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) are always read-only\n\nNon-editable cells can still be selected and copied, but they don't enter edit mode.\n\n### Cell Types\n\n| Column Type | Edit Control | Behavior |\n|-------------|-------------|----------|\n| Text | Text input | Free-text entry |\n| Number | Number input | Numeric entry with step controls |\n| Boolean | Yes/No dropdown | Toggle between Yes and No |\n| FK reference | Typeahead dropdown | Server-side search with debounced queries |\n| Enum | Select dropdown | Choose from allowed values |\n\n### Saving\n\nChanges are auto-saved when you:\n\n- Press **Enter** to confirm and move down\n- Press **Tab** to confirm and move to the next editable cell\n- **Click away** from the editing cell (blur)\n\nPress **Escape** to cancel an edit and revert to the previous value.\n\n## Views\n\nViews are named column projections defined in your table's resource config. They control which columns appear in the table based on the current role.\n\n### Toolbar\n\nThe toolbar shows a view dropdown when the table has views defined. Options include:\n\n- **All Fields** — Shows all columns (default)\n- Custom views — Only show the columns specified in the view config\n\nViews are filtered by role access. If a view's access rules require `admin` and the current user is a `member`, that view won't appear in the dropdown.\n\n### Example\n\nGiven this definition:\n\n```typescript\
|
|
118
|
+
"content": "# Table Views\n\nThe CMS provides two view modes for every table: **Table** mode for browsing and navigating records, and **Data Table** mode for spreadsheet-style inline editing. Switch between them with the toolbar toggle.\n\n## Table Mode\n\nTable mode is the default browse experience:\n\n- **Click rows** to navigate to the record detail view\n- **Row action menus** (three-dot icon) with view, edit, delete, and custom actions\n- **Column headers** are sortable — click to toggle ascending/descending\n- **Search bar** for full-text search across all fields\n- **Responsive columns** that adapt to available space\n\nEach row shows the most relevant columns for the table. Foreign key columns display human-readable labels (resolved via `_label` fields) instead of raw UUIDs. Boolean columns render as colored Yes/No badges. Enum columns use color-coded pills.\n\n### Row Actions\n\nThe three-dot menu on each row provides:\n\n| Action | Visibility | Description |\n|--------|-----------|-------------|\n| View details | Always | Navigate to the record detail page |\n| Edit | When role has `update` access | Navigate to the edit form |\n| Custom actions | Filtered by role + record state | Run actions like approve, void, post |\n| Delete | When role has `delete` access | Delete with confirmation |\n\nActions are filtered by the current role's CRUD permissions and the action's access conditions. For example, an \"approve\" action that requires `status === \"pending\"` only appears on pending records.\n\n## Data Table Mode\n\nData Table mode provides an Excel/Google Sheets-like editing experience:\n\n- **Cell selection** with a blue focus ring\n- **Keyboard navigation** using arrow keys, Tab, Enter, and Escape\n- **Type-to-edit** — start typing to enter edit mode on the selected cell\n- **Row numbers** displayed in the leftmost column\n- **Hint bar** at the bottom showing keyboard shortcuts\n\n### Editable Fields\n\nWhich cells are editable is determined by the table's guards:\n\n- Fields in `guards.updatable` are editable\n- Fields in `guards.immutable` are read-only (shown with a disabled style)\n- Fields in `guards.protected` are read-only (marked \"Updated via actions only\")\n- Audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) are always read-only\n\nNon-editable cells can still be selected and copied, but they don't enter edit mode.\n\n### Cell Types\n\n| Column Type | Edit Control | Behavior |\n|-------------|-------------|----------|\n| Text | Text input | Free-text entry |\n| Number | Number input | Numeric entry with step controls |\n| Boolean | Yes/No dropdown | Toggle between Yes and No |\n| FK reference | Typeahead dropdown | Server-side search with debounced queries |\n| Enum | Select dropdown | Choose from allowed values |\n\n### Saving\n\nChanges are auto-saved when you:\n\n- Press **Enter** to confirm and move down\n- Press **Tab** to confirm and move to the next editable cell\n- **Click away** from the editing cell (blur)\n\nPress **Escape** to cancel an edit and revert to the previous value.\n\n## Views\n\nViews are named column projections defined in your table's resource config. They control which columns appear in the table based on the current role.\n\n### Toolbar\n\nThe toolbar shows a view dropdown when the table has views defined. Options include:\n\n- **All Fields** — Shows all columns (default)\n- Custom views — Only show the columns specified in the view config\n\nViews are filtered by role access. If a view's access rules require `admin` and the current user is a `member`, that view won't appear in the dropdown.\n\n### Example\n\nGiven this definition:\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'status', 'ssn', 'internalNotes'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\n- Members see: \"All Fields\" and \"summary\"\n- Admins see: \"All Fields\", \"summary\", and \"full\"\n- Owners see: \"All Fields\", \"summary\", and \"full\"\n\nWhen a view is selected, the CMS calls the `listView` API endpoint instead of the standard `list`, fetching only the projected columns.\n\n## Default Sort\n\nYou can set a default sort order for a table by adding `defaultSort` to your resource config:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n // ...\n});\n```\n\nWhen the CMS loads the table, it applies this sort automatically. Users can still click column headers to change the sort — `defaultSort` only sets the initial state.\n\n## Pagination\n\nThe bottom of every table view shows pagination controls:\n\n- **Page range indicator** — \"Showing 1-25 of 142\"\n- **Page buttons** — Navigate directly to a page, with ellipsis for large page counts\n- **Previous/Next** arrows\n\nThe default page size is 25 records. The CMS resets to page 1 when you change the search query or switch views.\n\n## Search\n\nThe search bar performs full-text search across all columns. Type a query and the CMS debounces the request, then fetches matching records from the API.\n\nSearch works in both Table and Data Table modes, and works with views (searching within the projected columns).\n\n## Next Steps\n\n- **[Inline Editing](/cms/inline-editing)** — Deep dive into spreadsheet editing, FK typeahead, and keyboard shortcuts\n- **[Security](/cms/security)** — How roles and guards affect the table UI\n- **[Actions](/cms/actions)** — Custom actions in the row menu and detail view"
|
|
119
119
|
},
|
|
120
120
|
"compiler/cloud-compiler/authentication": {
|
|
121
121
|
"title": "Authentication",
|
|
@@ -167,7 +167,7 @@ export const DOCS = {
|
|
|
167
167
|
},
|
|
168
168
|
"compiler/config/single-tenant": {
|
|
169
169
|
"title": "Single-Tenant Mode",
|
|
170
|
-
"content": "Single-tenant mode disables the Better Auth organization plugin, removing the `organizationId` requirement from your API. This is ideal for personal sites, blogs, admin panels, or any app with a single tenant.\n\n## Enabling Single-Tenant Mode\n\nSet `features.organizations` to `false` in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## What Changes\n\n| Aspect | Multi-Tenant (default) | Single-Tenant |\n|--------|----------------------|---------------|\n| Organization plugin | Enabled | Disabled |\n| `organizationId` columns | Required on resources | Not used |\n| Role source | Org membership table | `user.role` field |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |\n| Admin org endpoints | `/admin/v1/organizations` generated | Skipped |\n| `ctx.activeOrgId` | From session/JWT | Always `undefined` |\n| `ctx.roles` | From org member role | From `user.role` |\n\n## Firewall Configuration\n\nIn single-tenant mode, resources use either **owner** scope (user-scoped data) or **exception** (public/system data):\n\n```typescript\n// User-scoped data (requires authentication)\nexport default defineTable(posts, {\n firewall: {
|
|
170
|
+
"content": "Single-tenant mode disables the Better Auth organization plugin, removing the `organizationId` requirement from your API. This is ideal for personal sites, blogs, admin panels, or any app with a single tenant.\n\n## Enabling Single-Tenant Mode\n\nSet `features.organizations` to `false` in your config:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## What Changes\n\n| Aspect | Multi-Tenant (default) | Single-Tenant |\n|--------|----------------------|---------------|\n| Organization plugin | Enabled | Disabled |\n| `organizationId` columns | Required on resources | Not used |\n| Role source | Org membership table | `user.role` field |\n| Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |\n| Admin org endpoints | `/admin/v1/organizations` generated | Skipped |\n| `ctx.activeOrgId` | From session/JWT | Always `undefined` |\n| `ctx.roles` | From org member role | From `user.role` |\n\n## Firewall Configuration\n\nIn single-tenant mode, resources use either **owner** scope (user-scoped data) or **exception** (public/system data):\n\n```typescript\n// User-scoped data (requires authentication)\nexport default defineTable(posts, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: ['user', 'admin'] },\n },\n crud: {\n create: { access: { roles: ['admin'] } },\n },\n});\n\n// Public data (no ownership filtering)\nexport default defineTable(pages, {\n firewall: [{ exception: true }],\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\n## Public Routes\n\nUse the `PUBLIC` role to expose routes without authentication. This works the same as in multi-tenant mode:\n\n```typescript\nread: {\n access: { roles: ['PUBLIC'] }, // GET / and GET /:id — no auth required\n},\ncrud: {\n create: { access: { roles: ['admin'] } }, // Admin only\n}\n```\n\n## Role-Based Access\n\nRoles come from the `user.role` field (managed by Better Auth's [admin plugin](https://www.better-auth.com/docs/plugins/admin)).\n\n| Role | Description |\n|------|-------------|\n| `admin` | Full access, set via Better Auth admin plugin |\n| `user` | Default role for authenticated users |\n| `PUBLIC` | Unauthenticated access (special keyword) |\n\n```typescript\n// Admin-only action\nexport default defineActions({\n publish: {\n access: { roles: ['admin'] },\n execute: async ({ ctx, db }) => {\n // ctx.userRole === 'admin'\n // ctx.roles === ['admin']\n },\n },\n});\n```\n\n## Consuming the API\n\nSince single-tenant mode produces 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', content: '...' }),\n});\n```"
|
|
171
171
|
},
|
|
172
172
|
"compiler/config/variables": {
|
|
173
173
|
"title": "Environment Variables",
|
|
@@ -175,11 +175,11 @@ export const DOCS = {
|
|
|
175
175
|
},
|
|
176
176
|
"compiler/definitions/access": {
|
|
177
177
|
"title": "Access - Role & Condition-Based Access Control",
|
|
178
|
-
"content": "Define who can perform CRUD operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: { organization: {} },\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n crud: {\n list: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n get: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n}\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- `PUBLIC` cannot use the `+` suffix\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\ncrud: {\n list: { access: { userRole: ['admin'] } },\n get: { access: { userRole: ['admin'] } },\n create: { access: { userRole: ['admin'] } },\n update: { access: { userRole: ['admin'] } },\n delete: { access: { userRole: ['admin'] } },\n}\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Special Role: `PUBLIC`\n\nUse `roles: [\"PUBLIC\"]` to make an endpoint accessible without authentication. This is intended for public-facing endpoints like contact forms, public listings, or webhooks.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **Firewall still applies** — data is still scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it will throw a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: { exception: true }`\n\n#### PUBLIC on Org-Scoped Tables\n\nFor org-scoped tables, PUBLIC routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a **query parameter**:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThis returns only that organization's records — the firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` error with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: { organization: {} },\n crud: {\n list: { access: { roles: [\"PUBLIC\"] } }, // Public browsing\n get: { access: { roles: [\"PUBLIC\"] } }, // Public detail view\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n },\n});\n```\n\n```typescript\n// Contact form — public, no auth\naccess: { roles: [\"PUBLIC\"] }\n\n// Any authenticated user with any org role\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\n\n// Admin and above\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\n\n// Specific role only (no hierarchy expansion)\naccess: { roles: [\"admin\"] }\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## CRUD Configuration\n\n```typescript\ncrud: {\n // LIST - GET /resource\n list: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n fields: ['id', 'candidateId', 'jobId', 'stage'], // Selective field returns (optional)\n },\n\n // GET - GET /resource/:id\n get: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n fields: ['id', 'candidateId', 'jobId', 'stage', 'notes'], // Optional field selection\n },\n\n // CREATE - POST /resource\n create: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n },\n\n // UPDATE - PATCH /resource/:id\n update: {\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n },\n\n // DELETE - DELETE /resource/:id\n delete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n },\n\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n put: {\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n },\n}\n```\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\ncrud: {\n update: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
|
|
178
|
+
"content": "Define who can perform CRUD operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncrud: {\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n}\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- `PUBLIC` cannot use the `+` suffix\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncrud: {\n create: { access: { userRole: ['admin'] } },\n update: { access: { userRole: ['admin'] } },\n delete: { access: { userRole: ['admin'] } },\n}\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Special Role: `PUBLIC`\n\nUse `roles: [\"PUBLIC\"]` to make an endpoint accessible without authentication. This is intended for public-facing endpoints like contact forms, public listings, or webhooks.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **Firewall still applies** — data is still scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it will throw a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\n#### PUBLIC on Org-Scoped Tables\n\nFor org-scoped tables, PUBLIC routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a **query parameter**:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThis returns only that organization's records — the firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` error with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n crud: {\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n },\n});\n```\n\n```typescript\n// Contact form — public, no auth\naccess: { roles: [\"PUBLIC\"] }\n\n// Any authenticated user with any org role\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\n\n// Admin and above\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\n\n// Specific role only (no hierarchy expansion)\naccess: { roles: [\"admin\"] }\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Read & CRUD Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under `crud:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncrud: {\n // CREATE - POST /resource\n create: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n },\n\n // UPDATE - PATCH /resource/:id\n update: {\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n },\n\n // DELETE - DELETE /resource/:id\n delete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n },\n\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n put: {\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\ncrud: {\n update: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
|
|
179
179
|
},
|
|
180
180
|
"compiler/definitions/actions": {
|
|
181
181
|
"title": "Actions",
|
|
182
|
-
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` or `/{actionName}` |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\n## Defining Actions\n\nActions are defined in a separate `actions.ts` file that references your table:\n\n```typescript\n// features/applications/actions.ts\n\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({ stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]), notes: z.string().optional() }),\n access: { roles: [\"owner\", \"hiring-manager\"] },\n execute: async ({ db, record, ctx }) => {\n // Business logic\n return record;\n },\n },\n});\n```\n\n> **Import style.** With `feature()` (the recommended default), use a **default import** — `import applications from './applications'`. With the two-export form (`q.table()` + `defineTable()`), use a **named import** — `import { applications } from './applications'`. Both resolve to the same typed table handle.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes* | Inline execution function |\n| `handler` | Yes* | File path for complex logic (alternative to `execute`) |\n| `standalone` | No | Set `true` for non-record actions |\n| `path` | No | Custom route path (standalone only) |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST) |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: 'sync', 'async', or 'fire-and-forget' |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute/handler code |\n| `unsafe` | No | Unsafe raw DB mode. Use `true` (legacy) or object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`) |\n\n*Either `execute` or `handler` is required, not both.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance-stage\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions.ts\n\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } }, // Precondition\n },\n execute: async ({ db, ctx, record, input }) => {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(q.eq(applications.id, record.id))\n .returning();\n\n return updated;\n },\n },\n});\n```\n\n> **Query helpers.** Quickback's compiled projects generate `src/lib/q.ts` that re-exports Drizzle's query builders under the same `q` namespace you use for schema authoring — `q.eq`, `q.and`, `q.or`, `q.gte`, `q.desc`, etc. Your handler stays inside one DSL. You can still `import { eq } from 'drizzle-orm'` directly if you prefer; `q` is just a consistent surface.\n\n### Request Example\n\n```\nPOST /applications/app_123/advance-stage\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Use `standalone: true` and optionally specify a custom `path`.\n\n**Route pattern:** Custom `path` or `/{actionName}`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\nexport default defineActions(sessions, {\n chat: {\n description: \"Send a message to AI\",\n standalone: true,\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: {\n roles: [\"recruiter\", \"hiring-manager\"],\n },\n handler: \"./handlers/chat\",\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Example: Report Generation\n\n```typescript\nexport default defineActions(applications, {\n generateReport: {\n description: \"Generate hiring pipeline report\",\n standalone: true,\n path: \"/applications/report\",\n method: \"GET\",\n responseType: \"file\",\n input: z.object({\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n }),\n access: { roles: [\"owner\", \"hiring-manager\"] },\n handler: \"./handlers/generate-report\",\n },\n});\n```\n\n### Actions-Only Features\n\nYou can create feature directories that contain **only standalone actions** — no table definitions required. This is useful for utility endpoints like reports, integrations, or webhooks that don't map to a specific resource.\n\n```\nquickback/features/\n└── reports/\n ├── actions.ts # Standalone actions only (no table file)\n └── handlers/\n ├── trial-balance.ts\n └── profit-loss.ts\n```\n\n```typescript\n// features/reports/actions.ts\nexport default defineActions(null, {\n trialBalance: {\n description: \"Generate trial balance report\",\n standalone: true,\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n handler: \"./handlers/trial-balance\",\n },\n});\n```\n\nPass `null` as the schema argument since there is no table. All actions in a tableless feature **must** have `standalone: true` — record-based actions require a table to operate on.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions.ts\nexport default defineActions(null, {\n submit: {\n description: \"Public contact form submission\",\n standalone: true,\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n handler: \"./handlers/submit\",\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n orgId: { equals: \"$ctx.orgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\nexport default defineActions(applications, {\n adminReport: {\n description: \"Generate cross-org hiring report\",\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n execute: async ({ db, rawDb, ctx, input }) => {\n // db is still scoped (safety net)\n // rawDb bypasses scoped filters\n const allOrgs = await rawDb.select().from(applications);\n return allOrgs;\n },\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- platform admin gate (`ctx.userRole === \"admin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `rawDb` is `undefined` in the executor params.\n\nLegacy `unsafe: true` is still supported, but object mode is recommended so audit logs include an explicit reason.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code and handler files. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\nreconcileLedger: {\n description: \"Run custom reconciliation query\",\n allowRawSql: true,\n input: z.object({}),\n access: { roles: [\"owner\"] },\n execute: async ({ db }) => {\n // Allowed because allowRawSql: true\n return db.execute(sql`select 1`);\n },\n}\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Handler Files\n\nFor complex actions, separate the logic into handler files.\n\n### When to Use Handler Files\n\n- Complex business logic spanning multiple operations\n- External API integrations\n- File generation or processing\n- Logic reused across multiple actions\n\n### Handler Structure\n\n```typescript\n// handlers/generate-report.ts\n\nexport const execute: ActionExecutor = async ({ db, ctx, input, services }) => {\n const apps = await db\n .select()\n .from(applicationsTable)\n .where(between(applicationsTable.createdAt, input.startDate, input.endDate));\n\n const pdf = await services.pdf.generate(apps);\n\n return {\n file: pdf,\n filename: `hiring-report-${input.startDate}-${input.endDate}.pdf`,\n contentType: 'application/pdf',\n };\n};\n```\n\n### Importing Tables\n\nHandler files can import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// handlers/advance-stage.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\nexport const execute: ActionExecutor = async ({ db, ctx, input, c }) => {\n const [job] = await db\n .select()\n .from(jobs)\n .where(eq(jobs.id, input.jobId))\n .limit(1);\n\n if (!job) {\n return c.json({ error: 'Job not found', code: 'NOT_FOUND' }, 404);\n }\n\n // ... continue with business logic\n};\n```\n\n**Path pattern from `features/{name}/handlers/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, orgId)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auditFields: object; // { createdAt, modifiedAt } timestamps\n}\n```\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n```typescript\n// GET action - input comes from query params\ngetStageHistory: {\n method: \"GET\",\n input: z.object({ format: z.string().optional() }),\n // Called as: GET /applications/:id/getStageHistory?format=detailed\n}\n\n// POST action (default) - input comes from JSON body\n'advance-stage': {\n // method: \"POST\" is implied\n input: z.object({ stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]) }),\n // Called as: POST /applications/:id/advance-stage with JSON body\n}\n```\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error |\n| `401` | Not authenticated |\n| `403` | Access check failed (role or precondition) |\n| `404` | Record not found (record-based actions) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nexecute: async ({ ctx, record, input, c }) => {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nexecute: async ({ ctx, record, input }) => {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode, details?)`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In resource.ts\nguards: {\n protected: {\n stage: [\"advance-stage\", \"reject\"], // Only these actions can modify stage\n }\n}\n```\n\nThis allows the `advance-stage` action to set `stage = \"interview\"` even though the field is protected from regular PATCH requests.\n\n## Examples\n\n### Application Stage Advance (Record-Based)\n\n```typescript\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n execute: async ({ db, ctx, record, input }) => {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n },\n});\n```\n\n### AI Chat (Standalone with Streaming)\n\n```typescript\nexport default defineActions(sessions, {\n chat: {\n description: \"Send a message to AI assistant\",\n standalone: true,\n path: \"/chat\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n handler: \"./handlers/chat\",\n },\n});\n```\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\nexport default defineActions(candidates, {\n bulkImport: {\n description: \"Import candidates from job board CSV\",\n standalone: true,\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n execute: async ({ db, input }) => {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n },\n});\n```"
|
|
182
|
+
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` or `/{actionName}` |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\n## Defining Actions\n\nActions are defined in a separate `actions.ts` file that references your table:\n\n```typescript\n// features/applications/actions.ts\n\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({ stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]), notes: z.string().optional() }),\n access: { roles: [\"owner\", \"hiring-manager\"] },\n execute: async ({ db, record, ctx }) => {\n // Business logic\n return record;\n },\n },\n});\n```\n\n> **Import style.** With `feature()` (the recommended default), use a **default import** — `import applications from './applications'`. With the two-export form (`q.table()` + `defineTable()`), use a **named import** — `import { applications } from './applications'`. Both resolve to the same typed table handle.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes* | Inline execution function |\n| `handler` | Yes* | File path for complex logic (alternative to `execute`) |\n| `standalone` | No | Set `true` for non-record actions |\n| `path` | No | Custom route path (standalone only) |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST) |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: 'sync', 'async', or 'fire-and-forget' |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute/handler code |\n| `unsafe` | No | Unsafe raw DB mode. Use `true` (legacy) or object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`) |\n| `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |\n\n*Either `execute` or `handler` is required, not both.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance-stage\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Record Loading** - The record is fetched by ID\n3. **Firewall Check** - Ensures user can access this record\n4. **Access Check** - Validates roles and preconditions\n5. **Input Validation** - Request body validated against Zod schema\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions.ts\n\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } }, // Precondition\n },\n execute: async ({ db, ctx, record, input }) => {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(q.eq(applications.id, record.id))\n .returning();\n\n return updated;\n },\n },\n});\n```\n\n> **Query helpers.** Quickback's compiled projects generate `src/lib/q.ts` that re-exports Drizzle's query builders under the same `q` namespace you use for schema authoring — `q.eq`, `q.and`, `q.or`, `q.gte`, `q.desc`, etc. Your handler stays inside one DSL. You can still `import { eq } from 'drizzle-orm'` directly if you prefer; `q` is just a consistent surface.\n\n### Request Example\n\n```\nPOST /applications/app_123/advance-stage\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Use `standalone: true` and optionally specify a custom `path`.\n\n**Route pattern:** Custom `path` or `/{actionName}`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\nexport default defineActions(sessions, {\n chat: {\n description: \"Send a message to AI\",\n standalone: true,\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: {\n roles: [\"recruiter\", \"hiring-manager\"],\n },\n handler: \"./handlers/chat\",\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Example: Report Generation\n\n```typescript\nexport default defineActions(applications, {\n generateReport: {\n description: \"Generate hiring pipeline report\",\n standalone: true,\n path: \"/applications/report\",\n method: \"GET\",\n responseType: \"file\",\n input: z.object({\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n }),\n access: { roles: [\"owner\", \"hiring-manager\"] },\n handler: \"./handlers/generate-report\",\n },\n});\n```\n\n### Actions-Only Features\n\nYou can create feature directories that contain **only standalone actions** — no table definitions required. This is useful for utility endpoints like reports, integrations, or webhooks that don't map to a specific resource.\n\n```\nquickback/features/\n└── reports/\n ├── actions.ts # Standalone actions only (no table file)\n └── handlers/\n ├── trial-balance.ts\n └── profit-loss.ts\n```\n\n```typescript\n// features/reports/actions.ts\nexport default defineActions(null, {\n trialBalance: {\n description: \"Generate trial balance report\",\n standalone: true,\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n handler: \"./handlers/trial-balance\",\n },\n});\n```\n\nPass `null` as the schema argument since there is no table. All actions in a tableless feature **must** have `standalone: true` — record-based actions require a table to operate on.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions.ts\nexport default defineActions(null, {\n submit: {\n description: \"Public contact form submission\",\n standalone: true,\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n handler: \"./handlers/submit\",\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n orgId: { equals: \"$ctx.orgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\nexport default defineActions(applications, {\n adminReport: {\n description: \"Generate cross-org hiring report\",\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n execute: async ({ db, rawDb, ctx, input }) => {\n // db is still scoped (safety net)\n // rawDb bypasses scoped filters\n const allOrgs = await rawDb.select().from(applications);\n return allOrgs;\n },\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- platform admin gate (`ctx.userRole === \"admin\"`)\n- mandatory audit logging on deny/success/error\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `rawDb` is `undefined` in the executor params.\n\nLegacy `unsafe: true` is still supported, but object mode is recommended so audit logs include an explicit reason.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code and handler files. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\nreconcileLedger: {\n description: \"Run custom reconciliation query\",\n allowRawSql: true,\n input: z.object({}),\n access: { roles: [\"owner\"] },\n execute: async ({ db }) => {\n // Allowed because allowRawSql: true\n return db.execute(sql`select 1`);\n },\n}\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Handler Files\n\nFor complex actions, separate the logic into handler files.\n\n### When to Use Handler Files\n\n- Complex business logic spanning multiple operations\n- External API integrations\n- File generation or processing\n- Logic reused across multiple actions\n\n### Handler Structure\n\n```typescript\n// handlers/generate-report.ts\n\nexport const execute: ActionExecutor = async ({ db, ctx, input, services }) => {\n const apps = await db\n .select()\n .from(applicationsTable)\n .where(between(applicationsTable.createdAt, input.startDate, input.endDate));\n\n const pdf = await services.pdf.generate(apps);\n\n return {\n file: pdf,\n filename: `hiring-report-${input.startDate}-${input.endDate}.pdf`,\n contentType: 'application/pdf',\n };\n};\n```\n\n### Importing Tables\n\nHandler files can import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// handlers/advance-stage.ts\n\n// Same feature — import from parent directory using the table's file name\n\n// Cross-feature — go up to the features directory, then into the other feature\n\nexport const execute: ActionExecutor = async ({ db, ctx, input, c }) => {\n const [job] = await db\n .select()\n .from(jobs)\n .where(eq(jobs.id, input.jobId))\n .limit(1);\n\n if (!job) {\n return c.json({ error: 'Job not found', code: 'NOT_FOUND' }, 404);\n }\n\n // ... continue with business logic\n};\n```\n\n**Path pattern from `features/{name}/handlers/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, orgId)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auditFields: object; // { createdAt, modifiedAt } timestamps\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n}\n```\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// handlers/advance.ts\n\nexport const execute: ActionExecutor = async ({ db, record, input, auditFields, whereRecord }) => {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n modifiedAt: auditFields.modifiedAt,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n};\n```\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n```typescript\n// GET action - input comes from query params\ngetStageHistory: {\n method: \"GET\",\n input: z.object({ format: z.string().optional() }),\n // Called as: GET /applications/:id/getStageHistory?format=detailed\n}\n\n// POST action (default) - input comes from JSON body\n'advance-stage': {\n // method: \"POST\" is implied\n input: z.object({ stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]) }),\n // Called as: POST /applications/:id/advance-stage with JSON body\n}\n```\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nexecute: async ({ ctx, record, input, c }) => {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\n\nexecute: async ({ ctx, record, input }) => {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode, details?)`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In resource.ts\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n\nexport default defineActions(applications, {\n advance: {\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\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n handler: \"./handlers/advance\",\n },\n\n hire: {\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n handler: \"./handlers/hire\",\n },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\n## Examples\n\n### Application Stage Advance (Record-Based)\n\n```typescript\nexport default defineActions(applications, {\n 'advance-stage': {\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n execute: async ({ db, ctx, record, input }) => {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n },\n});\n```\n\n### AI Chat (Standalone with Streaming)\n\n```typescript\nexport default defineActions(sessions, {\n chat: {\n description: \"Send a message to AI assistant\",\n standalone: true,\n path: \"/chat\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n handler: \"./handlers/chat\",\n },\n});\n```\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\nexport default defineActions(candidates, {\n bulkImport: {\n description: \"Import candidates from job board CSV\",\n standalone: true,\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n execute: async ({ db, input }) => {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n },\n});\n```"
|
|
183
183
|
},
|
|
184
184
|
"compiler/definitions/concepts": {
|
|
185
185
|
"title": "Glossary",
|
|
@@ -187,27 +187,31 @@ export const DOCS = {
|
|
|
187
187
|
},
|
|
188
188
|
"compiler/definitions/feature": {
|
|
189
189
|
"title": "feature() — single-export sugar",
|
|
190
|
-
"content": "The `q.table()` + `defineTable()` pair has been co-equal with Drizzle since day one. It works, but it means two exports and two concepts for something most feature files treat as one unit: a table with a security contract.\n\n`feature()` collapses both into a single default export.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: {
|
|
190
|
+
"content": "The `q.table()` + `defineTable()` pair has been co-equal with Drizzle since day one. It works, but it means two exports and two concepts for something most feature files treat as one unit: a table with a security contract.\n\n`feature()` collapses both into a single default export.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n crud: {\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n },\n guards: { createable: [\"address\", \"name\"] },\n});\n\nexport type Contact = typeof contacts.$infer;\n```\n\n## After\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport default feature(\"contacts\", {\n columns: {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n crud: {\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n },\n guards: { createable: [\"address\", \"name\"] },\n});\n```\n\nType inference still works — `typeof import(\"./contacts\").default.$infer` gives you the `Contact` row type.\n\n## How it works\n\n`feature(name, config)` is a **compile-time sugar**, not a runtime abstraction. When the compiler sees `export default feature(...)`, it rewrites the source to the canonical two-export form before any parsing runs. Every downstream layer — dialect pass, audit injection, security contracts, CRUD routes, OpenAPI, MCP tools, RLS emission — runs on the same Drizzle source it always did. Zero runtime cost; zero semantic difference from `q.table()` + `defineTable()`.\n\nThat means:\n\n- **Both forms remain supported indefinitely.** Mix them freely — some files `feature(...)`, some files `q.table() + defineTable()`, some files Drizzle `sqliteTable() + defineTable()`. The compiler dispatches per file.\n- **Action files reference the table by default import.** `import contacts from \"./contacts\"` gives you the same typed handle `q.table(\"contacts\", ...)` would have returned, so `defineActions(contacts, { … })` still works.\n- **Diagnostics are identical.** Missing firewall → same warning. Protected-field wiring → same check. Nothing about `feature()` weakens the secure-by-default posture.\n\n## Aliases\n\n`q` is canonical (matches Zod's `z.`, Superstruct's `s.`). `qb` is exported as an alias if you'd rather self-document the namespace:\n\n```ts\n\nexport default feature(\"contacts\", {\n columns: { id: qb.id(), name: qb.text().required() },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // …\n});\n```\n\nSame object, two names — pick one.\n\n## When to use which\n\n| Pattern | When |\n|---|---|\n| `feature(name, {...})` | Default. One table, one security contract, one file. |\n| `q.table()` + `defineTable()` | Multiple tables per file (rare), or you want to reference the table identifier before the default export. |\n| `sqliteTable()` / `pgTable()` + `defineTable()` | Interop with existing Drizzle code / migrations. |\n| `q.table(...)` alone (no `defineTable`) | Internal join/lookup/pivot tables with no public API. Compiler warns so you confirm the opt-out is intentional. |\n\n## Handlers — one `q` namespace for everything\n\nCustom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:\n\n```ts title=\"quickback/features/mail/handlers/inbound.ts\"\n\nexport const execute = async ({ unsafeDb, input }) => {\n // Find the mailbox this email was addressed to\n const mailbox = await unsafeDb.query.mailboxes.findFirst({\n where: q.eq(mailboxes.address, input.mailboxAddress),\n });\n if (!mailbox) return { error: \"unknown mailbox\" };\n\n // Look up the thread by in-reply-to + organization scope\n const thread = input.parsed.inReplyTo\n ? await unsafeDb.query.threads.findFirst({\n where: q.and(\n q.eq(threads.organizationId, mailbox.organizationId),\n q.eq(threads.lastMessageId, input.parsed.inReplyTo),\n ),\n })\n : null;\n\n // Insert the new message\n await unsafeDb.insert(messages).values({\n id: crypto.randomUUID(),\n threadId: thread?.id,\n organizationId: mailbox.organizationId,\n subject: input.parsed.subject,\n createdAt: new Date().toISOString(),\n });\n\n return { ok: true };\n};\n```\n\nThe `q` in handlers is a runtime re-export of Drizzle's query builder — `q.eq`, `q.and`, `q.or`, `q.not`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export, zero wrapper cost.\n\n**The compiler generates `src/lib/q.ts`** in every project so the runtime `q` is always available. You never need to `import { eq } from \"drizzle-orm\"` in a handler — though you can if you want (Quickback doesn't hide drizzle, it just offers a consistent surface that matches the schema DSL).\n\n## Why one namespace\n\nQuickback is an opinionated wrapper with opinionated security. One DSL for schema (`q.table`, `q.text`, `q.id`), one DSL for queries (`q.eq`, `q.and`, `q.gte`), one opt-in for routes (`feature()` / `defineTable`). You never need to learn the names of the underlying tools to write a feature — the same way Next.js users don't need to know they're using webpack, or Astro users don't need to know they're using Vite."
|
|
191
191
|
},
|
|
192
192
|
"compiler/definitions/firewall": {
|
|
193
193
|
"title": "Firewall - Data Isolation",
|
|
194
|
-
"content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport
|
|
194
|
+
"content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\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 organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly (multi-scope, custom ctx source, or hand-rolled with Drizzle), use the predicate-array form:\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `ownerId` | `{ field: 'ownerId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** 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\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n },\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
|
|
195
195
|
},
|
|
196
196
|
"compiler/definitions/guards": {
|
|
197
197
|
"title": "Guards - Field Modification Rules",
|
|
198
|
-
"content": "Control which fields can be modified in CREATE vs UPDATE operations.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull().default('applied'),\n appliedAt: text('applied_at').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: {
|
|
198
|
+
"content": "Control which fields can be modified in CREATE vs UPDATE operations.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull().default('applied'),\n appliedAt: text('applied_at').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"],\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n },\n crud: {\n // ...\n },\n});\n```\n\n## Configuration Options\n\n```typescript\nguards: {\n // Fields allowed on CREATE\n createable?: string[];\n\n // Fields allowed on UPDATE/PATCH\n updatable?: string[];\n\n // Fields only modifiable via specific actions\n protected?: Record<string, string[]>;\n\n // Fields set on CREATE, never modified after\n immutable?: string[];\n}\n```\n\n## How It Works\n\n| List | What it controls |\n|------|------------------|\n| `createable` | Fields allowed in create (POST) request body |\n| `updatable` | Fields allowed in update (PATCH) request body |\n| `protected` | Fields blocked from CRUD, only modifiable via named actions |\n| `immutable` | Fields allowed on create, blocked on all updates |\n\n**Combining lists:**\n\n- `createable` + `updatable` - Most fields go in both (can set on create AND modify later)\n- `createable` only - Field is set once, cannot be changed via update\n- `protected` - Don't also list in `createable` or `updatable` (they're mutually exclusive)\n- `immutable` - Don't also list in `updatable` (contradiction)\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\", \"source\"],\n updatable: [\"notes\"],\n // \"candidateId\", \"jobId\" are only in createable = set once, can't change via update\n protected: {\n stage: [\"advance-stage\", \"reject\"], // NOT in createable/updatable\n },\n immutable: [\"appliedAt\"], // NOT in updatable\n}\n```\n\n**If a field is not listed anywhere, it cannot be set by the client.**\n\n## System-Managed Fields (Always Protected)\n\n`GUARDS_CONFIG.systemManaged` rejects any field in this set from client input — even with `guards: false`. The set always includes the audit fields:\n\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\nIt also extends with **scope columns** — any firewall predicate whose `equals` references `ctx.*` adds its `field` to systemManaged. Most commonly this comes from `q.scope()`:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → adds 'organizationId' to systemManaged\n}\n```\n\nThe same applies to a hand-rolled firewall:\n\n```typescript\nfirewall: [\n { field: 'tenantId', equals: 'ctx.activeOrgId' }, // → systemManaged\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' }, // → systemManaged\n { field: 'status', equals: 'active' }, // literal, NOT added\n]\n```\n\nThe semantic rule is \"if the firewall says this column's value comes from the request context, the client cannot submit it.\" The value is auto-populated on create / upsert from `ctx`.\n\n## Example\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"], // Only these actions can modify stage\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n}\n```\n\n## Disabling Guards\n\n```typescript\nguards: false // Only system fields protected\n```\n\nWhen `guards: false` is set, all user-defined fields become writable via CRUD operations. This is useful for:\n- External sync scenarios where you need full field control\n- Batch upsert operations where field restrictions would be limiting\n- Simple tables where field-level protection isn't needed\n\n## PUT/Upsert with External IDs\n\nWhen you disable guards AND use client-provided IDs, you unlock PUT (upsert) operations. This is designed for **syncing data from external systems**.\n\n### Requirements for PUT\n\n1. `generateId: false` in database config (client provides IDs)\n2. `guards: false` in resource definition\n\n### How PUT Works\n\n```\nPUT /resource/:id\n├── Record exists? → UPDATE (replace all fields)\n└── Record missing? → CREATE with provided ID\n```\n\n### Database Config\n\n```typescript\n// quickback.config.ts\nexport default {\n database: {\n generateId: false, // Client provides IDs (enables PUT)\n // Other options: 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial'\n }\n};\n```\n\n### Table Definition\n\n```typescript\n// features/integrations/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: false, // Disables field restrictions\n crud: {\n put: {\n access: { roles: ['hiring-manager', 'sync-service'] }\n }\n },\n});\n```\n\n## What's Still Protected with guards: false\n\nEven with `guards: false`, system-managed fields are ALWAYS protected. This includes:\n\n- `createdAt`, `createdBy` — set on INSERT only\n- `modifiedAt`, `modifiedBy` — auto-updated\n- `deletedAt`, `deletedBy` — set on soft delete\n- Any column declared via `q.scope()` (or any firewall predicate using `equals: 'ctx.*'`) — auto-populated from request context\n\nSo `guards: false` only opens up user-defined business fields. Tenant scope and audit fields stay locked down regardless.\n\n## Ownership Auto-Population\n\nWhen PUT creates a new record, ownership fields are auto-set from context:\n\n```typescript\n// Client sends: PUT /ats-imports/ext-123 { candidateName: \"Jane Doe\" }\n// Server creates:\n{\n id: \"ext-123\", // Client-provided\n candidateName: \"Jane Doe\", // Client-provided\n organizationId: ctx.activeOrgId, // Auto-set from firewall\n createdAt: now, // Auto-set\n createdBy: ctx.userId, // Auto-set\n modifiedAt: now, // Auto-set\n modifiedBy: ctx.userId, // Auto-set\n}\n```\n\n## Use Cases for PUT/External IDs\n\n| Use Case | Why PUT? |\n|----------|----------|\n| External API sync | External system controls the ID |\n| Webhook handlers | Events come with their own IDs |\n| Data migration | Preserve IDs from source system |\n| Idempotent updates | Safe to retry (no duplicate creates) |\n| Bulk upsert | Create or update in one operation |\n\n## ID Generation Options\n\n| `generateId` | PUT Available? | Notes |\n|--------------|----------------|-------|\n| `'uuid'` | No | Server generates UUID |\n| `'cuid'` | No | Server generates CUID |\n| `'nanoid'` | No | Server generates nanoid |\n| `'short'` | No | Server generates 6-char alphanumeric ID (e.g. `a3F9xK`) |\n| `'prefixed'` | No | Server generates prefixed ID (e.g. `room_abc123`) |\n| `'serial'` | No | Database auto-increments |\n| `false` | Yes (if guards: false) | Client provides ID |\n\n## Compile-Time Validation\n\nThe Quickback compiler validates your guards configuration and will error if:\n\n1. **Field in both `createable` and `protected`** - A field cannot be both client-writable on create and action-only\n2. **Field in both `updatable` and `protected`** - A field cannot be both client-writable on update and action-only\n3. **Field in both `updatable` and `immutable`** - Contradictory: immutable fields cannot be updated\n4. **Field in `protected` doesn't exist in schema** - Referenced field must exist in the table\n5. **Field in `createable`/`updatable`/`immutable` doesn't exist in schema** - All referenced fields must exist"
|
|
199
199
|
},
|
|
200
200
|
"compiler/definitions": {
|
|
201
201
|
"title": "Definitions Overview",
|
|
202
|
-
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: {
|
|
202
|
+
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\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: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → CRUD routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Four Security Layers\n\nEvery API request passes through four security layers, in order:\n\n```\nRequest → Firewall → Access → Guards → Masking → Response\n │ │ │ │\n │ │ │ └── Hide sensitive fields\n │ │ └── Block field modifications\n │ └── Check roles & conditions\n └── Isolate data by owner/org/team\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under `crud:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncrud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n}\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n2. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n3. **Guards** don't apply to GET (they're for writes)\n\n4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n5. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure CRUD permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Views](/compiler/definitions/views) — Column-level security\n7. [Validation](/compiler/definitions/validation) — Field validation rules\n8. [Actions](/compiler/definitions/actions) — Add custom business logic"
|
|
203
203
|
},
|
|
204
204
|
"compiler/definitions/masking": {
|
|
205
205
|
"title": "Masking - Field Redaction",
|
|
206
|
-
"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
|
|
206
|
+
"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```"
|
|
207
|
+
},
|
|
208
|
+
"compiler/definitions/read": {
|
|
209
|
+
"title": "Read - Unified Read Pipeline",
|
|
210
|
+
"content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\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## What `read` Owns\n\n| Endpoint | Gate |\n|----------|------|\n| `GET /api/v1/{resource}` | `read.access` |\n| `GET /api/v1/{resource}/:id` | `read.access` |\n| `GET /api/v1/{resource}?view={name}` | `read.views[name].access` (falls back to `read.access`) |\n| `GET /api/v1/{resource}/views/{name}` | Same — explicit path form of the `?view=` dispatch |\n\nSingle-record `GET /:id` inherits `read.access` automatically — there's no\nseparate `read.get` block. If you need different access for single records,\nuse record-level conditions on `read.access`:\n\n```typescript\nread: {\n access: {\n or: [\n { roles: ['admin'] },\n { roles: ['member'], record: { ownerId: { equals: '$ctx.userId' } } },\n ],\n },\n}\n```\n\n## Configuration Options\n\n```typescript\ninterface ReadConfig {\n // Role/condition gate for collection reads, single-record reads, and the\n // default view fallback.\n access?: Access;\n\n // Optional read-side firewall override. If omitted, the resource-level\n // `firewall` block is used (the common case).\n firewall?: FirewallConfig;\n\n // Pagination defaults for collection reads.\n pageSize?: number; // Default page size (default: 50)\n maxPageSize?: number; // Hard cap (default: 100)\n\n // Named field projections. Each view has its own access and field list.\n views?: {\n [viewName: string]: ViewConfig;\n };\n}\n\ninterface ViewConfig {\n fields: string[]; // Columns returned by this view\n access?: Access; // Per-view access (falls back to read.access)\n pageSize?: number;\n maxPageSize?: number;\n}\n```\n\n## Access Ordering on `/:id`\n\nSingle-record `GET /:id` evaluates checks in this order to close the\n404-vs-403 ID-probe channel:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nAn unauthorized caller without a matching role gets 403 from step 2 before\nthe database is touched, so they can't distinguish \"row exists in another\ntenant\" from \"row doesn't exist.\" A caller with the right role but the wrong\ntenant gets the firewall's configured response (403 by default; see\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) for an opaque\n404 instead).\n\nFunction-form access is opaque to the pre-check (it always passes there) and\nis fully evaluated post-record, so `access: async (ctx, record) => ...`\nstill works as before.\n\n## Views Under `read.views`\n\nViews are named field projections — Column Level Security. They live under\n`read.views` (not at the resource top level). See\n[Views](/compiler/definitions/views) for the full feature reference.\n\n```typescript\nread: {\n access: { roles: ['member', 'admin'] },\n views: {\n public: {\n fields: ['id', 'title', 'status'],\n access: { roles: ['PUBLIC'] },\n },\n internal: {\n fields: ['id', 'title', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\nBoth endpoint shapes are emitted automatically:\n\n- Query-string dispatch: `GET /api/v1/jobs?view=internal`\n- Explicit path: `GET /api/v1/jobs/views/internal`\n\n## Migrating from `crud.list` / `crud.get`\n\nDSL v2 rejects both at compile time. The migration is mechanical:\n\n| Before (DSL v1) | After (DSL v2) |\n|---|---|\n| `crud.list.access` | `read.access` |\n| `crud.list.pageSize` | `read.pageSize` |\n| `crud.list.maxPageSize` | `read.maxPageSize` |\n| `crud.list.fields: [...]` | Move to a named view under `read.views` |\n| `crud.get.access` | `read.access` (or record-level conditions) |\n| `crud.get.fields: [...]` | Move to a named view; clients call `?view=...` |\n| Top-level `views: {...}` | `read.views: {...}` |\n\nExample before/after:\n\n```typescript\n// Before — DSL v1\ncrud: {\n list: {\n access: { roles: ['member'] },\n pageSize: 25,\n },\n get: {\n access: { roles: ['member'] },\n fields: ['id', 'name', 'status'], // per-field projection\n },\n create: { access: { roles: ['admin'] } },\n}\n\n// After — DSL v2\nread: {\n access: { roles: ['member'] },\n pageSize: 25,\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member'] },\n },\n },\n}\ncrud: {\n create: { access: { roles: ['admin'] } },\n}\n```\n\nClients that previously hit `GET /:id` to retrieve only summary fields now\ncall `GET /:id?view=summary`.\n\n## Read-Only Resources\n\nA resource that exposes only reads is valid with an empty `crud` block (or\nno `crud` block at all):\n\n```typescript\nexport default defineTable(balanceSnapshots, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: ['member', 'admin'] } },\n // no crud — no writes\n});\n```\n\n## See Also\n\n- [Views](/compiler/definitions/views) — Full reference for named projections\n- [Access](/compiler/definitions/access) — Roles, record conditions, and combinators\n- [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`\n- [Views API](/compiler/using-the-api/views-api) — Calling views from clients"
|
|
207
211
|
},
|
|
208
212
|
"compiler/definitions/schema": {
|
|
209
213
|
"title": "Database Schema",
|
|
210
|
-
"content": "Quickback supports three co-equal authoring patterns. All compile to the same generated runtime — the compiler dispatches per file, so every feature in a project may choose independently.\n\n- **`feature()`** — single-export sugar for the `q` DSL. One import, one export, everything about the table and its security contract in one call. **Recommended default.** See [feature() — single-export sugar](/compiler/definitions/feature).\n- **`q.table()` + `defineTable()`** — the two-export form. Same DSL, more explicit. Use when you want to reference the table identifier before the default export (e.g. from an action file).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop with existing Drizzle code. Use when you're bringing an existing schema forward or want dialect-specific column options.\n\n## feature() — the one-call form (default)\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 organizationId: q.text().required(),\n },\n firewall: { organization: {} },\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n crud: {\n list: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n get: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the two-export form\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.text().required(),\n});\n\nexport default defineTable(jobs, {\n firewall: { organization: {} },\n guards: { /* ... */ },\n crud: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a cuid2 app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting — prefixed UUIDs for D1, cuid for libsql/bun-sqlite, `crypto.randomUUID()` for supabase, etc. This keeps q's output decoupled from any specific ID library.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing:\n\n- **Postgres family (Supabase, Neon, D1)** → `snake_case` (`organizationId` → `organization_id`)\n- **SQLite family (bun-sqlite, better-sqlite3, libsql)** → `camelCase` (`organizationId` → `organizationId`)\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'bun-sqlite',\n config: {\n path: './data/app.db',\n namingConvention: 'snake_case', // force snake_case everywhere\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.text('org_id').required(), // SQL name: 'org_id'\n```\n\n## Defining Tables with Drizzle\n\nIf you prefer Drizzle — or have an existing schema you're bringing forward — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\nexport default defineTable(jobs, {\n firewall: { organization: {} },\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n crud: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\n### Choosing Between `q` and Drizzle\n\n| Pick `q` when | Pick Drizzle when |\n|---|---|\n| Starting a new feature from scratch | You already have Drizzle schemas to bring forward |\n| You want the same Zod across actions, forms, and routes | You need Drizzle-specific column options not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types) |\n| You prefer concise, Zod-native syntax | You prefer the explicit Drizzle dialect import per target |\n\nFeatures in the same project may mix freely — Quickback dispatches per feature.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get CRUD routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with CRUD routes\n- **`defineResource`** — Deprecated. Still works but emits a warning during compilation. Use `defineTable` instead.\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all CRUD routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// Internal scoring table - no routes needed\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Always scope junction tables\n});\n\n// No default export = no CRUD routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration.\n\nThe compiler automatically injects **audit fields** (`createdAt`, `modifiedAt`, `deletedAt`, etc.) and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback automatically adds and manages these audit fields on **all tables** in a feature (including child/junction tables without `defineTable`) - you don't need to define them:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set when record is created |\n| `createdBy` | text | User ID who created the record |\n| `modifiedAt` | timestamp | Updated on every change |\n| `modifiedBy` | text | User ID who last modified |\n| `deletedAt` | timestamp | Set on soft delete |\n| `deletedBy` | text | User ID who soft-deleted the record |\n\nAll six fields are injected into every table, including `deletedAt` and `deletedBy`, regardless of whether the resource uses soft-delete mode. This keeps the schema uniform and lets you opt in to soft delete later without a migration. To opt out of audit injection entirely, set `compiler.features.auditFields: false` globally.\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\n### Protected System Fields\n\nThese fields are always protected and cannot be set by clients, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\n## Ownership Fields\n\nFor the firewall to work, include the appropriate ownership columns:\n\n```typescript\n// For organization-scoped data (most common)\norganizationId: text('organization_id').notNull()\n\n// For user-owned data (personal data)\nownerId: text('owner_id').notNull()\n\n// For team-scoped data\nteamId: text('team_id').notNull()\n```\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n firewall: { organization: {} },\n crud: {\n list: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n get: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: { exception: true },\n crud: {\n list: { access: { roles: [\"PUBLIC\"] } },\n get: { access: { roles: [\"PUBLIC\"] } },\n },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (D1, Turso, better-sqlite3)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Supabase, Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for CRUD operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
|
|
214
|
+
"content": "Quickback supports three co-equal authoring patterns. All compile to the same generated runtime — the compiler dispatches per file, so every feature in a project may choose independently.\n\n- **`feature()`** — single-export sugar for the `q` DSL. One import, one export, everything about the table and its security contract in one call. **Recommended default.** See [feature() — single-export sugar](/compiler/definitions/feature).\n- **`q.table()` + `defineTable()`** — the two-export form. Same DSL, more explicit. Use when you want to reference the table identifier before the default export (e.g. from an action file).\n- **Drizzle `sqliteTable()` / `pgTable()` + `defineTable()`** — interop with existing Drizzle code. Use when you're bringing an existing schema forward or want dialect-specific column options.\n\n## feature() — the one-call form (default)\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 organizationId: q.scope('organization'),\n },\n // firewall block omitted — q.scope('organization') triggers auto-derivation\n // of [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'deletedAt', isNull: true }].\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n});\n```\n\nType inference still works — `typeof import('./jobs').default.$infer` gives you the row type. In action files, `import jobs from './jobs'` gives you the same typed handle you'd get from `q.table()`, so `defineActions(jobs, { … })` accepts it unchanged.\n\n## q.table() + defineTable() — the two-export form\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(),\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n organizationId: q.scope('organization'),\n});\n\nexport default defineTable(jobs, {\n guards: { /* ... */ },\n crud: { /* ... */ },\n read: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nProduces byte-identical output to the `feature()` form above — the compiler expands `feature()` to exactly this shape internally. Use whichever reads better for the file you're writing.\n\nA few mechanics to know:\n\n- **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.\n- **`q.id()`** emits `text('id').primaryKey()` with a cuid2 app-layer default.\n- **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.\n- **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`.\n- **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.int()` | `integer(...)` | `z.number().int()` |\n| `q.bool()` | `boolean(...)` | `z.boolean()` |\n| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |\n| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |\n| `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |\n| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |\n| `q.id()` | `text('id').primaryKey()` | `z.string()` |\n| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |\n\n`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting — prefixed UUIDs for D1, cuid for libsql/bun-sqlite, `crypto.randomUUID()` for supabase, etc. This keeps q's output decoupled from any specific ID library.\n\n### q.scope() — tenant scope columns\n\n`q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:\n\n1. **Auto-derive the firewall predicate** — `q.scope('organization')` produces `[{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` so you can omit the explicit `firewall:` block. (If `deletedAt` is present — and it is, by default, via audit-field injection — the soft-delete predicate is appended automatically.)\n2. **Reject the column from client input** — scope fields land in `GUARDS_CONFIG.systemManaged` alongside the audit fields, so `POST { organizationId: 'org_other' }` returns 400 even if guards aren't otherwise configured.\n3. **Auto-populate on create / upsert** — the value is taken from the request context, not the request body.\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\nOverride the context source for non-default sources:\n\n```typescript\nownerId: q.scope('owner', { source: 'ctx.userId' }),\n```\n\n`q.scope()` is preferred over `q.text().required()` for tenant columns. Auto-detection on column names (`organizationId`, `userId`, etc.) still works as a fallback for projects bringing forward Drizzle schemas, but the explicit `q.scope()` form locks in the semantics in the source.\n\n### Naming Convention\n\nBy default, `q` picks the SQL column name from the JS key using the target database's conventional casing:\n\n- **Postgres family (Supabase, Neon, D1)** → `snake_case` (`organizationId` → `organization_id`)\n- **SQLite family (bun-sqlite, better-sqlite3, libsql)** → `camelCase` (`organizationId` → `organizationId`)\n\nYou can override for any project by setting `namingConvention` on the database provider config:\n\n```ts\n// quickback/quickback.config.ts\nexport default {\n providers: {\n database: {\n name: 'bun-sqlite',\n config: {\n path: './data/app.db',\n namingConvention: 'snake_case', // force snake_case everywhere\n },\n },\n },\n};\n```\n\nFor one-off overrides on a specific column, pass an explicit name as the positional argument:\n\n```ts\norganizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'\n```\n\n## Defining Tables with Drizzle\n\nIf you prefer Drizzle — or have an existing schema you're bringing forward — use `pgTable` / `sqliteTable` / `mysqlTable` directly:\n\n| Target Database | Import From | Table Function |\n|-----------------|-------------|----------------|\n| Cloudflare D1, Turso, SQLite | `drizzle-orm/sqlite-core` | `sqliteTable` |\n| Supabase, Neon, PostgreSQL | `drizzle-orm/pg-core` | `pgTable` |\n| PlanetScale, MySQL | `drizzle-orm/mysql-core` | `mysqlTable` |\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n organizationId: text('organization_id').notNull(),\n title: text('title').notNull(),\n department: text('department').notNull(),\n status: text('status').notNull(),\n salaryMin: integer('salary_min'),\n salaryMax: integer('salary_max'),\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n crud: { /* ... */ },\n});\n\nexport type Job = typeof jobs.$inferSelect;\n```\n\nWhen using Drizzle (rather than `q.scope()`), declare the firewall as a predicate array. Auto-detection still works on column names (`organizationId`, `ownerId`, `teamId`) so you can omit `firewall:` entirely if exactly one isolation column is present.\n\n### Choosing Between `q` and Drizzle\n\n| Pick `q` when | Pick Drizzle when |\n|---|---|\n| Starting a new feature from scratch | You already have Drizzle schemas to bring forward |\n| You want the same Zod across actions, forms, and routes | You need Drizzle-specific column options not yet in `q` (e.g., `decimal`, `varchar` with length, dialect-specific types) |\n| You prefer concise, Zod-native syntax | You prefer the explicit Drizzle dialect import per target |\n\nFeatures in the same project may mix freely — Quickback dispatches per feature.\n\n### Drizzle Column Types\n\nDrizzle supports all standard SQL column types:\n\n| Type | Drizzle Function | Example |\n|------|------------------|---------|\n| String | `text()`, `varchar()` | `text('name')` |\n| Integer | `integer()`, `bigint()` | `integer('count')` |\n| Boolean | `boolean()` | `boolean('is_active')` |\n| Timestamp | `timestamp()` | `timestamp('created_at')` |\n| JSON | `json()`, `jsonb()` | `jsonb('metadata')` |\n| UUID | `uuid()` | `uuid('id')` |\n| Decimal | `decimal()`, `numeric()` | `decimal('price', { precision: 10, scale: 2 })` |\n\n### Drizzle Column Modifiers\n\n```typescript\n// Required field\nname: text('name').notNull()\n\n// Default value\nisActive: boolean('is_active').default(true)\n\n// Primary key\nid: text('id').primaryKey()\n\n// Unique constraint\nemail: text('email').unique()\n\n// Default to current timestamp\ncreatedAt: timestamp('created_at').defaultNow()\n```\n\n## File Organization\n\nOrganize your tables by feature. Each feature directory contains table files:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n ├── jobs/\n │ ├── jobs.ts # Main table + config\n │ ├── applications.ts # Related table + config\n │ └── actions.ts # Custom actions\n ├── candidates/\n │ ├── candidates.ts # Table + config\n │ └── candidate-notes.ts # Related table\n └── organizations/\n └── organizations.ts\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` get CRUD routes generated\n- Tables without a default export are internal (no routes, used for joins/relations)\n- Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`\n\n### defineTable vs defineResource\n\n- **`defineTable`** — The standard function for defining tables with CRUD routes\n- **`defineResource`** — Deprecated. Still works but emits a warning during compilation. Use `defineTable` instead.\n\n```typescript\n// Preferred:\nexport default defineTable(jobs, { /* config */ });\n```\n\n## 1 Resource = 1 Security Boundary\n\nEach `defineTable()` call defines a complete, self-contained security boundary. The security config you write — firewall, access, guards, and masking — is compiled into a single resource file that wraps all CRUD routes for that table.\n\nThis is a deliberate design choice. Mixing two resources with different security rules in one configuration would create ambiguity about which firewall, access, or masking rules apply to which table. By keeping it 1:1, there's never any question.\n\n| Scenario | What to do |\n|----------|------------|\n| Table needs its own API routes + security | Own file with `defineTable()` |\n| Table is internal/supporting (no direct API) | Extra `.ts` file in the parent feature directory, no `defineTable()` |\n\nA supporting table without `defineTable()` is useful when it's accessed internally — by action handlers, joins, or background jobs — but should never be directly exposed as its own API endpoint.\n\n## Internal Tables (No Routes)\n\nFor junction tables or internal data structures that shouldn't have API routes, simply omit the `defineTable` export:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// Internal scoring table - no routes needed\nexport const interviewScores = sqliteTable('interview_scores', {\n applicationId: text('application_id').notNull(),\n interviewerId: text('interviewer_id').notNull(),\n score: integer('score'),\n organizationId: text('organization_id').notNull(), // Scope junction tables for cascade soft-deletes\n});\n\n// No default export = no CRUD routes generated\n```\n\nThese internal tables still participate in the database schema and migrations — they just don't get API routes or security configuration.\n\nThe compiler automatically injects **audit fields** (`createdAt`, `modifiedAt`, `deletedAt`, etc.) and **`organizationId`** into child/junction tables when the parent feature is org-scoped. This ensures cascade soft deletes and scoped queries work correctly without manual column definitions.\n\n## Audit Fields\n\nQuickback automatically adds and manages these audit fields on **all tables** in a feature (including child/junction tables without `defineTable`) - you don't need to define them:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set when record is created |\n| `createdBy` | text | User ID who created the record |\n| `modifiedAt` | timestamp | Updated on every change |\n| `modifiedBy` | text | User ID who last modified |\n| `deletedAt` | timestamp | Set on soft delete |\n| `deletedBy` | text | User ID who soft-deleted the record |\n\nAll six fields are injected into every table, including `deletedAt` and `deletedBy`, regardless of whether the resource uses soft-delete mode. This keeps the schema uniform and lets you opt in to soft delete later without a migration. To opt out of audit injection entirely, set `compiler.features.auditFields: false` globally.\n\n### Disabling Audit Fields\n\nTo disable automatic audit fields for your project:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n compiler: {\n features: {\n auditFields: false, // Disable for entire project\n }\n }\n});\n```\n\n### Protected System Fields\n\nThese fields are always protected and cannot be set by clients, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\n## Ownership Fields\n\nFor the firewall to work, declare a tenant-scope column. With `q.scope()` (recommended), the compiler auto-derives the firewall predicate, marks the column as system-managed, and auto-populates it on create:\n\n```typescript\n// q DSL (recommended)\norganizationId: q.scope('organization') // → ctx.activeOrgId\nownerId: q.scope('owner') // → ctx.userId\nteamId: q.scope('team') // → ctx.activeTeamId\n```\n\nWhen using Drizzle directly, declare a regular column. Auto-detection picks it up by name; `q.scope()` semantics (systemManaged, auto-populate) still apply because they're keyed off the firewall predicate, not the column DSL:\n\n```typescript\n// Drizzle interop\norganizationId: text('organization_id').notNull()\nownerId: text('owner_id').notNull()\nteamId: text('team_id').notNull()\n```\n\n## Display Column\n\nWhen a table has foreign key columns (e.g., `departmentId` referencing `departments`), Quickback can automatically resolve the human-readable label in GET and LIST responses. This eliminates the need for frontend lookup calls.\n\n### Auto-Detection\n\nQuickback auto-detects the display column by checking for common column names in this order:\n\n`name` → `title` → `label` → `headline` → `subject` → `code` → `displayName` → `fullName` → `description`\n\nIf your `departments` table has a `name` column, it's automatically used as the display column. No config needed.\n\n### Explicit Override\n\nOverride the auto-detected column with `displayColumn`:\n\n```typescript\nexport default defineTable(interviewStages, {\n displayColumn: 'label', // Use 'label' instead of auto-detected 'name'\n read: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n});\n```\n\n### Default Sort\n\nSet a default sort order for the CMS table list view with `defaultSort`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n firewall: [{ exception: true }],\n read: { access: { roles: [\"PUBLIC\"] } },\n});\n```\n\nThe CMS applies this sort when the table first loads. Users can still click column headers to change the sort order.\n\n### How Labels Appear in Responses\n\nFor any FK column ending in `Id`, the API adds a `_label` field with the resolved display value:\n\n```json\n{\n \"id\": \"job_abc\",\n \"title\": \"Senior Engineer\",\n \"departmentId\": \"dept_xyz\",\n \"department_label\": \"Engineering\",\n \"locationId\": \"loc_123\",\n \"location_label\": \"San Francisco\"\n}\n```\n\nThe pattern is `{columnWithoutId}_label`. The frontend can find all labels with:\n\n```typescript\nObject.keys(record).filter(k => k.endsWith('_label'))\n```\n\nLabel resolution works within the same feature (tables in the same feature directory). System columns (`organizationId`, `createdBy`, `modifiedBy`) are never resolved.\n\nFor LIST endpoints, labels are batch-resolved efficiently — one query per FK column, not per record.\n\n## References\n\nWhen your FK columns don't match the target table name by convention (e.g., `vendorId` actually points to the `contact` table), declare explicit references so the CMS and schema registry know the correct target:\n\n```typescript\nexport default defineTable(applications, {\n references: {\n candidateId: \"candidate\",\n jobId: \"job\",\n referredById: \"candidate\",\n },\n // ... firewall, guards, crud\n});\n```\n\nEach key is a column name ending in `Id`, and the value is the camelCase table name it references. These mappings flow into the schema registry as `fkTarget` on each column, enabling the CMS to render typeahead/lookup inputs that search the correct table.\n\nConvention-based matching (strip `Id` suffix, look for a matching table) still works for simple cases like `projectId` → `project`. Use `references` only for columns where the convention doesn't match.\n\n## Input Hints\n\nControl how the CMS renders form inputs for specific columns. By default the CMS infers input types from the column's SQL type — `inputHints` lets you override that:\n\n```typescript\nexport default defineTable(jobs, {\n inputHints: {\n status: \"select\",\n department: \"select\",\n salaryMin: \"currency\",\n salaryMax: \"currency\",\n description: \"richtext\",\n },\n // ... firewall, guards, crud\n});\n```\n\n### Available Hint Values\n\n| Hint | Renders As |\n|------|-----------|\n| `richtext` | Rich text editor (tiptap) — bold, italic, headings, lists, links. Stores HTML. Lazy-loaded in edit mode, rendered as formatted HTML in view mode. |\n| `select` | Dropdown select (single value) |\n| `multi-select` | Multi-value select |\n| `radio` | Radio button group |\n| `checkbox` | Checkbox toggle |\n| `textarea` | Multi-line text input |\n| `lookup` | FK typeahead search |\n| `hidden` | Hidden from forms |\n| `color` | Color picker |\n| `date` | Date picker |\n| `datetime` | Date + time picker |\n| `time` | Time picker |\n| `currency` | Currency input with formatting |\n\nInput hints are emitted in the schema registry as `inputHints` on the table metadata, and the CMS reads them to render the appropriate form controls.\n\n### Rich Text Example\n\nFor fields that contain HTML content (e.g., blog posts, descriptions from RSS feeds), use `\"richtext\"`:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n inputHints: { description: \"richtext\" },\n // ...\n});\n```\n\nThe CMS will:\n- **View mode**: Render the HTML with proper formatting (headings, lists, links, etc.)\n- **Edit mode**: Load a tiptap rich text editor with a toolbar (bold, italic, H2, H3, bullet/ordered lists, links, code, undo/redo)\n- **Storage**: HTML strings — no format conversion needed, compatible with external HTML content\n\n## Relations (Optional)\n\nDrizzle supports defining relations for type-safe joins:\n\n```typescript\n\nexport const jobsRelations = relations(jobs, ({ one, many }) => ({\n organization: one(organizations, {\n fields: [jobs.organizationId],\n references: [organizations.id],\n }),\n applications: many(applications),\n}));\n```\n\n## Database Configuration\n\nConfigure database options in your Quickback config:\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: 'my-app',\n providers: {\n database: defineDatabase('cloudflare-d1', {\n generateId: 'prefixed', // 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial' | false\n namingConvention: 'snake_case', // 'camelCase' | 'snake_case'\n usePlurals: false, // Auth table names: 'users' vs 'user'\n }),\n },\n compiler: {\n features: {\n auditFields: true, // Auto-manage audit timestamps\n }\n }\n});\n```\n\n## Choosing Your Dialect\n\nUse the Drizzle dialect that matches your database provider:\n\n### SQLite (D1, Turso, better-sqlite3)\n\n```typescript\n\nexport const jobs = sqliteTable('jobs', {\n id: text('id').primaryKey(),\n title: text('title').notNull(),\n metadata: text('metadata', { mode: 'json' }), // JSON stored as text\n isOpen: integer('is_open', { mode: 'boolean' }).default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### PostgreSQL (Supabase, Neon)\n\n```typescript\n\nexport const jobs = pgTable('jobs', {\n id: serial('id').primaryKey(),\n title: text('title').notNull(),\n metadata: jsonb('metadata'), // Native JSONB\n isOpen: boolean('is_open').default(false),\n organizationId: text('organization_id').notNull(),\n});\n```\n\n### Key Differences\n\n| Feature | SQLite | PostgreSQL |\n|---------|--------|------------|\n| Boolean | `integer({ mode: 'boolean' })` | `boolean()` |\n| JSON | `text({ mode: 'json' })` | `jsonb()` or `json()` |\n| Auto-increment | `integer().primaryKey()` | `serial()` |\n| UUID | `text()` | `uuid()` |\n\n## Next Steps\n\n- [Configure the firewall](/compiler/definitions/firewall) for data isolation\n- [Set up access control](/compiler/definitions/access) for CRUD operations\n- [Define guards](/compiler/definitions/guards) for field modification rules\n- [Add custom actions](/compiler/definitions/actions) for business logic"
|
|
211
215
|
},
|
|
212
216
|
"compiler/definitions/validation": {
|
|
213
217
|
"title": "Validation",
|
|
@@ -215,7 +219,7 @@ export const DOCS = {
|
|
|
215
219
|
},
|
|
216
220
|
"compiler/definitions/views": {
|
|
217
221
|
"title": "Views - Column Level Security",
|
|
218
|
-
"content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n
|
|
222
|
+
"content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n> **Migration note**: views were previously declared at the resource top\n> level (`views: {...}`). In DSL v2 they live under\n> [`read.views`](/compiler/definitions/read#views-under-read-views) so the\n> read pipeline owns its own configuration. The top-level form is rejected\n> at compile time.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n\n // Named field projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'source', 'resumeUrl', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n report: {\n fields: ['id', 'name', 'source', 'createdAt'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n});\n```\n\n## Generated Endpoints\n\nEach view generates **two** equivalent GET endpoints — pick whichever is more ergonomic for your client:\n\n```\nGET /api/v1/candidates # Full read - read.access fields\nGET /api/v1/candidates?view=pipeline # Query-string dispatch\nGET /api/v1/candidates/views/pipeline # Explicit path form\nGET /api/v1/candidates?view=full # hiring-manager/recruiter only\nGET /api/v1/candidates/views/report # report fields\n```\n\nThe `?view=` query-string form is convenient when the rest of your client\nalready builds collection URLs and you only need to swap the projection.\nThe `/views/{name}` path form is better when you want a stable URL per\nprojection.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n### Pagination\n\n| Parameter | Description | Default | Max |\n|-----------|-------------|---------|-----|\n| `limit` | Number of records to return | 50 | 100 |\n| `offset` | Number of records to skip | 0 | - |\n\n```bash\n# Get first 10 records\nGET /api/v1/candidates/views/pipeline?limit=10\n\n# Get records 11-20\nGET /api/v1/candidates/views/pipeline?limit=10&offset=10\n```\n\n### Filtering\n\n```bash\n# Filter by exact value\nGET /api/v1/candidates/views/pipeline?source=linkedin\n\n# Filter with operators\nGET /api/v1/candidates/views/pipeline?createdAt.gt=2024-01-01\n\n# Multiple filters (AND logic)\nGET /api/v1/candidates/views/pipeline?source=linkedin&name.like=Smith\n```\n\n### Sorting\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n\n```bash\nGET /api/v1/candidates/views/pipeline?sort=name&order=asc\n```\n\n## Security\n\nAll four security pillars apply to views:\n\n| Pillar | Behavior |\n|--------|----------|\n| **Firewall** | WHERE clause applied (same as list) |\n| **Access** | Per-view access control |\n| **Guards** | N/A (read-only) |\n| **Masking** | Applied to returned fields |\n\n### Firewall\n\nViews automatically apply the same firewall conditions as the list endpoint. Users only see records within their organization scope.\n\n### Access Control\n\nEach view has its own access configuration:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Pipeline view - available to all roles\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Full view - recruiter and above\n full: {\n fields: ['id', 'name', 'source', 'email', 'phone', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\n### Masking\n\nMasking rules are applied to the returned fields. If a view includes a masked field like `email`, the masking rules still apply:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Even if an interviewer accesses the 'full' view, email will be masked\n // because masking rules take precedence\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n### How Views and Masking Work Together\n\nViews and masking are orthogonal concerns:\n- **Views** control field selection (which columns appear)\n- **Masking** controls field transformation (how values appear based on role)\n\nExample configuration:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name'], // email NOT included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email'], // email included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n| Endpoint | Role | `email` in response? | `email` value |\n|----------|------|---------------------|---------------|\n| `/views/pipeline` | interviewer | No | N/A |\n| `/views/pipeline` | recruiter | No | N/A |\n| `/views/full` | interviewer | Yes | `j***@c******.com` |\n| `/views/full` | recruiter | Yes | `jane@company.com` |\n\n## Response Format\n\nView responses include metadata about the view:\n\n```json\n{\n \"data\": [\n { \"id\": \"cnd_123\", \"name\": \"Jane Doe\", \"source\": \"linkedin\" },\n { \"id\": \"cnd_456\", \"name\": \"John Smith\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"fields\": [\"id\", \"name\", \"source\"],\n \"pagination\": {\n \"limit\": 50,\n \"offset\": 0,\n \"count\": 2\n }\n}\n```\n\n## Complete Example\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n guards: {\n createable: ['title', 'department', 'status', 'salaryMin', 'salaryMax'],\n updatable: ['title', 'department', 'status'],\n },\n\n masking: {\n salaryMin: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n salaryMax: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Public job board view\n board: {\n fields: ['id', 'title', 'department', 'status'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Internal view with salary info\n internal: {\n fields: ['id', 'title', 'department', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n // Compensation report\n compensation: {\n fields: ['id', 'title', 'department', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n\n crud: {\n create: { access: { roles: ['owner', 'hiring-manager'] } },\n update: { access: { roles: ['owner', 'hiring-manager'] } },\n delete: { access: { roles: ['owner', 'hiring-manager'] } },\n },\n});\n```"
|
|
219
223
|
},
|
|
220
224
|
"compiler/getting-started/claude-code": {
|
|
221
225
|
"title": "AI Tools",
|
|
@@ -223,23 +227,23 @@ export const DOCS = {
|
|
|
223
227
|
},
|
|
224
228
|
"compiler/getting-started/full-example": {
|
|
225
229
|
"title": "Complete Example",
|
|
226
|
-
"content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based CRUD permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/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 source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.text().required(),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // FIREWALL — Data isolation\n firewall: { organization: {} },\n\n // CRUD — Role-based permissions\n crud: {\n list: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n get: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n },\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // VIEWS — Column-level projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n});\n```\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Pattern: Organization only\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n const conditions = [];\n\n // Organization isolation\n conditions.push(eq(candidates.organizationId, ctx.activeOrgId!));\n\n return and(...conditions);\n}\n\n/**\n * Guards configuration for field modification rules\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy'\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// CRUD Access configuration\nexport const CRUD_ACCESS = {\n list: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n get: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n};\n\n// Views configuration\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n};\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n CRUD_ACCESS\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates - List with firewall + masking\napp.get('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.list.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.list.access.roles,\n ctx.roles\n ), 403);\n }\n\n // Query with firewall conditions\n const results = await db.select().from(candidates)\n .where(buildFirewallConditions(ctx));\n\n // Apply masking before returning\n return c.json({\n data: maskCandidates(results, ctx),\n });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates/views/pipeline` | interviewer | No | N/A |\n| `/candidates/views/pipeline` | recruiter | No | N/A |\n| `/candidates/views/full` | interviewer | No | N/A (no access) |\n| `/candidates/views/full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/views/full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
|
|
230
|
+
"content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based CRUD permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/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 source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.scope(\"organization\"),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // firewall — auto-derived from q.scope(\"organization\") + audit deletedAt;\n // explicit declaration is optional once a scope column is declared.\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction (query.roles defaults to show.roles)\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // READ — Collection + per-id GET, plus named views\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n },\n\n // CRUD — Write operations\n crud: {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n },\n});\n```\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Auto-derived from q.scope(\"organization\") + audit-injected deletedAt.\n * 2 predicates: tenant scope AND soft-delete filter.\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n return and(\n eq(candidates.organizationId, ctx.activeOrgId!),\n isNull(candidates.deletedAt),\n );\n}\n\n/**\n * Guards configuration for field modification rules.\n * organizationId is added to systemManaged because q.scope(\"organization\")\n * is bound to ctx.activeOrgId — clients cannot submit it.\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy',\n 'organizationId', // ← added by q.scope(\"organization\")\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// CRUD Access configuration (write operations only)\nexport const CRUD_ACCESS = {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n};\n\n// Views configuration (read pipeline)\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n} as const;\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n VIEWS_CONFIG,\n CRUD_ACCESS,\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates?view=<name> — unified read handler dispatched by ?view\nconst READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };\n\napp.get('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n const params = Object.fromEntries(new URL(c.req.url).searchParams);\n const view = VIEWS_CONFIG[params.view as keyof typeof VIEWS_CONFIG];\n if (!view) return c.json({ error: 'View required', code: 'VIEW_REQUIRED' }, 400);\n\n // Per-view access gate (falls back to read-level access)\n if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {\n return c.json(AccessErrors.roleRequired(view.access?.roles ?? READ_ACCESS.roles, ctx.roles), 403);\n }\n\n // Query with firewall conditions, project view fields, mask, return.\n const results = await db.select(/* projected fields */).from(candidates)\n .where(buildFirewallConditions(ctx));\n\n return c.json({ data: maskCandidates(results, ctx), view: params.view });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates?view=pipeline` | interviewer | No | N/A |\n| `/candidates?view=pipeline` | recruiter | No | N/A |\n| `/candidates?view=full` | interviewer | No | N/A (no access) |\n| `/candidates?view=full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates?view=pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates?view=full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
|
|
227
231
|
},
|
|
228
232
|
"compiler/getting-started/hand-crafted": {
|
|
229
233
|
"title": "Hand-Crafted Setup",
|
|
230
|
-
"content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/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\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: {
|
|
234
|
+
"content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/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\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n },\n});\n```\n\n### 4. Log In and Compile\n\n```bash\nquickback login\nquickback compile\n```\n\nThe compiler generates a complete `src/` directory with route handlers, middleware, database schemas, and migrations.\n\n### 5. Integrate with Your Existing Code\n\nThe compiled output creates a self-contained Hono app in `src/index.ts`. If you need to integrate the generated routes into an existing Hono app, you can import the feature routes directly:\n\n```typescript\n\nconst app = new Hono();\n\n// Your existing routes\napp.get(\"/\", (c) => c.json({ status: \"ok\" }));\n\n// Mount generated feature routes\napp.route(\"/api/v1/candidates\", candidatesRoutes);\n\nexport default app;\n```\n\n## Directory Structure\n\nThe compiler expects this structure inside `quickback/`:\n\n```\nquickback/\n├── quickback.config.ts # Required: compiler configuration\n└── features/ # Required: feature definitions\n ├── candidates/\n │ ├── candidates.ts # Schema + security (defineTable)\n │ └── actions.ts # Optional: custom actions\n ├── jobs/\n │ ├── jobs.ts\n │ └── actions.ts\n └── ...\n```\n\nEach feature directory should contain:\n- **`{name}.ts`** — The main definition file using `defineTable()` (required)\n- **`actions.ts`** — Custom actions using `defineActions()` (optional)\n\n## Adding Features\n\nTo add a new feature, create a new directory under `quickback/features/` and recompile:\n\n```bash\nmkdir quickback/features/jobs\n# Create jobs/jobs.ts with defineTable(...)\nquickback compile\n```\n\nThe compiler detects all features automatically — no registration needed.\n\n## Recompiling\n\nAfter any change to your definitions, recompile to regenerate the output:\n\n```bash\nquickback compile\n```\n\nThe compiler regenerates the entire `src/` directory. Your definitions in `quickback/` are the source of truth — never edit the generated files directly.\n\n**Warning:** Don't edit files in `src/` manually. They will be overwritten on the next compile. All changes should be made in your `quickback/` definitions.\n\n## Next Steps\n\n- [Configuration reference](/compiler/config) — All config options\n- [Schema definitions](/compiler/definitions/schema) — Define tables with `defineTable()`\n- [Security pillars](/compiler/definitions) — Firewall, Access, Guards, Masking\n- [Templates](/compiler/getting-started/templates) — Use a template for new projects instead"
|
|
231
235
|
},
|
|
232
236
|
"compiler/getting-started": {
|
|
233
237
|
"title": "Getting Started",
|
|
234
|
-
"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.
|
|
238
|
+
"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](/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/using-the-api) — CRUD endpoints, filtering, and batch operations"
|
|
235
239
|
},
|
|
236
240
|
"compiler/getting-started/patterns": {
|
|
237
241
|
"title": "Common Patterns",
|
|
238
|
-
"content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Public Read, Authenticated Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: {
|
|
242
|
+
"content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Public Read, Authenticated Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n submitScore: {\n type: \"record\",\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: [\"stage\"], // Stage can only be changed via actions\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n type: \"record\",\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via PUT/upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
|
|
239
243
|
},
|
|
240
244
|
"compiler/getting-started/template-blog": {
|
|
241
245
|
"title": "Blog Template",
|
|
242
|
-
"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:
|
|
246
|
+
"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"
|
|
243
247
|
},
|
|
244
248
|
"compiler/getting-started/template-bun": {
|
|
245
249
|
"title": "Bun Template",
|
|
@@ -247,11 +251,11 @@ export const DOCS = {
|
|
|
247
251
|
},
|
|
248
252
|
"compiler/getting-started/template-cloudflare": {
|
|
249
253
|
"title": "Cloudflare Template",
|
|
250
|
-
"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:
|
|
254
|
+
"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"
|
|
251
255
|
},
|
|
252
256
|
"compiler/getting-started/template-empty": {
|
|
253
257
|
"title": "Empty Scaffolding Templates",
|
|
254
|
-
"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:
|
|
258
|
+
"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"
|
|
255
259
|
},
|
|
256
260
|
"compiler/getting-started/templates": {
|
|
257
261
|
"title": "Templates",
|
|
@@ -271,15 +275,15 @@ export const DOCS = {
|
|
|
271
275
|
},
|
|
272
276
|
"compiler/integrations/neon": {
|
|
273
277
|
"title": "Neon",
|
|
274
|
-
"content": "Quickback supports Neon as a PostgreSQL database provider, generating schemas with Row Level Security (RLS) policies that enforce your firewall configuration at the database level.\n\n## Why Neon?\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-Level Security** — RLS policies enforce access even if API is bypassed\n- **Serverless Architecture** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS with `auth.user_id()` function\n- **Better Auth Integration** — Works seamlessly with Better Auth\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: 'auto', // auto-detects based on runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n### Environment Variables\n\n```bash\nDATABASE_URL=postgresql://user:pwd@ep-xxx.neon.tech/db?sslmode=require\n```\n\n## Row Level Security\n\nQuickback generates RLS policies from your firewall config:\n\n```typescript\nfirewall:
|
|
278
|
+
"content": "Quickback supports Neon as a PostgreSQL database provider, generating schemas with Row Level Security (RLS) policies that enforce your firewall configuration at the database level.\n\n## Why Neon?\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-Level Security** — RLS policies enforce access even if API is bypassed\n- **Serverless Architecture** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS with `auth.user_id()` function\n- **Better Auth Integration** — Works seamlessly with Better Auth\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: 'auto', // auto-detects based on runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n### Environment Variables\n\n```bash\nDATABASE_URL=postgresql://user:pwd@ep-xxx.neon.tech/db?sslmode=require\n```\n\n## Row Level Security\n\nQuickback generates RLS policies from your firewall config:\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\n-- Generated policy (uses auth.user_id() for Neon)\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())\n);\n```\n\n### Firewall Patterns\n\n**Organization-Scoped:**\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-Scoped:**\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public Tables:**\n```sql\nCREATE POLICY \"categories_deny_anon\" ON categories FOR ALL TO anon USING (false);\nCREATE POLICY \"categories_all\" ON categories FOR ALL TO authenticated USING (true) WITH CHECK (true);\n```\n\n## Generated Helper Functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if user has any specified role |\n| `has_org_role(role)` | Checks for a specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\n## Generated Files\n\n```\nquickback/drizzle/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql\n│ ├── 0101_create_rls_policies.sql\n│ └── 0102_create_indexes.sql\nsrc/\n├── db/\n│ └── schema.ts\n├── auth/\n│ └── schema.ts\n└── lib/\n └── neon.ts\n```\n\n## Setting Up Neon Authorize\n\n1. Go to **Project Settings > Authorize** in Neon console\n2. Add your JWKS URL: `https://your-api.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from JWT\n\n## Getting Started\n\n1. Create a Neon project at [neon.tech](https://neon.tech)\n2. Configure your Quickback project for Neon\n3. Run `quickback compile`\n4. Apply migrations with `drizzle-kit migrate`"
|
|
275
279
|
},
|
|
276
280
|
"compiler/integrations/supabase": {
|
|
277
281
|
"title": "Supabase",
|
|
278
|
-
"content": "Quickback supports Supabase as a deployment target, generating PostgreSQL schemas with Row Level Security (RLS) policies that enforce your firewall configuration at the database level.\n\n## Why Supabase?\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-Level Security** — RLS policies enforce access even if API is bypassed\n- **Integrated Auth** — Supabase Auth with JWT claims for RLS\n- **Real-time** — Postgres Changes for live updates\n- **Managed Infrastructure** — Automatic backups, scaling, monitoring\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"supabase\"),\n database: defineDatabase(\"supabase\"),\n auth: defineAuth(\"supabase-auth\"),\n },\n});\n```\n\n## Key Difference from Neon\n\n| Feature | Supabase | Neon |\n|---------|----------|------|\n| Auth function | `auth.uid()` | `auth.user_id()` |\n| Auth provider | Supabase Auth | Neon Authorize + Better Auth |\n| Users table | `auth.users` | `public.users` (Better Auth) |\n\n## Row Level Security\n\nQuickback generates RLS policies from your firewall config:\n\n```typescript\nfirewall:
|
|
282
|
+
"content": "Quickback supports Supabase as a deployment target, generating PostgreSQL schemas with Row Level Security (RLS) policies that enforce your firewall configuration at the database level.\n\n## Why Supabase?\n\n- **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search\n- **Database-Level Security** — RLS policies enforce access even if API is bypassed\n- **Integrated Auth** — Supabase Auth with JWT claims for RLS\n- **Real-time** — Postgres Changes for live updates\n- **Managed Infrastructure** — Automatic backups, scaling, monitoring\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"supabase\"),\n database: defineDatabase(\"supabase\"),\n auth: defineAuth(\"supabase-auth\"),\n },\n});\n```\n\n## Key Difference from Neon\n\n| Feature | Supabase | Neon |\n|---------|----------|------|\n| Auth function | `auth.uid()` | `auth.user_id()` |\n| Auth provider | Supabase Auth | Neon Authorize + Better Auth |\n| Users table | `auth.users` | `public.users` (Better Auth) |\n\n## Row Level Security\n\nQuickback generates RLS policies from your firewall config:\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\n-- Generated policy\nCREATE POLICY \"documents_select\" ON documents FOR SELECT\nUSING (\n organization_id = get_active_org_id()\n AND (has_any_role(ARRAY['admin']) OR user_id = auth.uid())\n);\n```\n\n### Firewall Patterns\n\n**Organization-Scoped:**\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-Scoped:**\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.uid());\n```\n\n## Defense in Depth\n\nAll generated policies include a deny policy for anonymous users:\n\n```sql\nCREATE POLICY \"tablename_deny_anon\" ON tablename FOR ALL\nTO anon\nUSING (false);\n```\n\n## Generated Helper Functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if user has any specified role |\n| `has_org_role(role)` | Checks for a specific role |\n| `is_org_member()` | Checks org membership |\n| `get_user_role()` | Returns user's role in active org |\n\n## Generated Files\n\n```\nsupabase/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql\n│ ├── 0101_create_rls_policies.sql\n│ └── 0102_create_audit_triggers.sql\nsrc/\n├── db/\n│ └── schema.ts\n└── lib/\n └── supabase.ts\n```\n\n## Getting Started\n\n1. Install the Supabase CLI\n2. Configure your Quickback project for Supabase\n3. Run `quickback compile`\n4. Push migrations with `supabase db push`"
|
|
279
283
|
},
|
|
280
284
|
"compiler/troubleshooting": {
|
|
281
285
|
"title": "Troubleshooting",
|
|
282
|
-
"content": "Common issues and their solutions. For cloud compiler specific issues, see [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting).\n\n## Compilation Issues\n\n### \"Feature must use defineTable()\"\n\nYour table file is missing the default export:\n\n```typescript\n// Wrong — no default export\nexport const applications = sqliteTable(\"applications\", { ... });\n\n// Correct — add defineTable default export\nexport const applications = sqliteTable(\"applications\", { ... });\nexport default defineTable(applications, { ... });\n```\n\n### \"File exports multiple tables with defineTable\"\n\nA single file can export multiple Drizzle tables, but only ONE can have a `defineTable()` default export. Split tables into separate files:\n\n```\nquickback/features/applications/\n├── applications.ts # defineTable(applications, { ... })\n└── candidates.ts # defineTable(candidates, { ... })\n```\n\n### Missing fields in generated API\n\nIf a field exists in your schema but doesn't appear in API responses:\n\n1. **Guards:** Check that the field is in `createable` (for POST) or `updatable` (for PATCH). Fields not listed are silently stripped.\n2. **Views:** If using views, the field must be in the view's `fields` array.\n3. **Masking:** The field may be present but masked (showing `[REDACTED]` or `***`). Check your masking config.\n\n### \"organizationId\" not auto-
|
|
286
|
+
"content": "Common issues and their solutions. For cloud compiler specific issues, see [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting).\n\n## Compilation Issues\n\n### \"Feature must use defineTable()\"\n\nYour table file is missing the default export:\n\n```typescript\n// Wrong — no default export\nexport const applications = sqliteTable(\"applications\", { ... });\n\n// Correct — add defineTable default export\nexport const applications = sqliteTable(\"applications\", { ... });\nexport default defineTable(applications, { ... });\n```\n\n### \"File exports multiple tables with defineTable\"\n\nA single file can export multiple Drizzle tables, but only ONE can have a `defineTable()` default export. Split tables into separate files:\n\n```\nquickback/features/applications/\n├── applications.ts # defineTable(applications, { ... })\n└── candidates.ts # defineTable(candidates, { ... })\n```\n\n### Missing fields in generated API\n\nIf a field exists in your schema but doesn't appear in API responses:\n\n1. **Guards:** Check that the field is in `createable` (for POST) or `updatable` (for PATCH). Fields not listed are silently stripped.\n2. **Views:** If using views, the field must be in the view's `fields` array.\n3. **Masking:** The field may be present but masked (showing `[REDACTED]` or `***`). Check your masking config.\n\n### \"organizationId\" not auto-detected\n\nThe firewall auto-detects `organizationId` and `ownerId` columns by name. If your column uses a different name, declare the firewall explicitly:\n\n```typescript\nfirewall: [\n { field: 'orgId', equals: 'ctx.activeOrgId' },\n]\n```\n\nOr use `q.scope()` and override the SQL name:\n\n```typescript\ncolumns: {\n orgId: q.scope('organization', { sqlName: 'org_id' }),\n}\n```\n\n## Migration Issues\n\n### Columns persist after removal from schema\n\nQuickback (via Drizzle) does **not** generate DROP COLUMN migrations. If you remove a column from your schema, the database column will remain as an orphaned column. SQLite handles this gracefully — the column won't appear in API responses since Drizzle only selects defined columns.\n\nTo clean up, you'd need to manually create a migration.\n\n### Drizzle rename prompts in CI\n\nIf compilation fails with `drizzle-kit requested interactive rename input`, add explicit rename hints in your config. See [Drizzle rename prompts](/compiler/cloud-compiler/troubleshooting#drizzle-rename-prompts-in-ciheadless-compile).\n\n## Runtime Issues\n\n### 401 on all requests\n\n1. **Missing auth:** Ensure your request includes `Authorization: Bearer <token>` or the session cookie\n2. **Expired session:** Sessions last 7 days by default. Re-authenticate.\n3. **Wrong auth URL:** Check that `BETTER_AUTH_URL` matches your deployment URL\n\n### 403 Forbidden\n\n1. **Wrong role:** Check the `access` config for the endpoint — your role may not be listed\n2. **Wrong org:** You may be in a different organization than the record's `organizationId`\n3. **Firewall hiding:** If `errorMode: 'hide'` is set, firewall violations return 404 instead of 403\n\n### 400 Bad Request on create/update\n\n1. **Guard violation:** You're sending a field not in `createable` or `updatable`. Check the error's `details.fields`.\n2. **Missing required field:** A `.notNull()` column without a default is missing from your request body.\n3. **Immutable field:** You're trying to update a field marked as `immutable`.\n\n### Records missing from list\n\nRecords may be filtered by:\n1. **Firewall:** Only records matching your organization (and optionally owner) are returned\n2. **Soft delete:** Soft-deleted records are automatically excluded\n3. **Access conditions:** Record-level conditions may filter results\n\n## See Also\n\n- [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting) — CLI and authentication issues\n- [Errors](/compiler/using-the-api/errors) — Complete error code reference\n- [Firewall](/compiler/definitions/firewall) — Data isolation configuration\n- [Guards](/compiler/definitions/guards) — Field modification rules"
|
|
283
287
|
},
|
|
284
288
|
"compiler/using-the-api/actions-api": {
|
|
285
289
|
"title": "Actions API",
|
|
@@ -287,7 +291,7 @@ export const DOCS = {
|
|
|
287
291
|
},
|
|
288
292
|
"compiler/using-the-api/batch-operations": {
|
|
289
293
|
"title": "Batch Operations",
|
|
290
|
-
"content": "Batch operations let you create, update, or delete multiple records in a single request. They are **auto-enabled** when the corresponding CRUD operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `crud.create` exists |\n| `/{resource}/batch` | `PATCH` | `crud.update` exists |\n| `/{resource}/batch` | `DELETE` | `crud.delete` exists |\n| `/{resource}/batch` | `PUT` | `crud.put` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncrud: {\n create: { access: { roles: ['hiring-manager'] } },\n batchCreate: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"atomic\": false\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"atomic\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"atomic\": false\n }\n}\n```\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`.\n\n## Atomic Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"atomic\": true` to require all-or-nothing processing:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"atomic\": true\n }\n}\n```\n\n### Atomic Failure Response (400)\n\nIf any record fails in atomic mode, the entire batch is rejected:\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding CRUD operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n crud: {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },\n\n // Override batch-specific settings\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowAtomic: true, // Default: true\n },\n batchUpdate: {\n maxBatchSize: 100,\n allowAtomic: true,\n },\n batchDelete: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowAtomic: true,\n },\n\n // Disable a batch operation entirely\n batchUpsert: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
|
|
294
|
+
"content": "Batch operations let you create, update, or delete multiple records in a single request. They are **auto-enabled** when the corresponding CRUD operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `crud.create` exists |\n| `/{resource}/batch` | `PATCH` | `crud.update` exists |\n| `/{resource}/batch` | `DELETE` | `crud.delete` exists |\n| `/{resource}/batch` | `PUT` | `crud.put` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncrud: {\n create: { access: { roles: ['hiring-manager'] } },\n batchCreate: false, // Disable batch create\n}\n```\n\n## Batch Create\n\n```\nPOST /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"records\": [\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Strong frontend background\" },\n { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"notes\": \"Referred by employee\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" },\n { \"id\": \"app_abc3\", \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"applied\", \"createdAt\": \"2025-01-15T10:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_101\", \"jobId\": \"job_202\", \"stage\": \"applied\", \"notes\": \"Also interested in backend role\" },\n \"error\": {\n \"error\": \"Database insert failed\",\n \"layer\": \"validation\",\n \"code\": \"INSERT_FAILED\",\n \"details\": { \"reason\": \"UNIQUE constraint failed: applications.candidateId, applications.jobId\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n- **201** — All records created successfully\n- **207** — Partial success (some errors, some successes)\n\n`POST /batch` uses a single bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag.\n\nFields applied automatically to each record:\n- ID generation (UUID, prefixed, etc.)\n- Ownership fields (`organizationId`, `ownerId`, `createdBy`)\n- Audit fields (`createdAt`, `modifiedAt`)\n- Default values and computed fields\n\n## Batch Update\n\n```\nPATCH /api/v1/{resource}/batch\n```\n\nEvery record **must include an `id` field**.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\" },\n { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (200 or 207)\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"notes\": \"Passed phone screen, schedule onsite\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" },\n { \"id\": \"app_abc2\", \"notes\": \"Moved to technical interview round\", \"modifiedAt\": \"2025-01-15T11:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"app_xyz9\", \"notes\": \"Hiring manager approved offer\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"app_xyz9\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\nRecords that don't exist or aren't accessible through the firewall return a `NOT_FOUND` error. Guard rules (immutable, protected, not-updatable fields) are checked per record.\n\n### Missing IDs\n\nIf any records are missing the `id` field, the entire request is rejected:\n\n```json\n{\n \"error\": \"Records missing required ID field\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_MISSING_IDS\",\n \"details\": { \"indices\": [0, 2] },\n \"hint\": \"All records must include an ID field for batch update.\"\n}\n```\n\n## Batch Delete\n\n```\nDELETE /api/v1/{resource}/batch\n```\n\n### Request\n\n```json\n{\n \"ids\": [\"app_abc1\", \"app_abc2\", \"app_abc3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nNote: Batch delete uses an `ids` array (not `records`).\n\n### Response (200 or 207)\n\n**Soft delete** (default):\n\n```json\n{\n \"success\": [\n { \"id\": \"app_abc1\", \"candidateId\": \"cand_101\", \"deletedAt\": \"2025-01-15T12:00:00Z\" },\n { \"id\": \"app_abc2\", \"candidateId\": \"cand_103\", \"deletedAt\": \"2025-01-15T12:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"failFast\": false,\n \"transactional\": true\n }\n}\n```\n\n`DELETE /batch` issues a single bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`.\n\n**Hard delete**: Returns objects with only the `id` field (record data is deleted).\n\n## Batch Upsert\n\n```\nPUT /api/v1/{resource}/batch\n```\n\nInserts new records or updates existing ones. Every record must include an `id` field.\n\n**Note:** Batch upsert is only available when `generateId` is set to `false` (user-provided IDs) in your configuration.\n\n### Request\n\n```json\n{\n \"records\": [\n { \"id\": \"app_001\", \"candidateId\": \"cand_101\", \"jobId\": \"job_201\", \"stage\": \"screening\", \"notes\": \"Updated after phone screen\" },\n { \"id\": \"app_002\", \"candidateId\": \"cand_104\", \"jobId\": \"job_203\", \"stage\": \"applied\", \"notes\": \"New application from referral\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\n### Response (201 or 207)\n\nThe compiler checks which IDs already exist and splits the batch into creates and updates. Create records get ownership and default fields; update records get only `modifiedAt`. Under `failFast: true`, both the bulk insert and the per-record updates run inside the same transaction — a failed update rolls back the inserts too on tx-supporting providers.\n\n## Fail-Fast Mode\n\nBy default, batch operations use **partial success** mode — each record is processed independently, and failures don't affect other records.\n\nSet `\"failFast\": true` to stop on the first error:\n\n```json\n{\n \"records\": [...],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\n### Fail-Fast Failure Response (400)\n\n```json\n{\n \"error\": \"Batch failed at index 1\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 1,\n \"reason\": \"Database insert failed\",\n \"errorDetails\": { \"reason\": \"UNIQUE constraint failed\" }\n }\n}\n```\n\n## Transactional Semantics\n\nThe behavior of `failFast: true` depends on whether your database provider\nsupports transactions. The response's `meta.transactional` flag tells you\nwhich guarantee you actually got — inspect it in clients that care about\nrollback.\n\n### Per-Provider Matrix\n\n| Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |\n|----------|----------|-----------|----------------------|----------|\n| `PATCH /batch` (update) | postgres / supabase / neon / libsql / better-sqlite3 / bun-sqlite | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |\n| `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |\n| `PATCH /batch` (update) | cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — D1 has no `db.transaction`. Records before the failure stay committed. |\n| `PUT /batch` (upsert) | tx-supporting | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |\n| `PUT /batch` (upsert) | cloudflare-d1 | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |\n| `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |\n| `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |\n\n### Reading `meta.transactional` in clients\n\n```typescript\nconst res = await fetch('/api/v1/jobs/batch', {\n method: 'PATCH',\n body: JSON.stringify({ records, options: { failFast: true } }),\n});\nconst body = await res.json();\n\nif (!body.meta.transactional && body.errors.length > 0) {\n // Some records succeeded before the failure and remain committed.\n // Compensate via the success array if needed.\n}\n```\n\n### Embeddings and Realtime\n\nWhen a resource has `embeddings` or `realtime` configured, queue messages\nand broadcasts are emitted **after** the transaction commits. A\nrolled-back batch produces no orphan embedding jobs.\n\n## Batch Size Limit\n\nThe default maximum batch size is **100 records**. Requests exceeding the limit are rejected:\n\n```json\n{\n \"error\": \"Batch size limit exceeded\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_SIZE_EXCEEDED\",\n \"details\": { \"max\": 100, \"actual\": 250 },\n \"hint\": \"Maximum 100 records allowed per batch. Split into multiple requests.\"\n}\n```\n\n## Configuration\n\nBatch operations inherit access control from their corresponding CRUD operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n crud: {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },\n\n // Override batch-specific settings\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n batchUpdate: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n batchDelete: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n\n // Disable a batch operation entirely\n batchUpsert: false,\n },\n});\n```\n\n## Security\n\nAll security pillars apply to batch operations:\n\n1. **Authentication** — Required for all batch endpoints (401 if missing)\n2. **Firewall** — Applied per-record for update/delete/upsert (not applicable to create)\n3. **Access** — Role-based check using the batch operation's access config\n4. **Guards** — Per-record validation (createable/updatable/immutable fields)\n5. **Masking** — Applied to all records in the success array before response\n\n## See Also\n\n- [CRUD Endpoints](/compiler/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
|
|
291
295
|
},
|
|
292
296
|
"compiler/using-the-api/caching": {
|
|
293
297
|
"title": "Caching & ETags",
|
|
@@ -295,7 +299,7 @@ export const DOCS = {
|
|
|
295
299
|
},
|
|
296
300
|
"compiler/using-the-api/crud": {
|
|
297
301
|
"title": "CRUD Endpoints",
|
|
298
|
-
"content": "Quickback automatically generates RESTful CRUD endpoints for each resource you define. This page covers how to use these endpoints.\n\n## Quick Reference\n\nAll endpoints require authentication. Include your session cookie or Bearer token:\n\n```bash\n# List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\"\n\n# Get a single record\ncurl http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# Create a record\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# Update a record\ncurl -X PATCH http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Staff Engineer\"}'\n\n# Delete a record\ncurl -X DELETE http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# List with filters, sorting, and pagination\ncurl \"http://localhost:8787/api/v1/jobs?status=open&sort=createdAt:desc&limit=25&count=true\" \\\n -H \"Authorization: Bearer <token>\"\n```\n\n## Endpoint Overview\n\nFor a resource named `jobs`, Quickback generates:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/jobs` | List all records |\n| `GET` | `/jobs/:id` | Get a single record |\n| `POST` | `/jobs` | Create a new record |\n| `POST` | `/jobs/batch` | Batch create multiple records |\n| `PATCH` | `/jobs/:id` | Update a record |\n| `PATCH` | `/jobs/batch` | Batch update multiple records |\n| `DELETE` | `/jobs/:id` | Delete a record |\n| `DELETE` | `/jobs/batch` | Batch delete multiple records |\n| `PUT` | `/jobs/:id` | Upsert a record (requires config) |\n| `PUT` | `/jobs/batch` | Batch upsert multiple records (requires config) |\n\n## List Records\n\n```\nGET /jobs\n```\n\nReturns a paginated list of records the user has access to.\n\n### Query Parameters\n\n| Parameter | Description | Example |\n|-----------|-------------|---------|\n| `limit` | Number of records to return (default: 50, max: 100) | `?limit=25` |\n| `offset` | Number of records to skip | `?offset=50` |\n| `sort` | Field to sort by | `?sort=createdAt` |\n| `order` | Sort direction: `asc` or `desc` | `?order=desc` |\n\n### Filtering\n\nFilter records using query parameters:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMax.gt=100000 # Greater than\nGET /jobs?salaryMin.gte=80000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=150000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n### Response\n\n```json\n{\n \"data\": [\n {\n \"id\": \"job_123\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T10:30:00Z\"\n }\n ],\n \"pagination\": {\n \"limit\": 50,\n \"offset\": 0,\n \"count\": 1\n }\n}\n```\n\n### FK Label Resolution\n\nForeign key columns are automatically enriched with `_label` fields containing the referenced table's display value. For example, `departmentId` gets a corresponding `department_label` field. See [Display Column](/compiler/definitions/schema#display-column) for details.\n\n## Get Single Record\n\n```\nGET /jobs/:id\n```\n\nReturns a single record by ID.\n\n### Response\n\n```json\n{\n \"id\": \"job_123\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T10:30:00Z\"\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `404` | Record not found or not accessible |\n| `403` | User lacks permission to view this record |\n\n## Create Record\n\n```\nPOST /jobs\nContent-Type: application/json\n\n{\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000\n}\n```\n\nCreates a new record. Only fields listed in `guards.createable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_456\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T11:00:00Z\",\n \"createdBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or missing required field |\n| `403` | User lacks permission to create records |\n\n## Update Record\n\n```\nPATCH /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Staff Engineer\"\n}\n```\n\nUpdates an existing record. Only fields listed in `guards.updatable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"title\": \"Staff Engineer\",\n \"modifiedAt\": \"2024-01-15T12:00:00Z\",\n \"modifiedBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or field not updatable |\n| `403` | User lacks permission to update this record |\n| `404` | Record not found |\n\n## Delete Record\n\n```\nDELETE /jobs/:id\n```\n\nDeletes a record. Behavior depends on the `delete.mode` configuration.\n\n### Soft Delete (default)\n\nSets `deletedAt` and `deletedBy` fields. Record remains in database but is filtered from queries.\n\n### Hard Delete\n\nPermanently removes the record from the database.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"deleted\": true\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `403` | User lacks permission to delete this record |\n| `404` | Record not found |\n\n## Upsert Record (PUT)\n\n```\nPUT /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Contract Recruiter\",\n \"department\": \"Talent Acquisition\",\n \"status\": \"open\",\n \"externalId\": \"ext-123\"\n}\n```\n\nCreates or updates a record by ID. Requires special configuration:\n\n1. `generateId: false` in database config\n2. `guards: false` in resource definition\n\n### Behavior\n\n- If record exists: Updates all provided fields\n- If record doesn't exist: Creates with the provided ID\n\n### Use Cases\n\n- Syncing data from external systems\n- Webhook handlers with external IDs\n- Idempotent operations (safe to retry)\n\nSee [Guards documentation](/compiler/definitions/guards#putupsert-with-external-ids) for setup details.\n\n## Batch Operations\n\nQuickback provides batch endpoints for efficient bulk operations. Batch operations automatically inherit from their corresponding CRUD operations and maintain full security layer consistency.\n\n### Batch Create Records\n\n```\nPOST /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" },\n { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\nCreates multiple records in a single request. Each record follows the same validation rules as single create operations.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects to create |\n| `options.atomic` | Boolean | If `true`, all records succeed or all fail (default: `false`) |\n\n#### Response (Partial Success - Default)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"id\": \"job_2\", \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"atomic\": false\n }\n}\n```\n\n#### HTTP Status Codes\n\n- `201` - All records created successfully\n- `207` - Partial success (some records failed)\n- `400` - Atomic mode enabled and one or more records failed\n\n#### Batch Size Limit\n\nDefault: 100 records per request (configurable via `maxBatchSize`)\n\n### Batch Update Records\n\n```\nPATCH /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\" },\n { \"id\": \"job_3\", \"status\": \"closed\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\nUpdates multiple records in a single request. All records must include an `id` field.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and fields to update |\n| `options.atomic` | Boolean | If `true`, all records succeed or all fail (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"job_3\", \"status\": \"closed\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"atomic\": false\n }\n}\n```\n\n#### Features\n\n- **Batch fetching**: Single database query for all IDs (with firewall)\n- **Per-record access**: Access checks run with record context\n- **Field validation**: Guards apply to each record individually\n\n### Batch Delete Records\n\n```\nDELETE /jobs/batch\nContent-Type: application/json\n\n{\n \"ids\": [\"job_1\", \"job_2\", \"job_3\"],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\nDeletes multiple records in a single request. Supports both soft and hard delete modes.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `ids` | Array | Array of record IDs to delete |\n| `options.atomic` | Boolean | If `true`, all records succeed or all fail (default: `false`) |\n\n#### Response (Soft Delete)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" },\n { \"id\": \"job_2\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"id\": \"job_3\",\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"atomic\": false\n }\n}\n```\n\n#### Delete Modes\n\n- **Soft delete** (default): Sets `deletedAt`, `deletedBy`, `modifiedAt`, `modifiedBy` fields\n- **Hard delete**: Permanently removes records from database\n\n### Batch Upsert Records\n\n```\nPUT /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\" }\n ],\n \"options\": {\n \"atomic\": false\n }\n}\n```\n\nCreates or updates multiple records in a single request. Creates if ID doesn't exist, updates if it does.\n\n**Strict Requirements** (same as single PUT):\n1. `generateId: false` in database config (user provides IDs)\n2. `guards: false` in resource definition (no field restrictions)\n3. All records must include an `id` field\n\n**Note**: System-managed fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are always protected and will be rejected if included in the request, regardless of guards configuration.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and all fields |\n| `options.atomic` | Boolean | If `true`, all records succeed or all fail (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\", \"modifiedAt\": \"2024-01-15T16:00:00Z\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\", \"createdAt\": \"2024-01-15T16:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"atomic\": false\n }\n}\n```\n\n#### How It Works\n\n1. Batch existence check with firewall\n2. Split records into CREATE and UPDATE batches\n3. Validate new records with `validateCreate()`\n4. Validate existing records with `validateUpdate()`\n5. Check CREATE access for new records\n6. Check UPDATE access for existing records (per-record)\n7. Execute bulk insert and individual updates\n8. Return combined results\n\n### Batch Operation Features\n\n#### Partial Success Mode (Default)\n\nBy default, batch operations use **partial success** mode:\n- All records are processed independently\n- Failed records go into `errors` array with detailed error information\n- Successful records go into `success` array\n- HTTP status `207 Multi-Status` if any errors, `201`/`200` if all success\n\n```json\n{\n \"success\": [ /* succeeded records */ ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { /* original input */ },\n \"error\": {\n \"error\": \"Human-readable message\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": {\n \"total\": 10,\n \"succeeded\": 8,\n \"failed\": 2,\n \"atomic\": false\n }\n}\n```\n\n#### Atomic Mode (Opt-in)\n\nEnable **atomic mode** for all-or-nothing behavior:\n\n```json\n{\n \"records\": [ /* ... */ ],\n \"options\": {\n \"atomic\": true\n }\n}\n```\n\n**Atomic mode behavior**:\n- First error immediately stops processing\n- All changes are rolled back (database transaction)\n- HTTP status `400 Bad Request`\n- Returns single error with failure details\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\": { /* the actual error */ }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n#### Human-Readable Errors\n\nAll batch operation errors include:\n- **Layer identification**: Which security layer rejected the request\n- **Error code**: Machine-readable code for programmatic handling\n- **Clear message**: Human-readable explanation\n- **Details**: Contextual information (fields, IDs, reasons)\n- **Helpful hints**: Actionable guidance for resolution\n\n#### Performance Optimizations\n\n- **Batch size limits**: Default 100 records (prevents memory exhaustion)\n- **Single firewall query**: `WHERE id IN (...)` instead of N queries\n- **Bulk operations**: Single INSERT for multiple records (CREATE, UPSERT)\n- **O(1) lookups**: Map-based record lookup instead of Array.find()\n\n#### Configuration\n\nBatch operations are **auto-enabled** when corresponding CRUD operations exist:\n\n```typescript\n// Auto-enabled - no configuration needed\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } }\n // batchCreate and batchUpdate automatically available\n}\n\n// Customize batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // Different access rules\n maxBatchSize: 50, // Lower limit\n allowAtomic: false // Disable atomic mode\n }\n}\n\n// Disable batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: false // Explicitly disable\n}\n```\n\n#### Security Layer Application\n\nBatch operations maintain **full security layer consistency**:\n\n1. **Firewall**: Auto-apply ownership fields, batch fetch with isolation\n2. **Access**: Operation-level for CREATE, per-record for UPDATE/DELETE\n3. **Guards**: Per-record field validation (same rules as single operations)\n4. **Masking**: Applied to success array (respects user permissions)\n5. **Audit**: Single timestamp for entire batch for consistency\n\n## Authentication\n\nAll endpoints require authentication. Include your auth token in the request header:\n\n```\nAuthorization: Bearer <your-token>\n```\n\nThe user's context (userId, roles, organizationId) is extracted from the token and used to:\n\n1. Apply firewall filters (data isolation)\n2. Check access permissions\n3. Set audit fields (createdBy, modifiedBy)\n\n## Error Responses\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\nSee [Errors](/compiler/using-the-api/errors) for the complete reference of error codes by security layer."
|
|
302
|
+
"content": "Quickback automatically generates RESTful CRUD endpoints for each resource you define. This page covers the write side (create, update, delete, upsert) and lists collection-read endpoints. Read-side configuration lives under [`read:`](/compiler/definitions/read).\n\n> **Migration note**: `crud.list` and `crud.get` are rejected at compile time in DSL v2. List-level access moves to [`read.access`](/compiler/definitions/read), and per-field projections move to named views under [`read.views`](/compiler/definitions/read#views-under-read-views). See the [migration table](/compiler/definitions/read#migrating-from-crud-list-crud-get).\n\n## Quick Reference\n\nAll endpoints require authentication. Include your session cookie or Bearer token:\n\n```bash\n# List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\"\n\n# Get a single record\ncurl http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# Create a record\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# Update a record\ncurl -X PATCH http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Staff Engineer\"}'\n\n# Delete a record\ncurl -X DELETE http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# List with filters, sorting, and pagination\ncurl \"http://localhost:8787/api/v1/jobs?status=open&sort=createdAt:desc&limit=25&count=true\" \\\n -H \"Authorization: Bearer <token>\"\n```\n\n## Endpoint Overview\n\nFor a resource named `jobs`, Quickback generates:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/jobs` | List all records |\n| `GET` | `/jobs/:id` | Get a single record |\n| `POST` | `/jobs` | Create a new record |\n| `POST` | `/jobs/batch` | Batch create multiple records |\n| `PATCH` | `/jobs/:id` | Update a record |\n| `PATCH` | `/jobs/batch` | Batch update multiple records |\n| `DELETE` | `/jobs/:id` | Delete a record |\n| `DELETE` | `/jobs/batch` | Batch delete multiple records |\n| `PUT` | `/jobs/:id` | Upsert a record (requires config) |\n| `PUT` | `/jobs/batch` | Batch upsert multiple records (requires config) |\n\n## List & Get Records\n\n`GET /{resource}` and `GET /{resource}/:id` are part of the [read pipeline](/compiler/definitions/read). Configuration (access, pagination, view projections) lives under `read:`. Filtering, sorting, and pagination query parameters work the same on both endpoints — see [Query Parameters](/compiler/using-the-api/query-params).\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n pageSize: 25,\n maxPageSize: 100,\n views: {\n summary: { fields: ['id', 'title', 'status'], access: { roles: ['interviewer'] } },\n },\n}\n```\n\nCalls a client makes:\n\n```bash\nGET /jobs # Collection — gated by read.access\nGET /jobs/:id # Single — gated by read.access (with ID-probe defense)\nGET /jobs?view=summary # View dispatch\nGET /jobs/views/summary # Explicit view path\n```\n\n### ID-probe defense on `/:id`\n\nSingle-record reads run a role-only access check **before** the firewall query, so an unauthorized caller can't tell apart \"row exists in another tenant\" from \"row doesn't exist.\" See [Access ordering](/compiler/definitions/read#access-ordering-on-id) for details.\n\n| Status | Description |\n|--------|-------------|\n| `401` | Not authenticated |\n| `403` | Authenticated but role doesn't satisfy `read.access` |\n| `404` | Authenticated and role passes, but firewall excluded the record (or it doesn't exist). Set [`firewallErrorMode: 'reveal'`](/compiler/definitions/firewall) to return 403 instead. |\n\n### FK Label Resolution\n\nForeign key columns are automatically enriched with `_label` fields containing the referenced table's display value. For example, `departmentId` gets a corresponding `department_label` field. See [Display Column](/compiler/definitions/schema#display-column) for details.\n\n## Create Record\n\n```\nPOST /jobs\nContent-Type: application/json\n\n{\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000\n}\n```\n\nCreates a new record. Only fields listed in `guards.createable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_456\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T11:00:00Z\",\n \"createdBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or missing required field |\n| `403` | User lacks permission to create records |\n\n## Update Record\n\n```\nPATCH /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Staff Engineer\"\n}\n```\n\nUpdates an existing record. Only fields listed in `guards.updatable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"title\": \"Staff Engineer\",\n \"modifiedAt\": \"2024-01-15T12:00:00Z\",\n \"modifiedBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or field not updatable |\n| `403` | User lacks permission to update this record |\n| `404` | Record not found |\n\n## Delete Record\n\n```\nDELETE /jobs/:id\n```\n\nDeletes a record. Behavior depends on the `delete.mode` configuration.\n\n### Soft Delete (default)\n\nSets `deletedAt` and `deletedBy` fields. Record remains in database but is filtered from queries.\n\n### Hard Delete\n\nPermanently removes the record from the database.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"deleted\": true\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `403` | User lacks permission to delete this record |\n| `404` | Record not found |\n\n## Upsert Record (PUT)\n\n```\nPUT /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Contract Recruiter\",\n \"department\": \"Talent Acquisition\",\n \"status\": \"open\",\n \"externalId\": \"ext-123\"\n}\n```\n\nCreates or updates a record by ID. Requires special configuration:\n\n1. `generateId: false` in database config\n2. `guards: false` in resource definition\n\n### Behavior\n\n- If record exists: Updates all provided fields\n- If record doesn't exist: Creates with the provided ID\n\n### Use Cases\n\n- Syncing data from external systems\n- Webhook handlers with external IDs\n- Idempotent operations (safe to retry)\n\nSee [Guards documentation](/compiler/definitions/guards#putupsert-with-external-ids) for setup details.\n\n## Batch Operations\n\nQuickback provides batch endpoints for efficient bulk operations. Batch operations automatically inherit from their corresponding CRUD operations and maintain full security layer consistency.\n\n### Batch Create Records\n\n```\nPOST /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" },\n { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates multiple records in a single request. Each record follows the same validation rules as single create operations.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects to create |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Partial Success - Default)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"id\": \"job_2\", \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n#### HTTP Status Codes\n\n- `201` - All records created successfully\n- `207` - Partial success (some records failed)\n- `400` - `failFast: true` was set and one or more records failed\n\n#### Batch Size Limit\n\nDefault: 100 records per request (configurable via `maxBatchSize`)\n\n### Batch Update Records\n\n```\nPATCH /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\" },\n { \"id\": \"job_3\", \"status\": \"closed\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nUpdates multiple records in a single request. All records must include an `id` field.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and fields to update |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"job_3\", \"status\": \"closed\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n#### Features\n\n- **Batch fetching**: Single database query for all IDs (with firewall)\n- **Per-record access**: Access checks run with record context\n- **Field validation**: Guards apply to each record individually\n\n### Batch Delete Records\n\n```\nDELETE /jobs/batch\nContent-Type: application/json\n\n{\n \"ids\": [\"job_1\", \"job_2\", \"job_3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nDeletes multiple records in a single request. Supports both soft and hard delete modes.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `ids` | Array | Array of record IDs to delete |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Soft Delete)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" },\n { \"id\": \"job_2\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"id\": \"job_3\",\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n#### Delete Modes\n\n- **Soft delete** (default): Sets `deletedAt`, `deletedBy`, `modifiedAt`, `modifiedBy` fields\n- **Hard delete**: Permanently removes records from database\n\n### Batch Upsert Records\n\n```\nPUT /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates or updates multiple records in a single request. Creates if ID doesn't exist, updates if it does.\n\n**Strict Requirements** (same as single PUT):\n1. `generateId: false` in database config (user provides IDs)\n2. `guards: false` in resource definition (no field restrictions)\n3. All records must include an `id` field\n\n**Note**: System-managed fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are always protected and will be rejected if included in the request, regardless of guards configuration.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and all fields |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\", \"modifiedAt\": \"2024-01-15T16:00:00Z\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\", \"createdAt\": \"2024-01-15T16:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"atomic\": false\n }\n}\n```\n\n#### How It Works\n\n1. Batch existence check with firewall\n2. Split records into CREATE and UPDATE batches\n3. Validate new records with `validateCreate()`\n4. Validate existing records with `validateUpdate()`\n5. Check CREATE access for new records\n6. Check UPDATE access for existing records (per-record)\n7. Execute bulk insert and individual updates\n8. Return combined results\n\n### Batch Operation Features\n\n#### Partial Success Mode (Default)\n\nBy default, batch operations use **partial success** mode:\n- All records are processed independently\n- Failed records go into `errors` array with detailed error information\n- Successful records go into `success` array\n- HTTP status `207 Multi-Status` if any errors, `201`/`200` if all success\n\n```json\n{\n \"success\": [ /* succeeded records */ ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { /* original input */ },\n \"error\": {\n \"error\": \"Human-readable message\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": {\n \"total\": 10,\n \"succeeded\": 8,\n \"failed\": 2,\n \"atomic\": false\n }\n}\n```\n\n#### Fail-Fast Mode (Opt-in)\n\nSet `options.failFast: true` to stop on the first error. On providers that\nsupport transactions, the loop is wrapped in `db.transaction(...)` so prior\nwrites roll back. The response's `meta.transactional` field tells you\nwhether you got real rollback or just early-stop semantics — see\n[Batch Operations: Transactional semantics](/compiler/using-the-api/batch-operations#transactional-semantics).\n\n```json\n{\n \"records\": [ /* ... */ ],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\nOn the first failure under `failFast: true`:\n- Processing stops; no further records are attempted\n- HTTP status `400 Bad Request`\n- A single error is returned\n\n```json\n{\n \"error\": \"Batch failed at index 2\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { /* the actual error */ }\n }\n}\n```\n\n#### Human-Readable Errors\n\nAll batch operation errors include:\n- **Layer identification**: Which security layer rejected the request\n- **Error code**: Machine-readable code for programmatic handling\n- **Clear message**: Human-readable explanation\n- **Details**: Contextual information (fields, IDs, reasons)\n- **Helpful hints**: Actionable guidance for resolution\n\n#### Performance Optimizations\n\n- **Batch size limits**: Default 100 records (prevents memory exhaustion)\n- **Single firewall query**: `WHERE id IN (...)` instead of N queries\n- **Bulk operations**: Single INSERT for multiple records (CREATE, UPSERT)\n- **O(1) lookups**: Map-based record lookup instead of Array.find()\n\n#### Configuration\n\nBatch operations are **auto-enabled** when corresponding CRUD operations exist:\n\n```typescript\n// Auto-enabled - no configuration needed\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } }\n // batchCreate and batchUpdate automatically available\n}\n\n// Customize batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // Different access rules\n maxBatchSize: 50, // Lower limit\n allowFailFast: false // Disable failFast mode\n }\n}\n\n// Disable batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: false // Explicitly disable\n}\n```\n\n#### Security Layer Application\n\nBatch operations maintain **full security layer consistency**:\n\n1. **Firewall**: Auto-apply ownership fields, batch fetch with isolation\n2. **Access**: Operation-level for CREATE, per-record for UPDATE/DELETE\n3. **Guards**: Per-record field validation (same rules as single operations)\n4. **Masking**: Applied to success array (respects user permissions)\n5. **Audit**: Single timestamp for entire batch for consistency\n\n## Authentication\n\nAll endpoints require authentication. Include your auth token in the request header:\n\n```\nAuthorization: Bearer <your-token>\n```\n\nThe user's context (userId, roles, organizationId) is extracted from the token and used to:\n\n1. Apply firewall filters (data isolation)\n2. Check access permissions\n3. Set audit fields (createdBy, modifiedBy)\n\n## Error Responses\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\nSee [Errors](/compiler/using-the-api/errors) for the complete reference of error codes by security layer."
|
|
299
303
|
},
|
|
300
304
|
"compiler/using-the-api/errors": {
|
|
301
305
|
"title": "Errors",
|
|
@@ -315,7 +319,7 @@ export const DOCS = {
|
|
|
315
319
|
},
|
|
316
320
|
"compiler/using-the-api/views-api": {
|
|
317
321
|
"title": "Views API",
|
|
318
|
-
"content": "Views provide named column projections that limit which fields are returned in API responses. Each view can have its own access control, and all security pillars (firewall, masking) still apply.\n\n##
|
|
322
|
+
"content": "Views provide named column projections that limit which fields are returned in API responses. Each view can have its own access control, and all security pillars (firewall, masking) still apply.\n\n## Endpoints\n\nViews are dispatched two equivalent ways:\n\n```\nGET /api/v1/{resource}?view={view-name} # Query-string dispatch\nGET /api/v1/{resource}/views/{view-name} # Explicit path\n```\n\nBoth forms are emitted automatically and behave identically.\n\n## Example\n\nGiven this definition (views live under [`read.views`](/compiler/definitions/read#views-under-read-views)):\n\n```typescript\nexport default defineTable(candidates, {\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n },\n },\n },\n // ...\n});\n```\n\n### Request\n\n```bash\n# Query-string form\ncurl '/api/v1/candidates?view=pipeline' \\\n -H \"Authorization: Bearer <token>\"\n\n# Path form (equivalent)\ncurl /api/v1/candidates/views/pipeline \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Response\n\n```json\n{\n \"data\": [\n { \"id\": \"cand_001\", \"name\": \"Alice Johnson\", \"source\": \"LinkedIn\" },\n { \"id\": \"cand_002\", \"name\": \"Bob Martinez\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"fields\": [\"id\", \"name\", \"source\"],\n \"pagination\": {\n \"limit\": 50,\n \"offset\": 0,\n \"count\": 2\n }\n}\n```\n\nOnly the fields specified in the view definition are returned. Requesting the `full` view with an `interviewer` role returns 403.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `limit` | Number of records to return (1–100) | `50` |\n| `offset` | Number of records to skip | `0` |\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n| `{field}` | Filter by exact value | — |\n| `{field}.gt` | Greater than | — |\n| `{field}.gte` | Greater than or equal | — |\n| `{field}.lt` | Less than | — |\n| `{field}.lte` | Less than or equal | — |\n| `{field}.ne` | Not equal | — |\n| `{field}.like` | Pattern match (SQL LIKE) | — |\n| `{field}.in` | Match any value in comma-separated list | — |\n\n### Examples\n\n```bash\n# Paginated with sorting\nGET /api/v1/candidates/views/pipeline?limit=10&offset=0&sort=name&order=asc\n\n# With filters\nGET /api/v1/candidates/views/pipeline?source=referral&name.like=%25Johnson%25\n\n# Combined\nGET /api/v1/candidates/views/pipeline?source.in=LinkedIn,referral&sort=name&order=asc&limit=25\n```\n\n## Security\n\nAll security pillars apply to view endpoints:\n\n1. **Authentication** — Required (401 if missing)\n2. **Firewall** — Organization/user isolation applied to all results. Only records the user owns or has access to are returned.\n3. **Access** — Per-view role check. Each view can require different roles.\n4. **Masking** — Applied to all returned fields. If a masked field is in the view's field list, the masking rules still apply based on the user's role.\n\n### Access Control Per View\n\nDifferent views can require different permission levels:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Available to all org members including interviewers\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Restricted view with contact details\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\nAn `interviewer` requesting the `full` view receives:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": { \"required\": [\"hiring-manager\", \"recruiter\"], \"current\": [\"interviewer\"] }\n}\n```\n\n### Masking in Views\n\nMasking is applied after field projection. If your masking config hides `phone` from interviewers:\n\n```typescript\nmasking: {\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n}\n```\n\nAn `interviewer` requesting a view that includes `phone` will see the masked value (e.g., `***-***-5678`), while a `recruiter` sees the full value.\n\n## See Also\n\n- [Defining Views](/compiler/definitions/views) — How to configure views in defineTable\n- [Query Parameters](/compiler/using-the-api/query-params) — Full query parameter reference\n- [Access Control](/compiler/definitions/access) — Role-based access configuration"
|
|
319
323
|
},
|
|
320
324
|
"index": {
|
|
321
325
|
"title": "Quickback Documentation",
|
|
@@ -403,11 +407,11 @@ export const DOCS = {
|
|
|
403
407
|
},
|
|
404
408
|
"stack/realtime/durable-objects": {
|
|
405
409
|
"title": "Realtime",
|
|
406
|
-
"content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: { organization: {} },\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\n## Generated Helper\n\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated users in the organization receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/realtime/v1/ws-ticket', {\n method: 'POST',\n headers: { Authorization: `Bearer ${sessionToken}` },\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/realtime/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /realtime/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade — no HTTP round-trip.\n3. **API broadcasts** — After CRUD ops, the API calls the Broadcaster DO directly via its binding (in-process, no network hop).\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
|
|
410
|
+
"content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\n## Generated Helper\n\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated users in the organization receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/realtime/v1/ws-ticket', {\n method: 'POST',\n headers: { Authorization: `Bearer ${sessionToken}` },\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/realtime/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /realtime/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade — no HTTP round-trip.\n3. **API broadcasts** — After CRUD ops, the API calls the Broadcaster DO directly via its binding (in-process, no network hop).\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
|
|
407
411
|
},
|
|
408
412
|
"stack/realtime": {
|
|
409
413
|
"title": "Realtime",
|
|
410
|
-
"content": "The Quickback Stack uses Cloudflare Durable Objects to broadcast real-time updates over WebSockets. CRUD events and custom broadcasts are delivered to connected clients with the same security layers (firewall isolation, role-based filtering, field masking) applied.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per organization. One instance per org.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Organization-scoped | Each org gets its own Durable Object instance |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nAdd `realtime` to individual table definitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: {
|
|
414
|
+
"content": "The Quickback Stack uses Cloudflare Durable Objects to broadcast real-time updates over WebSockets. CRUD events and custom broadcasts are delivered to connected clients with the same security layers (firewall isolation, role-based filtering, field masking) applied.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per organization. One instance per org.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Organization-scoped | Each org gets its own Durable Object instance |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nAdd `realtime` to individual table definitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n requiredRoles: [\"recruiter\", \"hiring-manager\"],\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime binding in your database config. The compiler generates the Durable Object class, helper functions, and wrangler bindings — all within your main worker.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — WebSocket connection, authentication, and client-side handling"
|
|
411
415
|
},
|
|
412
416
|
"stack/realtime/using-realtime": {
|
|
413
417
|
"title": "Using Realtime",
|
|
@@ -435,7 +439,7 @@ export const DOCS = {
|
|
|
435
439
|
},
|
|
436
440
|
"stack/vector/embeddings": {
|
|
437
441
|
"title": "Automatic Embeddings",
|
|
438
|
-
"content": "Quickback can automatically generate embeddings for your data using Cloudflare Queues and Workers AI. When configured, INSERT and UPDATE operations automatically enqueue embedding jobs that are processed asynchronously.\n\n## Enabling Embeddings\n\nAdd an `embeddings` configuration to your resource definition:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default defineTable(jobs, {\n firewall: { organization: {} },\n\n embeddings: {\n fields: ['description'], // Fields to concatenate and embed\n model: '@cf/baai/bge-base-en-v1.5', // Embedding model (optional)\n onInsert: true, // Auto-embed on create (default: true)\n onUpdate: ['description'], // Re-embed when these fields change\n embeddingColumn: 'embedding', // Column to store embedding\n metadata: ['department'], // Metadata for Vectorize index\n },\n\n crud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } },\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `fields` | `string[]` | **Required** | Fields to concatenate and embed |\n| `model` | `string` | `'@cf/baai/bge-base-en-v1.5'` | Workers AI embedding model |\n| `onInsert` | `boolean` | `true` | Embed on INSERT operations |\n| `onUpdate` | `boolean \\| string[]` | `true` | Embed on UPDATE; array limits to specific fields |\n| `embeddingColumn` | `string` | `'embedding'` | Column to store the embedding vector |\n| `separator` | `string` | `' '` | Separator for joining multiple fields |\n| `metadata` | `string[]` | `[]` | Fields to include in Vectorize metadata |\n\n### onUpdate Options\n\n```typescript\n// Always re-embed on any update\nonUpdate: true\n\n// Never re-embed on update\nonUpdate: false\n\n// Only re-embed when specific fields change\nonUpdate: ['description', 'title']\n```\n\n## How It Works\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Main API Worker │\n│ │\n│ ┌─────────────────────┐ ┌────────────────────┐ │\n│ │ POST /jobs │ │ Queue Consumer │ │\n│ │ │ │ │ │\n│ │ 1. Auth middleware │ │ 1. Workers AI │ │\n│ │ 2. Firewall │ │ embed() │ │\n│ │ 3. Guards │ │ 2. D1 update() │ │\n│ │ 4. Insert to D1 │ │ 3. Vectorize │ │\n│ │ 5. Enqueue job ─────┼───▶│ upsert() │ │\n│ └─────────────────────┘ └────────────────────┘ │\n│ ▲ │\n│ ┌─────────────────┴──────────────────┐ │\n│ │ EMBEDDINGS_QUEUE │ │\n│ └────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n1. **API Request** - POST/PATCH arrives and passes through auth, firewall, guards\n2. **Database Insert** - Record is created/updated in D1\n3. **Enqueue Job** - Embedding job is sent to Cloudflare Queue\n4. **Queue Consumer** - Processes job asynchronously:\n - Calls Workers AI to generate embedding\n - Updates D1 with embedding vector\n - Optionally upserts to Vectorize index\n\n## Security Model\n\n**Security is enforced at enqueue time, not consume time:**\n\n- Jobs are only enqueued after passing all security checks (auth, firewall, guards)\n- The queue consumer is an internal process that executes pre-validated jobs\n- If a user can't create a job posting, they can't trigger an embedding job\n\n## Generic Embeddings API\n\nIn addition to automatic embeddings on CRUD operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.\n\n### POST /api/v1/embeddings\n\nGenerate an embedding for any text content:\n\n```bash\ncurl -X POST https://your-api.workers.dev/api/v1/embeddings \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -d '{\n \"content\": \"Text to embed\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\",\n \"table\": \"jobs\",\n \"id\": \"job_123\"\n }'\n```\n\n#### Request Body\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `content` | `string` | Yes | Text to generate embedding for |\n| `model` | `string` | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |\n| `table` | `string` | No | Table to store embedding back to |\n| `id` | `string` | Conditional | Record ID to update (required if `table` is specified) |\n\n#### Response\n\n```json\n{\n \"queued\": true,\n \"jobId\": \"550e8400-e29b-41d4-a716-446655440000\",\n \"table\": \"jobs\",\n \"id\": \"job_123\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n}\n```\n\n### GET /api/v1/embeddings/tables\n\nList tables that have embeddings configured:\n\n```bash\ncurl https://your-api.workers.dev/api/v1/embeddings/tables \\\n -H \"Cookie: better-auth.session_token=...\"\n```\n\nResponse:\n\n```json\n{\n \"tables\": [\n {\n \"name\": \"jobs\",\n \"embeddingColumn\": \"embedding\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n }\n ]\n}\n```\n\n### Authentication & Authorization\n\nThe generic embeddings API requires authentication and uses the `activeOrgId` from the user's context to enforce organization-level isolation. Embedding jobs are scoped to the user's current organization.\n\n### Use Cases\n\nThe generic embeddings API is useful for:\n\n- **Batch embedding**: Embed content without going through CRUD routes\n- **Re-embedding**: Force re-generation of embeddings for existing records\n- **Preview embeddings**: Test embedding generation before persisting\n- **External content**: Embed content that doesn't fit your defined schemas\n\n## Generated Files\n\nWhen embeddings are configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/queue-consumer.ts` | Queue consumer handler for processing embedding jobs |\n| `src/routes/embeddings.ts` | Generic embeddings API routes |\n| `wrangler.toml` | Queue producer/consumer bindings, AI binding |\n| `src/env.d.ts` | `EMBEDDINGS_QUEUE`, `AI` types |\n| `src/index.ts` | Exports `queue` handler, mounts `/api/v1/embeddings` |\n\n### wrangler.toml additions\n\n```toml\n# Embeddings Queue\n[[queues.producers]]\nqueue = \"your-app-embeddings-queue\"\nbinding = \"EMBEDDINGS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"your-app-embeddings-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n# Workers AI\n[ai]\nbinding = \"AI\"\n```\n\n## Multiple Fields\n\nEmbed multiple fields by concatenating them:\n\n```typescript\nembeddings: {\n fields: ['title', 'description', 'department'], // Joined with spaces by default\n // ...\n}\n```\n\nGenerated embedding text: `\"${title} ${description} ${department}\"`\n\n### Custom Separator\n\nUse `separator` to control how fields are joined. This is useful for sentence boundary detection:\n\n```typescript\nembeddings: {\n fields: ['title', 'description'],\n separator: '. ', // Join with period + space\n // ...\n}\n```\n\nGenerated code: `[result[0].title, result[0].description].filter(Boolean).join('. ')`\n\nThe `filter(Boolean)` ensures null or empty fields are excluded cleanly — no trailing separator when a field is absent.\n\n## Vectorize Integration\n\nIf you have a Vectorize index configured, embeddings are automatically upserted:\n\n```typescript\n// quickback.config.ts\nproviders: {\n database: {\n config: {\n vectorizeIndexName: 'jobs-embeddings', // Your Vectorize index\n vectorizeBinding: 'VECTORIZE',\n },\n },\n},\n```\n\nThe queue consumer will:\n1. Generate the embedding via Workers AI\n2. Store the vector in D1 (JSON string)\n3. Upsert to Vectorize with metadata\n\n### Vectorize Metadata\n\nInclude fields in Vectorize metadata for filtering:\n\n```typescript\nembeddings: {\n fields: ['description'],\n metadata: ['department', 'organizationId', 'status'],\n}\n```\n\nEnables queries like:\n```typescript\nconst results = await env.VECTORIZE.query(vector, {\n topK: 10,\n filter: { department: 'engineering' }\n});\n```\n\n## Schema Requirements\n\nYour schema must include the embedding column:\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 description: q.text().required(),\n department: q.text().optional(),\n status: q.text().required(),\n organizationId: q.text().required(),\n\n // Embedding column — stores JSON array of floats\n embedding: q.text().optional(),\n },\n firewall: { organization: {} },\n crud: { list: {}, get: {}, create: {}, update: {}, delete: {} },\n});\n```\n\n## Supported Models\n\nAny Workers AI embedding model can be used:\n\n| Model | Dimensions | Notes |\n|-------|------------|-------|\n| `@cf/baai/bge-base-en-v1.5` | 768 | Default, good general-purpose |\n| `@cf/baai/bge-small-en-v1.5` | 384 | Faster, smaller |\n| `@cf/baai/bge-large-en-v1.5` | 1024 | Higher quality |\n\nSee [Workers AI Models](https://developers.cloudflare.com/workers-ai/models/) for the full list.\n\n## Deployment\n\nAfter compiling with embeddings:\n\n1. **Create the queue:**\n ```bash\n wrangler queues create your-app-embeddings-queue\n ```\n\n2. **Deploy the worker:**\n ```bash\n wrangler deploy\n ```\n\nThe single worker handles both HTTP requests and queue consumption.\n\n## Monitoring\n\nQueue metrics are available in the Cloudflare dashboard:\n- Messages enqueued\n- Messages processed\n- Retry count\n- Consumer lag\n\nCheck queue health:\n```bash\nwrangler queues list\nwrangler queues consumer your-app-embeddings-queue\n```\n\n## Error Handling\n\nFailed jobs are automatically retried (up to `max_retries`):\n\n```typescript\n// In queue consumer\ntry {\n const embedding = await env.AI.run(job.model, { text: job.content });\n // ...\n message.ack();\n} catch (error) {\n console.error('[Queue] Embedding job failed:', error);\n message.retry(); // Will retry up to 3 times\n}\n```\n\nAfter max retries, the message is dead-lettered (if configured) or dropped.\n\n## Similarity Search Service\n\nFor applications that need typed similarity search with classification, you can define embedding search configurations using `defineEmbedding`. This generates a service layer with typed search functions.\n\n### Defining Search Configurations\n\nCreate a file in `services/embeddings/`:\n\n```typescript\n// services/embeddings/job-similarity.ts\n\nexport default defineEmbedding({\n name: 'job-similarity',\n description: 'Find similar job postings by description content',\n\n // Source configuration\n source: 'jobs', // Table name\n vectorIndex: 'VECTORIZE', // Binding name\n model: '@cf/baai/bge-base-en-v1.5',\n\n // Search configuration\n search: {\n threshold: 0.60, // Minimum similarity (default: 0.60)\n limit: 10, // Max results (default: 10)\n classify: {\n DUPLICATE_POSTING: 0.90, // Score >= 0.90 = DUPLICATE_POSTING\n SIMILAR_ROLE: 0.85, // Score >= 0.85 = SIMILAR_ROLE\n RELATED: 0.75, // Score >= 0.75 = RELATED\n },\n filters: ['department', 'organizationId'], // Filterable fields\n },\n\n // Generation triggers (beyond CRUD)\n triggers: {\n onQueueMessage: 'embed_job', // Listen for queue messages\n },\n});\n```\n\n### Generated Service Layer\n\nAfter compilation, a `createEmbeddings()` helper is generated in `src/lib/embeddings.ts`:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const embeddings = createEmbeddings(ctx.env);\n\n // Search with automatic classification\n const similar = await embeddings.jobSimilarity.search(\n 'Senior Full-Stack Engineer with React and Node.js experience',\n {\n department: 'engineering',\n limit: 5,\n threshold: 0.70,\n }\n );\n\n // Returns: [{ id, score: 0.87, classification: 'SIMILAR_ROLE', metadata }]\n for (const match of similar) {\n console.log(`${match.classification}: ${match.id} (${match.score})`);\n }\n\n return { similar };\n};\n```\n\n### Classification Thresholds\n\nResults are automatically classified based on similarity score:\n\n| Classification | Default Threshold | Meaning |\n|----------------|-------------------|---------|\n| `DUPLICATE_POSTING` | >= 0.90 | Near-identical job posting |\n| `SIMILAR_ROLE` | >= 0.85 | Strongly similar role and requirements |\n| `RELATED` | >= 0.75 | Topically related position |\n| `NEW` | < 0.75 | No significant match |\n\nCustomize thresholds per use case:\n\n```typescript\nsearch: {\n classify: {\n DUPLICATE_POSTING: 0.95, // Stricter duplicate detection\n SIMILAR_ROLE: 0.88,\n RELATED: 0.70, // Broader \"related\" category\n },\n}\n```\n\n### Gray Zone Detection\n\nFor cases where automatic classification isn't sufficient, use gray zone detection to get matches that need semantic evaluation:\n\n```typescript\nconst results = await embeddings.jobSimilarity.findWithGrayZone(\n 'Some job description text',\n { min: 0.60, max: 0.85 }\n);\n\n// Returns structured results:\n// {\n// high_confidence: [...], // Score >= 0.85 (auto-classified)\n// gray_zone: [...] // 0.60 <= score < 0.85 (needs review)\n// }\n\n// Process high confidence matches automatically\nfor (const match of results.high_confidence) {\n await markAsDuplicate(match.id);\n}\n\n// Queue gray zone for manual review\nfor (const match of results.gray_zone) {\n await queueForReview(match.id, match.score);\n}\n```\n\n### Generate Embeddings Directly\n\nGenerate embeddings without searching:\n\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Get raw embedding vector\nconst vector = await embeddings.jobSimilarity.embed(\n 'Text to embed'\n);\n// Returns: number[] (768 dimensions for bge-base)\n```\n\n### Multiple Search Configurations\n\nDefine different configurations for different use cases:\n\n```typescript\n// services/embeddings/candidate-similarity.ts\nexport default defineEmbedding({\n name: 'candidate-similarity',\n description: 'Match candidates by resume content',\n source: 'candidates',\n search: {\n threshold: 0.65,\n limit: 20,\n classify: {\n DUPLICATE_POSTING: 0.92,\n SIMILAR_ROLE: 0.80,\n RELATED: 0.65,\n },\n filters: ['source'],\n },\n});\n\n// services/embeddings/application-match.ts\nexport default defineEmbedding({\n name: 'application-match',\n description: 'Match applications to similar job postings',\n source: 'applications',\n search: {\n threshold: 0.70,\n limit: 5,\n classify: {\n DUPLICATE_POSTING: 0.95,\n SIMILAR_ROLE: 0.90,\n RELATED: 0.80,\n },\n filters: ['jobId', 'organizationId'],\n },\n});\n```\n\nUsage:\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Different search behaviors for different content types\nconst similarJobs = await embeddings.jobSimilarity.search(text, opts);\nconst similarCandidates = await embeddings.candidateSimilarity.search(text, opts);\nconst matchingApplications = await embeddings.applicationMatch.search(text, opts);\n```\n\n### Table-Level vs Service-Level\n\n| Feature | Table-level (`defineTable`) | Service-level (`defineEmbedding`) |\n|---------|----------------------------|----------------------------------|\n| Auto-embed on INSERT | ✅ | ❌ |\n| Auto-embed on UPDATE | ✅ | ❌ |\n| Custom search functions | ❌ | ✅ |\n| Classification thresholds | ❌ | ✅ |\n| Gray zone detection | ❌ | ✅ |\n| Filterable searches | ❌ | ✅ |\n| Queue message triggers | ❌ | ✅ |\n\n**Use both together:**\n- `defineTable` with `embeddings` config for automatic embedding generation\n- `defineEmbedding` for typed search functions with classification"
|
|
442
|
+
"content": "Quickback can automatically generate embeddings for your data using Cloudflare Queues and Workers AI. When configured, INSERT and UPDATE operations automatically enqueue embedding jobs that are processed asynchronously.\n\n## Enabling Embeddings\n\nAdd an `embeddings` configuration to your resource definition:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n embeddings: {\n fields: ['description'], // Fields to concatenate and embed\n model: '@cf/baai/bge-base-en-v1.5', // Embedding model (optional)\n onInsert: true, // Auto-embed on create (default: true)\n onUpdate: ['description'], // Re-embed when these fields change\n embeddingColumn: 'embedding', // Column to store embedding\n metadata: ['department'], // Metadata for Vectorize index\n },\n\n crud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } },\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `fields` | `string[]` | **Required** | Fields to concatenate and embed |\n| `model` | `string` | `'@cf/baai/bge-base-en-v1.5'` | Workers AI embedding model |\n| `onInsert` | `boolean` | `true` | Embed on INSERT operations |\n| `onUpdate` | `boolean \\| string[]` | `true` | Embed on UPDATE; array limits to specific fields |\n| `embeddingColumn` | `string` | `'embedding'` | Column to store the embedding vector |\n| `separator` | `string` | `' '` | Separator for joining multiple fields |\n| `metadata` | `string[]` | `[]` | Fields to include in Vectorize metadata |\n\n### onUpdate Options\n\n```typescript\n// Always re-embed on any update\nonUpdate: true\n\n// Never re-embed on update\nonUpdate: false\n\n// Only re-embed when specific fields change\nonUpdate: ['description', 'title']\n```\n\n## How It Works\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Main API Worker │\n│ │\n│ ┌─────────────────────┐ ┌────────────────────┐ │\n│ │ POST /jobs │ │ Queue Consumer │ │\n│ │ │ │ │ │\n│ │ 1. Auth middleware │ │ 1. Workers AI │ │\n│ │ 2. Firewall │ │ embed() │ │\n│ │ 3. Guards │ │ 2. D1 update() │ │\n│ │ 4. Insert to D1 │ │ 3. Vectorize │ │\n│ │ 5. Enqueue job ─────┼───▶│ upsert() │ │\n│ └─────────────────────┘ └────────────────────┘ │\n│ ▲ │\n│ ┌─────────────────┴──────────────────┐ │\n│ │ EMBEDDINGS_QUEUE │ │\n│ └────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n1. **API Request** - POST/PATCH arrives and passes through auth, firewall, guards\n2. **Database Insert** - Record is created/updated in D1\n3. **Enqueue Job** - Embedding job is sent to Cloudflare Queue\n4. **Queue Consumer** - Processes job asynchronously:\n - Calls Workers AI to generate embedding\n - Updates D1 with embedding vector\n - Optionally upserts to Vectorize index\n\n## Security Model\n\n**Security is enforced at enqueue time, not consume time:**\n\n- Jobs are only enqueued after passing all security checks (auth, firewall, guards)\n- The queue consumer is an internal process that executes pre-validated jobs\n- If a user can't create a job posting, they can't trigger an embedding job\n\n## Generic Embeddings API\n\nIn addition to automatic embeddings on CRUD operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.\n\n### POST /api/v1/embeddings\n\nGenerate an embedding for any text content:\n\n```bash\ncurl -X POST https://your-api.workers.dev/api/v1/embeddings \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -d '{\n \"content\": \"Text to embed\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\",\n \"table\": \"jobs\",\n \"id\": \"job_123\"\n }'\n```\n\n#### Request Body\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `content` | `string` | Yes | Text to generate embedding for |\n| `model` | `string` | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |\n| `table` | `string` | No | Table to store embedding back to |\n| `id` | `string` | Conditional | Record ID to update (required if `table` is specified) |\n\n#### Response\n\n```json\n{\n \"queued\": true,\n \"jobId\": \"550e8400-e29b-41d4-a716-446655440000\",\n \"table\": \"jobs\",\n \"id\": \"job_123\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n}\n```\n\n### GET /api/v1/embeddings/tables\n\nList tables that have embeddings configured:\n\n```bash\ncurl https://your-api.workers.dev/api/v1/embeddings/tables \\\n -H \"Cookie: better-auth.session_token=...\"\n```\n\nResponse:\n\n```json\n{\n \"tables\": [\n {\n \"name\": \"jobs\",\n \"embeddingColumn\": \"embedding\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n }\n ]\n}\n```\n\n### Authentication & Authorization\n\nThe generic embeddings API requires authentication and uses the `activeOrgId` from the user's context to enforce organization-level isolation. Embedding jobs are scoped to the user's current organization.\n\n### Use Cases\n\nThe generic embeddings API is useful for:\n\n- **Batch embedding**: Embed content without going through CRUD routes\n- **Re-embedding**: Force re-generation of embeddings for existing records\n- **Preview embeddings**: Test embedding generation before persisting\n- **External content**: Embed content that doesn't fit your defined schemas\n\n## Generated Files\n\nWhen embeddings are configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/queue-consumer.ts` | Queue consumer handler for processing embedding jobs |\n| `src/routes/embeddings.ts` | Generic embeddings API routes |\n| `wrangler.toml` | Queue producer/consumer bindings, AI binding |\n| `src/env.d.ts` | `EMBEDDINGS_QUEUE`, `AI` types |\n| `src/index.ts` | Exports `queue` handler, mounts `/api/v1/embeddings` |\n\n### wrangler.toml additions\n\n```toml\n# Embeddings Queue\n[[queues.producers]]\nqueue = \"your-app-embeddings-queue\"\nbinding = \"EMBEDDINGS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"your-app-embeddings-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n# Workers AI\n[ai]\nbinding = \"AI\"\n```\n\n## Multiple Fields\n\nEmbed multiple fields by concatenating them:\n\n```typescript\nembeddings: {\n fields: ['title', 'description', 'department'], // Joined with spaces by default\n // ...\n}\n```\n\nGenerated embedding text: `\"${title} ${description} ${department}\"`\n\n### Custom Separator\n\nUse `separator` to control how fields are joined. This is useful for sentence boundary detection:\n\n```typescript\nembeddings: {\n fields: ['title', 'description'],\n separator: '. ', // Join with period + space\n // ...\n}\n```\n\nGenerated code: `[result[0].title, result[0].description].filter(Boolean).join('. ')`\n\nThe `filter(Boolean)` ensures null or empty fields are excluded cleanly — no trailing separator when a field is absent.\n\n## Vectorize Integration\n\nIf you have a Vectorize index configured, embeddings are automatically upserted:\n\n```typescript\n// quickback.config.ts\nproviders: {\n database: {\n config: {\n vectorizeIndexName: 'jobs-embeddings', // Your Vectorize index\n vectorizeBinding: 'VECTORIZE',\n },\n },\n},\n```\n\nThe queue consumer will:\n1. Generate the embedding via Workers AI\n2. Store the vector in D1 (JSON string)\n3. Upsert to Vectorize with metadata\n\n### Vectorize Metadata\n\nInclude fields in Vectorize metadata for filtering:\n\n```typescript\nembeddings: {\n fields: ['description'],\n metadata: ['department', 'organizationId', 'status'],\n}\n```\n\nEnables queries like:\n```typescript\nconst results = await env.VECTORIZE.query(vector, {\n topK: 10,\n filter: { department: 'engineering' }\n});\n```\n\n## Schema Requirements\n\nYour schema must include the embedding column:\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 description: q.text().required(),\n department: q.text().optional(),\n status: q.text().required(),\n organizationId: q.scope(\"organization\"),\n\n // Embedding column — stores JSON array of floats\n embedding: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n crud: { list: {}, get: {}, create: {}, update: {}, delete: {} },\n});\n```\n\n## Supported Models\n\nAny Workers AI embedding model can be used:\n\n| Model | Dimensions | Notes |\n|-------|------------|-------|\n| `@cf/baai/bge-base-en-v1.5` | 768 | Default, good general-purpose |\n| `@cf/baai/bge-small-en-v1.5` | 384 | Faster, smaller |\n| `@cf/baai/bge-large-en-v1.5` | 1024 | Higher quality |\n\nSee [Workers AI Models](https://developers.cloudflare.com/workers-ai/models/) for the full list.\n\n## Deployment\n\nAfter compiling with embeddings:\n\n1. **Create the queue:**\n ```bash\n wrangler queues create your-app-embeddings-queue\n ```\n\n2. **Deploy the worker:**\n ```bash\n wrangler deploy\n ```\n\nThe single worker handles both HTTP requests and queue consumption.\n\n## Monitoring\n\nQueue metrics are available in the Cloudflare dashboard:\n- Messages enqueued\n- Messages processed\n- Retry count\n- Consumer lag\n\nCheck queue health:\n```bash\nwrangler queues list\nwrangler queues consumer your-app-embeddings-queue\n```\n\n## Error Handling\n\nFailed jobs are automatically retried (up to `max_retries`):\n\n```typescript\n// In queue consumer\ntry {\n const embedding = await env.AI.run(job.model, { text: job.content });\n // ...\n message.ack();\n} catch (error) {\n console.error('[Queue] Embedding job failed:', error);\n message.retry(); // Will retry up to 3 times\n}\n```\n\nAfter max retries, the message is dead-lettered (if configured) or dropped.\n\n## Similarity Search Service\n\nFor applications that need typed similarity search with classification, you can define embedding search configurations using `defineEmbedding`. This generates a service layer with typed search functions.\n\n### Defining Search Configurations\n\nCreate a file in `services/embeddings/`:\n\n```typescript\n// services/embeddings/job-similarity.ts\n\nexport default defineEmbedding({\n name: 'job-similarity',\n description: 'Find similar job postings by description content',\n\n // Source configuration\n source: 'jobs', // Table name\n vectorIndex: 'VECTORIZE', // Binding name\n model: '@cf/baai/bge-base-en-v1.5',\n\n // Search configuration\n search: {\n threshold: 0.60, // Minimum similarity (default: 0.60)\n limit: 10, // Max results (default: 10)\n classify: {\n DUPLICATE_POSTING: 0.90, // Score >= 0.90 = DUPLICATE_POSTING\n SIMILAR_ROLE: 0.85, // Score >= 0.85 = SIMILAR_ROLE\n RELATED: 0.75, // Score >= 0.75 = RELATED\n },\n filters: ['department', 'organizationId'], // Filterable fields\n },\n\n // Generation triggers (beyond CRUD)\n triggers: {\n onQueueMessage: 'embed_job', // Listen for queue messages\n },\n});\n```\n\n### Generated Service Layer\n\nAfter compilation, a `createEmbeddings()` helper is generated in `src/lib/embeddings.ts`:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const embeddings = createEmbeddings(ctx.env);\n\n // Search with automatic classification\n const similar = await embeddings.jobSimilarity.search(\n 'Senior Full-Stack Engineer with React and Node.js experience',\n {\n department: 'engineering',\n limit: 5,\n threshold: 0.70,\n }\n );\n\n // Returns: [{ id, score: 0.87, classification: 'SIMILAR_ROLE', metadata }]\n for (const match of similar) {\n console.log(`${match.classification}: ${match.id} (${match.score})`);\n }\n\n return { similar };\n};\n```\n\n### Classification Thresholds\n\nResults are automatically classified based on similarity score:\n\n| Classification | Default Threshold | Meaning |\n|----------------|-------------------|---------|\n| `DUPLICATE_POSTING` | >= 0.90 | Near-identical job posting |\n| `SIMILAR_ROLE` | >= 0.85 | Strongly similar role and requirements |\n| `RELATED` | >= 0.75 | Topically related position |\n| `NEW` | < 0.75 | No significant match |\n\nCustomize thresholds per use case:\n\n```typescript\nsearch: {\n classify: {\n DUPLICATE_POSTING: 0.95, // Stricter duplicate detection\n SIMILAR_ROLE: 0.88,\n RELATED: 0.70, // Broader \"related\" category\n },\n}\n```\n\n### Gray Zone Detection\n\nFor cases where automatic classification isn't sufficient, use gray zone detection to get matches that need semantic evaluation:\n\n```typescript\nconst results = await embeddings.jobSimilarity.findWithGrayZone(\n 'Some job description text',\n { min: 0.60, max: 0.85 }\n);\n\n// Returns structured results:\n// {\n// high_confidence: [...], // Score >= 0.85 (auto-classified)\n// gray_zone: [...] // 0.60 <= score < 0.85 (needs review)\n// }\n\n// Process high confidence matches automatically\nfor (const match of results.high_confidence) {\n await markAsDuplicate(match.id);\n}\n\n// Queue gray zone for manual review\nfor (const match of results.gray_zone) {\n await queueForReview(match.id, match.score);\n}\n```\n\n### Generate Embeddings Directly\n\nGenerate embeddings without searching:\n\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Get raw embedding vector\nconst vector = await embeddings.jobSimilarity.embed(\n 'Text to embed'\n);\n// Returns: number[] (768 dimensions for bge-base)\n```\n\n### Multiple Search Configurations\n\nDefine different configurations for different use cases:\n\n```typescript\n// services/embeddings/candidate-similarity.ts\nexport default defineEmbedding({\n name: 'candidate-similarity',\n description: 'Match candidates by resume content',\n source: 'candidates',\n search: {\n threshold: 0.65,\n limit: 20,\n classify: {\n DUPLICATE_POSTING: 0.92,\n SIMILAR_ROLE: 0.80,\n RELATED: 0.65,\n },\n filters: ['source'],\n },\n});\n\n// services/embeddings/application-match.ts\nexport default defineEmbedding({\n name: 'application-match',\n description: 'Match applications to similar job postings',\n source: 'applications',\n search: {\n threshold: 0.70,\n limit: 5,\n classify: {\n DUPLICATE_POSTING: 0.95,\n SIMILAR_ROLE: 0.90,\n RELATED: 0.80,\n },\n filters: ['jobId', 'organizationId'],\n },\n});\n```\n\nUsage:\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Different search behaviors for different content types\nconst similarJobs = await embeddings.jobSimilarity.search(text, opts);\nconst similarCandidates = await embeddings.candidateSimilarity.search(text, opts);\nconst matchingApplications = await embeddings.applicationMatch.search(text, opts);\n```\n\n### Table-Level vs Service-Level\n\n| Feature | Table-level (`defineTable`) | Service-level (`defineEmbedding`) |\n|---------|----------------------------|----------------------------------|\n| Auto-embed on INSERT | ✅ | ❌ |\n| Auto-embed on UPDATE | ✅ | ❌ |\n| Custom search functions | ❌ | ✅ |\n| Classification thresholds | ❌ | ✅ |\n| Gray zone detection | ❌ | ✅ |\n| Filterable searches | ❌ | ✅ |\n| Queue message triggers | ❌ | ✅ |\n\n**Use both together:**\n- `defineTable` with `embeddings` config for automatic embedding generation\n- `defineEmbedding` for typed search functions with classification"
|
|
439
443
|
},
|
|
440
444
|
"stack/vector": {
|
|
441
445
|
"title": "Vector & AI",
|
|
@@ -510,6 +514,7 @@ export const TOPIC_LIST = [
|
|
|
510
514
|
"compiler/definitions/guards",
|
|
511
515
|
"compiler/definitions",
|
|
512
516
|
"compiler/definitions/masking",
|
|
517
|
+
"compiler/definitions/read",
|
|
513
518
|
"compiler/definitions/schema",
|
|
514
519
|
"compiler/definitions/validation",
|
|
515
520
|
"compiler/definitions/views",
|