@quickback-dev/cli 0.10.5 → 0.10.8
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/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +8 -1
- package/dist/commands/compile.js.map +1 -1
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +245 -230
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/api-client.d.ts +6 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/file-loader.d.ts +13 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +54 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/skill/SKILL.md +49 -6
- package/package.json +14 -14
- package/src/skill/SKILL.md +48 -5
package/dist/docs/content.js
CHANGED
|
@@ -1,121 +1,13 @@
|
|
|
1
1
|
// AUTO-GENERATED - DO NOT EDIT
|
|
2
2
|
// Generated by scripts/bundle-docs.ts from marketing/docs
|
|
3
3
|
export const DOCS = {
|
|
4
|
-
"account-ui/customization": {
|
|
5
|
-
"title": "Customization",
|
|
6
|
-
"content": "# Customization\n\nCustomize the Account UI to match your brand and messaging.\n\n**Standalone (template):** Configure via environment variables, edit `src/config/app.ts` directly, or use `setAppConfig()` for runtime overrides.\n\n**Library (npm):** Configure entirely via `setAppConfig()`. Import it from `quickback-better-auth-account-ui` instead of `@/config/app`.\n\n## Branding\n\n### App Identity\n\nSet your application's name and description:\n\n```bash\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\n```\n\nThese values appear in:\n- Page titles (`<title>Acme SaaS | Login</title>`)\n- Meta descriptions\n- UI headers and footers\n- Email templates\n\n### Visual Identity\n\n```bash\n# Primary theme color (used for buttons, links, accents)\nVITE_THEME_COLOR=#3b82f6\n\n# Company name (shown in footer, legal pages)\nVITE_COMPANY_NAME=Acme Corporation\n\n# Company address (shown in footer, receipts)\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n### Logo and Favicon\n\nPlace your branding assets in the `public/` directory:\n\n```\npublic/\n├── logo.png # Main logo (shown in header)\n├── favicon.ico # Browser favicon\n└── og-image.png # Social media preview image\n```\n\nThen update the paths in `src/config/app.ts`:\n\n```ts title=\"src/config/app.ts\"\nbranding: {\n primaryColor: \"#1e293b\",\n logoUrl: \"/logo.png\",\n faviconUrl: \"/favicon.ico\"\n},\n```\n\nOr set them at runtime in `src/main.tsx`:\n\n```ts\n\nsetAppConfig({\n branding: {\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n## Custom Labels\n\nOverride default UI labels using runtime configuration:\n\n```ts\n\nsetAppConfig({\n labels: {\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n company: 'My Company',\n organizations: 'Workspaces', // Rename \"Organizations\" to \"Workspaces\"\n },\n});\n```\n\n### Available Labels\n\n| Label | Default | Usage |\n|-------|---------|-------|\n| `terms` | \"Terms of Service\" | Footer link text |\n| `privacy` | \"Privacy Policy\" | Footer link text |\n| `support` | \"Contact Support\" | Footer link text |\n| `company` | (from `VITE_COMPANY_NAME`) | Footer company name |\n| `organizations` | \"Organizations\" | Navigation and page titles |\n\n## Custom Messages\n\nCustomize user-facing messages:\n\n```ts\n\nsetAppConfig({\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n contactAdminForInvite: \"Contact your team lead to get access.\",\n noPendingInvitations: \"No pending invites at this time\",\n createOrganization: \"Create Workspace\",\n // ... more messages\n },\n});\n```\n\n### Available Messages\n\n| Message | Default | Usage |\n|---------|---------|-------|\n| `noOrganizations` | \"You're not a member of any organizations yet.\" | Empty organizations list |\n| `contactAdminForInvite` | \"Contact an admin to be invited to an organization.\" | Organizations page help text |\n| `noPendingInvitations` | \"You have no pending invitations\" | Empty invitations list |\n| `createOrganization` | \"Create Organization\" | Button text |\n| `accountInformation` | \"Account Information\" | Profile section header |\n| `timezone` | \"Timezone\" | Label for timezone field |\n| `serverLocation` | \"Server Location\" | Label for server location |\n| `memberSince` | \"Member since\" | Account age label |\n| `pendingInvitations` | \"Pending Invitations\" | Section header |\n| `invitedAs` | \"Invited as\" | Invitation role label |\n| `accept` | \"Accept\" | Accept invitation button |\n| `decline` | \"Decline\" | Decline invitation button |\n| `userFallback` | \"User\" | Fallback for missing name |\n| `noEmailProvided` | \"No email provided\" | Fallback for missing email |\n| `more` | \"More\" | Pagination/load more text |\n| `total` | \"total\" | Total count label |\n| `active` | \"Active\" | Active status label |\n| `new` | \"New\" | New item label |\n\n## Route Customization\n\nCustomize route paths using runtime configuration:\n\n```ts\n\nsetAppConfig({\n routes: {\n public: {\n home: '/',\n login: '/sign-in', // Change from /login\n signup: '/sign-up', // Change from /signup\n forgotPassword: '/reset-password',\n welcome: '/getting-started',\n },\n authenticated: {\n dashboard: '/dashboard',\n profile: '/my-account',\n settings: '/preferences',\n },\n organizations: {\n list: '/workspaces', // Rename route\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n});\n```\n\n## Password Requirements\n\nCustomize password validation rules:\n\n```ts\n\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12, // Minimum password length\n maxLength: 128, // Maximum password length\n requireUppercase: true, // Must have uppercase letter\n requireLowercase: true, // Must have lowercase letter\n requireNumbers: true, // Must have number\n requireSymbols: true, // Must have special character\n },\n },\n});\n```\n\nPassword requirements are displayed to users during signup and password changes.\n\n## Session Duration\n\nControl how long users stay logged in:\n\n```ts\n\nsetAppConfig({\n auth: {\n sessionDuration: 7 * 24 * 60 * 60, // 7 days in seconds\n },\n});\n```\n\n## Email Customization\n\nConfigure email sender information:\n\n```bash\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=help@acme.com\n```\n\nThe `fromName` is automatically set to `VITE_APP_NAME`:\n\n```ts\n// Emails will show:\n// From: \"Acme SaaS <noreply@acme.com>\"\n```\n\n## URL Configuration\n\nConfigure URLs for external links:\n\n```bash\n# Main application (redirected to after login)\nVITE_QUICKBACK_APP_URL=https://app.acme.com\n\n# Organization/tenant URL pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}\n\n# Support pages\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/legal/privacy\nVITE_TERMS_URL=https://acme.com/legal/terms\n```\n\n### Tenant URL Patterns\n\nThe tenant URL pattern supports flexible organization routing:\n\n```bash\n# Path-based routing\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n# Result: https://app.acme.com/organizations/acme-corp\n\n# Subdomain routing\nVITE_TENANT_URL_PATTERN=https://{slug}.acme.com\n# Result: https://acme-corp.acme.com\n\n# Custom pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}/dashboard\n# Result: https://app.acme.com/workspace/acme-corp/dashboard\n```\n\n## Complete Customization Example\n\nHere's a complete example showing all customization options:\n\n```ts title=\"src/main.tsx\"\n\n// Apply customizations before rendering\nsetAppConfig({\n name: 'Acme SaaS',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/acme-logo.png',\n faviconUrl: '/favicon.ico',\n },\n\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n },\n\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n contactAdminForInvite: 'Contact your team lead for access.',\n },\n\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n\n// Render app\n\nconst root = document.getElementById('root')!;\ncreateRoot(root).render(\n \n);\n```\n\n## Custom Styles\n\nOverride default styles with custom CSS:\n\n```css title=\"custom-styles.css\"\n/* Override primary color */\n:root {\n --primary: 59 130 246; /* Tailwind blue-500 */\n --primary-foreground: 255 255 255;\n}\n\n/* Custom logo size */\n.logo {\n width: 180px;\n height: auto;\n}\n\n/* Custom button styles */\n.btn-primary {\n background-color: var(--primary);\n border-radius: 8px;\n font-weight: 600;\n}\n```\n\nImport your custom CSS after the Account UI styles:\n\n```ts\n\n```\n\n## Next Steps\n\n- **[Worker Setup](/account-ui/worker)** - Deploy your customized UI\n- **[Environment Variables](/account-ui/environment-variables)** - Complete configuration reference\n- **[Feature Flags](/account-ui/features)** - Enable/disable features"
|
|
7
|
-
},
|
|
8
|
-
"account-ui/environment-variables": {
|
|
9
|
-
"title": "Environment Variables",
|
|
10
|
-
"content": "# Environment Variables\n\nConfigure the Account UI by setting environment variables in your `.env` file or deployment platform.\n\n## Quick Setup — Single Variable\n\nFor the common \"unified deployment\" where API, Account, and CMS all live on the same Quickback origin, you only need **one** variable:\n\n```bash\n# Points at the Quickback Worker origin\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen `VITE_QUICKBACK_URL` is set, it's used as a fallback for the individual URL vars:\n\n| Individual var | Used first | Falls back to |\n|---|---|---|\n| `VITE_QUICKBACK_API_URL` | if set | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | if set | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | if set | `${VITE_QUICKBACK_URL}/cms` |\n\n## Required Variables\n\nAt minimum, you need one of:\n\n- **`VITE_QUICKBACK_URL`** — catch-all for the Quickback origin (recommended), **or**\n- **`VITE_QUICKBACK_API_URL`** — explicit API URL (use this if your API lives on a different subdomain from Account/CMS)\n\n### Split-subdomain setup\n\nIf your API, Account, and CMS live on separate custom subdomains, set them explicitly:\n\n```bash\n# Quickback API URL\nVITE_QUICKBACK_API_URL=https://api.example.com\n\n# Account UI URL (where the Account UI is deployed)\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# Optional: override Account/CMS URLs for cross-origin links\nVITE_QUICKBACK_ACCOUNT_URL=https://auth.example.com\nVITE_QUICKBACK_CMS_URL=https://cms.example.com\n```\n\n## App Identity\n\nConfigure your application's basic information:\n\n```bash\n# App name (displayed in UI)\nVITE_APP_NAME=My Application\n\n# Tagline (shown on landing pages)\nVITE_APP_TAGLINE=Build faster, ship sooner\n\n# Full description\nVITE_APP_DESCRIPTION=A complete platform for building modern web applications\n\n# Company information\nVITE_COMPANY_NAME=My Company Inc.\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n## URLs\n\n### Main Application\n\n```bash\n# Your main application URL\n# Users will be redirected here after authentication\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Organization/Tenant URL pattern (optional)\n# Use {slug} as placeholder for organization identifier\n# Examples:\n# /organizations/{slug} -> app.example.com/organizations/acme\n# /workspace/{slug} -> app.example.com/workspace/acme\n# https://{slug}.example.com -> acme.example.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n```\n\n### Support and Legal\n\n```bash\n# Support/help URL\nVITE_SUPPORT_URL=https://support.example.com\n\n# Privacy policy URL\nVITE_PRIVACY_URL=https://example.com/privacy\n\n# Terms of service URL\nVITE_TERMS_URL=https://example.com/terms\n```\n\n## Email Configuration\n\n```bash\n# From address for all emails\nVITE_EMAIL_FROM=noreply@example.com\n\n# Reply-to address\nVITE_EMAIL_REPLY_TO=support@example.com\n\n# Support email address\nVITE_SUPPORT_EMAIL=support@example.com\n\n# AWS Region for SES (if using AWS SES)\nVITE_EMAIL_REGION=us-east-1\n```\n\n## Branding\n\n```bash\n# Primary theme color (hex code)\nVITE_THEME_COLOR=#1e293b\n\n# SEO keywords (comma-separated)\nVITE_SEO_KEYWORDS=saas,authentication,account management\n```\n\n## Feature Flags\n\nEnable or disable features using boolean environment variables:\n\n### Authentication Features\n\n```bash\n# Enable user signup (default: true)\nENABLE_SIGNUP=true\n\n# Enable email verification after signup (default: true)\nENABLE_EMAIL_VERIFICATION=true\n\n# Disable email deliverability checks (default: false)\n# Set to true to skip checking if email addresses are deliverable\nDISABLE_EMAIL_STATUS_CHECK=false\n\n# Enable passkey (WebAuthn) login (default: true)\nENABLE_PASSKEY=true\n\n# Enable email OTP login and signup (default: true)\nENABLE_EMAIL_OTP=true\n\n# Enable email+password login and signup (default: false)\nENABLE_PASSWORD=false\n```\n\n### Account Management Features\n\n```bash\n# Enable file uploads (avatar, etc.) (default: false)\nVITE_ENABLE_FILE_UPLOADS=false\n```\n\n### Organization Features\n\n```bash\n# Enable multi-tenant organizations (default: true)\nENABLE_ORGANIZATIONS=true\n```\n\n### Admin Features\n\n```bash\n# Enable admin panel (default: true)\nENABLE_ADMIN=true\n```\n\n## Complete Example\n\nHere's a complete `.env` file with all common configuration:\n\n```bash title=\".env\"\n# ===== REQUIRED =====\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# ===== APP IDENTITY =====\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\nVITE_COMPANY_NAME=Acme Corporation\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n\n# ===== URLS =====\nVITE_QUICKBACK_APP_URL=https://app.acme.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/privacy\nVITE_TERMS_URL=https://acme.com/terms\n\n# ===== EMAIL =====\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=support@acme.com\nVITE_EMAIL_REGION=us-east-1\n\n# ===== BRANDING =====\nVITE_THEME_COLOR=#3b82f6\n\n# ===== SEO =====\nVITE_SEO_KEYWORDS=saas,project management,team collaboration\n\n# ===== FEATURES =====\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Environment-Specific Configuration\n\n### Development\n\n```bash title=\".env.development\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\nVITE_QUICKBACK_APP_URL=http://localhost:3000\nDISABLE_EMAIL_STATUS_CHECK=true\n```\n\n### Staging\n\n```bash title=\".env.staging\"\nVITE_QUICKBACK_API_URL=https://api-staging.example.com\nVITE_ACCOUNT_APP_URL=https://account-staging.example.com\nVITE_QUICKBACK_APP_URL=https://app-staging.example.com\n```\n\n### Production\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Cloudflare Pages Setup\n\nWhen deploying to Cloudflare Pages, set environment variables in the dashboard:\n\n1. Go to **Settings** → **Environment Variables**\n2. Add each `VITE_*` variable\n3. Separate values for **Production** and **Preview** branches\n\n## Wrangler Configuration\n\nFor `wrangler dev` and `wrangler deploy`, add variables to `wrangler.toml`:\n\n```toml title=\"wrangler.toml\"\n[env.production.vars]\nVITE_QUICKBACK_API_URL = \"https://api.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\nVITE_APP_NAME = \"My App\"\n# ... other variables\n```\n\nOr use `.dev.vars` for local development (git-ignored):\n\n```bash title=\".dev.vars\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\n```\n\n## Runtime Configuration\n\nSome values can be overridden at runtime using the config API:\n\n```ts\n\nsetAppConfig({\n name: 'My Custom App',\n branding: {\n primaryColor: '#ff6600',\n logoUrl: '/custom-logo.png',\n },\n urls: {\n base: 'https://account.custom.com',\n app: 'https://app.custom.com',\n },\n});\n```\n\n## Validation\n\nThe Account UI validates configuration on startup:\n\n- **Missing VITE_QUICKBACK_API_URL**: Throws error\n- **Invalid URLs**: Logs warning\n- **Missing optional fields**: Uses defaults\n\nCheck the browser console for configuration warnings.\n\n## Next Steps\n\n- **[Feature Flags](/account-ui/features)** - Detailed feature configuration\n- **[Customization](/account-ui/customization)** - Customize labels and messages\n- **[Worker Setup](/account-ui/worker)** - Deploy to Cloudflare"
|
|
11
|
-
},
|
|
12
|
-
"account-ui/features/admin": {
|
|
13
|
-
"title": "Admin Panel",
|
|
14
|
-
"content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin API:\n\n```bash\ncurl -X POST https://api.example.com/admin/v1/set-role \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"userId\": \"user_123\", \"role\": \"admin\" }'\n```\n\n## Custom Admin Domain\n\nGive the admin panel its own subdomain with `adminDomain`:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n auth: { password: true, admin: true },\n},\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n],\n```\n\nThe admin domain serves the same Account SPA at root (`/`). The SPA's client-side router handles showing the admin page at `admin.example.com/admin`. Authentication cookies are shared across subdomains automatically via [cross-subdomain cookie configuration](/compiler/config/domains#cross-subdomain-authentication).\n\n## CMS Access Control\n\nWhen both CMS and Account UI are enabled, the admin panel's profile page shows a \"Go to CMS\" button. You can restrict this to admin users only:\n\n```typescript\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\nWith `access: \"admin\"`, non-admin users can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to admins. See [CMS Connecting](/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.\n\n## Related\n\n- [Configuration](/compiler/config) — `auth.admin` and `adminDomain` options\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Access Control](/compiler/definitions/access) — Role-based permissions in your API"
|
|
15
|
-
},
|
|
16
|
-
"account-ui/features/api-keys": {
|
|
17
|
-
"title": "API Key Management",
|
|
18
|
-
"content": "Account UI provides an API key management interface for users to create, view, and revoke API keys.\n\n## Creating API Keys\n\nUsers can create API keys with:\n\n- Custom name/description\n- Optional expiration date\n- Scoped to the current organization\n\n## Managing Keys\n\n- View all active API keys\n- See last-used timestamp\n- Revoke individual keys\n\n## Related\n\n- [API Keys Auth](/stack/auth/api-keys) — Server-side API key authentication\n- [Environment Variables](/account-ui/environment-variables)"
|
|
19
|
-
},
|
|
20
|
-
"account-ui/features/avatars": {
|
|
21
|
-
"title": "Avatars",
|
|
22
|
-
"content": "When file uploads are enabled, Account UI provides avatar upload functionality.\n\n## Enabling\n\nIn `quickback.config.ts`:\n\n```ts\naccount: {\n fileUploads: true,\n // ...\n}\n```\n\nThe compiler emits `VITE_ENABLE_FILE_UPLOADS=true` into the Account SPA's\nbuild env. For standalone Account UI deployments (built outside the\ncompiler), set `VITE_ENABLE_FILE_UPLOADS=true` in `.env` directly.\n\n## Upload Flow\n\n1. User clicks their profile picture\n2. Image picker opens (supports JPG, PNG, WebP)\n3. Image is cropped to square\n4. Uploaded to R2/S3 storage\n5. Profile updated with new avatar URL\n\n## Requirements\n\n- `account.fileUploads: true` (or `VITE_ENABLE_FILE_UPLOADS=true` for standalone)\n- R2 bucket or S3-compatible storage configured\n- Upload endpoints available in your API\n\n## Related\n\n- [R2 Storage](/stack/storage/r2) — File storage setup\n- [Environment Variables](/account-ui/environment-variables)"
|
|
23
|
-
},
|
|
24
|
-
"account-ui/features/cli-authorize": {
|
|
25
|
-
"title": "CLI Authorization",
|
|
26
|
-
"content": "Account UI includes a device authorization page that allows users to approve CLI login requests.\n\n## How It Works\n\n1. User runs `quickback login` in the CLI\n2. CLI displays a URL and user code\n3. User opens the URL in their browser\n4. Account UI shows the authorization page with the device code\n5. User confirms the code matches and approves\n6. CLI receives the authentication token\n\n## Configuration\n\nThe CLI authorization page is always available when the Account UI is deployed. No additional configuration is needed.\n\n## Related\n\n- [Device Auth](/stack/auth/device-auth) — Server-side device auth flow\n- [CLI Reference](/compiler/cloud-compiler/cli) — CLI commands"
|
|
27
|
-
},
|
|
28
|
-
"account-ui/features": {
|
|
29
|
-
"title": "Feature Flags",
|
|
30
|
-
"content": "# Feature Flags\n\nControl which features are available in your Account UI deployment using feature flags. All features are configured via environment variables.\n\n## Authentication Features\n\n### User Signup\n\n```bash\nENABLE_SIGNUP=true # default: true\n```\n\nControls whether new users can register. Wired to the `ENABLE_SIGNUP` env var.\n\n**When enabled:**\n- Shows \"Sign Up\" link on login page\n- `/signup` route is accessible\n- New users can create accounts\n\n**When disabled:**\n- Signup route returns 404\n- Only existing users can log in\n- Useful for invite-only applications\n\n### Email Verification\n\n```bash\nENABLE_EMAIL_VERIFICATION=true # default: true\n```\n\nControls the email verification flow. Wired to the frontend via the `ENABLE_EMAIL_VERIFICATION` env var.\n\n**When enabled:**\n- Users must verify email before full access\n- Verification email sent on signup\n- \"Resend verification email\" option available\n- Unverified users see verification prompt\n\n**When disabled:**\n- Email addresses are trusted without verification\n- Users have immediate access after signup\n\n### Email Deliverability Check\n\n```bash\nDISABLE_EMAIL_STATUS_CHECK=false # default: false\n```\n\n**When `false` (checking enabled):**\n- System validates email addresses are deliverable\n- Rejects disposable/temporary email providers\n- Prevents typos in domain names\n\n**When `true` (checking disabled):**\n- Accepts all email formats\n- Useful for development/testing\n- Allows `@test.com`, `@localhost`, etc.\n\n### Passkey Login\n\n```bash\nENABLE_PASSKEY=true # default: true\n```\n\nControls passkey LOGIN only (not signup). When enabled, users can authenticate using passkeys.\n\n**When enabled:**\n- Users can register passkeys (fingerprint, Face ID, hardware keys)\n- Passwordless login option\n- \"Manage Passkeys\" page available\n\n**When disabled:**\n- No passkey registration\n- No passkey login option\n\n**Requirements:**\n- HTTPS (passkeys require secure context)\n- Modern browser with WebAuthn support\n\n### Email OTP\n\n```bash\nENABLE_EMAIL_OTP=true # default: true\n```\n\n**When enabled:**\n- Users can receive one-time passwords via email\n- Alternative to password login\n- `/email-otp` route available\n\n**When disabled:**\n- No email OTP option\n- Password or passkey required\n\n### Password Authentication\n\n```bash\nENABLE_PASSWORD=false # default: false\n```\n\n**When enabled:**\n- Email + password fields on login page\n- Password field on signup page\n- Traditional username/password authentication\n\n**When disabled:**\n- No password fields shown\n- Users authenticate via email OTP or passkey\n\n## Account Management Features\n\n### File Uploads\n\n```bash\nVITE_ENABLE_FILE_UPLOADS=false # default: false\n```\n\n**When enabled:**\n- Avatar/profile picture upload\n- Image cropping and editing\n- File upload to R2/S3\n\n**When disabled:**\n- No file upload functionality\n- Users can only use default avatars\n\n**Requirements:**\n- R2 bucket or S3 configured\n- Upload endpoints in your API\n\n## Organization Features\n\n### Organizations (Multi-Tenancy)\n\n```bash\nENABLE_ORGANIZATIONS=true # default: true\n```\n\n**When enabled:**\n- Users can create organizations\n- Organization management pages\n- Member invitations and roles\n- `/organizations/*` routes\n\n**When disabled:**\n- Single-user mode only\n- No organization features\n- Simpler user experience\n\n**Includes:**\n- Organization creation and deletion\n- Member management (owner, admin, member roles)\n- Invitation system\n- Organization settings\n\n## Admin Features\n\n### Admin Panel\n\n```bash\nENABLE_ADMIN=true # default: true\n```\n\n**When enabled:**\n- `/admin` route accessible to admin users\n- User management dashboard\n- Subscription management\n- Admin-only features:\n - Create users manually\n - Ban/unban users\n - Reset user passwords\n - View all sessions\n - Manage subscriptions\n\n**When disabled:**\n- No admin panel\n- Admin must use database directly\n\n**Requirements:**\n- User must have admin role in database\n\n## Feature Combinations\n\n### Minimal Configuration (Password-Only)\n\n```bash\nENABLE_PASSKEY=false\nENABLE_EMAIL_OTP=false\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=false\nENABLE_ADMIN=false\n```\n\nSimple email/password authentication for single-tenant apps.\n\n### Maximum Security\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_EMAIL_VERIFICATION=true\n```\n\nAll authentication methods with email verification and deliverability checks.\n\n### Multi-Tenant SaaS\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nFull-featured SaaS with organizations, teams, and admin panel.\n\n### Invite-Only Platform\n\n```bash\nENABLE_SIGNUP=false\nENABLE_PASSKEY=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nNo public signup - users must be created by admin or invited to organizations.\n\n## Feature Detection\n\nCheck if a feature is enabled in your code:\n\n```ts\n\nif (isFeatureEnabled('organizations')) {\n // Show organizations menu\n}\n\nif (isFeatureEnabled('passkey')) {\n // Offer passkey setup\n}\n```\n\n## Dynamic Feature Configuration\n\nOverride features at runtime:\n\n```ts\n\nsetAppConfig({\n features: {\n organizations: false, // Disable organizations\n passkey: true, // Enable passkey\n },\n});\n```\n\n## Testing Features\n\nFor local development, create `.env.local`:\n\n```bash title=\".env.local\"\n# Test with all features enabled\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=true # Allow test emails\n```\n\n## Next Steps\n\n- **[Environment Variables](/account-ui/environment-variables)** - Complete variable reference\n- **[Customization](/account-ui/customization)** - Customize UI text and labels\n- **[Worker Setup](/account-ui/worker)** - Deploy your configuration"
|
|
31
|
-
},
|
|
32
|
-
"account-ui/features/organizations": {
|
|
33
|
-
"title": "Organizations",
|
|
34
|
-
"content": "Account UI provides a complete organization management interface when `ENABLE_ORGANIZATIONS=true`.\n\n## Organization CRUD\n\n- Create new organizations\n- Update organization name and settings\n- Delete organizations (owner only)\n\n## Member Management\n\n- Invite members by email\n- Assign roles: **owner**, **admin**, **member**\n- Remove members\n- Transfer ownership\n\n## Invitations\n\n- Pending invitation list\n- Resend invitations\n- Cancel invitations\n\n> **Note:** These three roles (`owner`, `admin`, `member`) are Better Auth's built-in organization roles and map directly to Account UI's role picker. Use the same roles in your Quickback [Access](/compiler/definitions/access) rules — with [`auth.roleHierarchy`](/compiler/definitions/access#role-hierarchy) configured, you can write `roles: [\"member+\"]` to mean \"member and above.\"\n\n## Related\n\n- [Environment Variables](/account-ui/environment-variables)\n- [Account UI Overview](/account-ui)"
|
|
35
|
-
},
|
|
36
|
-
"account-ui/features/passkeys": {
|
|
37
|
-
"title": "Passkeys",
|
|
38
|
-
"content": "When `ENABLE_PASSKEY=true`, Account UI provides passkey registration and management.\n\n## Passkey Registration\n\n- Setup wizard guides users through passkey creation\n- Supports fingerprint, Face ID, and hardware security keys\n- Multiple passkeys can be registered per account\n\n## Passkey Login\n\n- \"Sign in with passkey\" button on login page\n- Browser's native WebAuthn dialog\n- No password required\n\n## Managing Passkeys\n\n- View registered passkeys\n- Remove individual passkeys\n- Register additional passkeys\n\n## Requirements\n\n- HTTPS (WebAuthn requires secure context)\n- Modern browser with WebAuthn support\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/account-ui/environment-variables)"
|
|
39
|
-
},
|
|
40
|
-
"account-ui/features/passwordless": {
|
|
41
|
-
"title": "Passwordless Authentication",
|
|
42
|
-
"content": "Account UI supports passwordless authentication via email OTP and magic links.\n\n## Email OTP\n\nWhen `ENABLE_EMAIL_OTP=true`:\n\n- Users enter their email address\n- A one-time password is sent via email\n- User enters the OTP code to authenticate\n\n## Magic Links\n\nWhen `ENABLE_MAGIC_LINK=true`:\n\n- Users enter their email address\n- A login link is sent via email\n- Clicking the link authenticates the user\n\n## Combo Auth\n\nWhen both are enabled, Account UI uses the `@quickback-dev/better-auth-combo-auth` plugin to combine them into a single flow — the email contains both a clickable link and a code.\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/account-ui/environment-variables)"
|
|
43
|
-
},
|
|
44
|
-
"account-ui/features/sessions": {
|
|
45
|
-
"title": "Session Management",
|
|
46
|
-
"content": "Account UI includes a session management page where users can view and revoke their active sessions.\n\n## Active Sessions\n\nUsers can see all devices where they're currently logged in, including:\n\n- Device type and browser\n- IP address and approximate location\n- Last active timestamp\n\n## Revoking Sessions\n\nUsers can revoke any session except their current one. This immediately invalidates the session token.\n\n## Related\n\n- [Environment Variables](/account-ui/environment-variables)\n- [Account UI Overview](/account-ui)"
|
|
47
|
-
},
|
|
48
|
-
"account-ui": {
|
|
49
|
-
"title": "Account UI",
|
|
50
|
-
"content": "# Quickback Account UI\n\nA complete authentication and account management frontend. It handles login, signup, password reset, profile management, device sessions, passkeys, organizations, and admin — so you don't have to build any of it.\n\n## What's Included\n\nAccount UI is a single React SPA that contains three distinct sections:\n\n### Account (every user)\n\nLogin, signup, profile editing, password management, device sessions, email changes, and account deletion. This is what every user interacts with.\n\nServed on its own domain (e.g., `auth.example.com`) or at `/account/` when embedded alongside the CMS.\n\n### Organization Management (multi-tenant)\n\nDashboard with org switching, org creation, member invitations, role management, and org settings. Only available when `auth.organizations` is enabled.\n\n### Admin Panel (admin users only)\n\nUser management dashboard — view all users, search, create accounts, ban/unban, reset passwords, and manage sessions. Only accessible to users with the `admin` role. Can be served on its own domain (e.g., `admin.example.com`) via the `adminDomain` config.\n\n## Quick Start (Compiler-Embedded)\n\nThe recommended approach: add `account` to your `quickback.config.ts` and compile. The compiler builds the SPA from source with your project-specific settings baked in.\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\" },\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\nThat's it. The compiler:\n1. Reads your auth feature flags and branding from the config\n2. Generates a `.env` file with the correct `VITE_*` variables\n3. Builds the SPA from source with Vite (inside Docker)\n4. Excludes routes for disabled features (compile-time tree shaking)\n5. Outputs the built assets alongside your API code\n\nNo manual `.env` configuration needed. No separate deployment.\n\nSee [Configuration](/compiler/config) for all `account` options and [Multi-Domain Architecture](/compiler/config/domains) for custom domain setup.\n\n### Skip SPA Rebuild\n\nAfter the first compile, skip rebuilding the Account SPA on subsequent compiles:\n\n```typescript\naccount: { build: false, /* ...other options */ }\n```\n\nUseful when iterating on API features — saves significant compile time. Set back to `true` (or omit) when you need to update the Account UI.\n\n### Custom Output Directory\n\n```typescript\naccount: { outputDir: \"my-custom-path/account\" }\n```\n\nChanges where compiled Account assets are placed, instead of the default `src/apps/account/`.\n\n## Compile-Time Feature Gating\n\nAuth feature flags control which pages are included in the bundle:\n\n| Flag | Pages Included |\n|------|---------------|\n| `auth.password` | Password login, inline password change on profile |\n| `auth.emailOTP` | Email OTP login flow, email-based password reset |\n| `auth.passkey` | Passkey setup and management |\n| `auth.organizations` | Dashboard, org creation, member management, invitations |\n| `auth.admin` | Admin panel (user management) |\n\nWhen a flag is `false`, the corresponding route files are **removed before the Vite build** — they never appear in the JavaScript bundle. This keeps production bundles minimal.\n\n## Standalone Usage\n\nAccount UI also works outside of Quickback:\n\n### Template (own the source)\n\nClone the repo and customize directly:\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\nConfigure via `.env` files and deploy as a standalone Cloudflare Worker. See [Standalone Usage](/account-ui/standalone) for Better Auth backends or [With Quickback](/account-ui/with-quickback) for Quickback-compiled backends.\n\n### Library (npm package)\n\nInstall as a dependency:\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n```tsx\n\nsetAppConfig({\n authRoute: 'quickback',\n name: 'My App',\n});\n```\n\nSee [Library Usage](/account-ui/library-usage) for details.\n\n## Features\n\n- **Authentication** — Email/password, passkeys (WebAuthn), email OTP, magic links, email verification, password reset\n- **Account Management** — Profile editing, avatar upload, password changes, device/session management, account deletion\n- **Organizations** — Multi-tenant org management with owner/admin/member roles, invitations, and org settings\n- **Admin Panel** — User management dashboard with search, create, ban/unban, password reset, and session viewing\n- **API Keys** — Generate and manage API keys for programmatic access\n- **CLI Authorization** — Device authorization flow for `quickback login`\n\n## Next Steps\n\n- **[With Quickback](/account-ui/with-quickback)** — Compiler-embedded and standalone setup\n- **[Standalone Usage](/account-ui/standalone)** — Use with any Better Auth backend\n- **[Library Usage](/account-ui/library-usage)** — Import as an npm package\n- **[Feature Flags](/account-ui/features)** — Enable and disable features\n- **[Environment Variables](/account-ui/environment-variables)** — Configuration reference\n- **[Customization](/account-ui/customization)** — Branding, labels, and theming\n- **[Multi-Domain Architecture](/compiler/config/domains)** — Custom domains and hostname routing"
|
|
51
|
-
},
|
|
52
|
-
"account-ui/library-usage": {
|
|
53
|
-
"title": "Library Usage",
|
|
54
|
-
"content": "# Library Usage\n\nInstead of cloning the template, you can install Account UI as an npm package. This gives you automatic updates via `npm update` while configuring the UI through `setAppConfig()`.\n\n## Installation\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n### Peer Dependencies\n\nAccount UI expects these packages in your app:\n\n```bash\nnpm install react react-dom react-router-dom @tanstack/react-query\n```\n\n## Basic Setup\n\n### 1. Import and Configure\n\n```tsx title=\"src/main.tsx\"\n\nsetAppConfig({\n authRoute: 'quickback', // or 'better-auth' for standalone Better Auth\n name: 'My App',\n companyName: 'My Company Inc.',\n tagline: 'Build faster, ship sooner',\n description: 'My app description',\n});\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n);\n```\n\n### 2. Set API URLs\n\nThe library reads API URLs from `globalThis` variables. Set these before importing the library:\n\n```tsx title=\"src/main.tsx\"\n// Single catch-all: API + Account + CMS URLs are all derived from this origin.\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com';\n(globalThis as any).__QUICKBACK_APP_URL__ = 'https://app.example.com';\n\n// Then import dynamically to ensure globals are set first\nconst { AuthApp, setAppConfig } = await import('quickback-better-auth-account-ui');\nawait import('quickback-better-auth-account-ui/styles.css');\n```\n\nIf your API lives on a different subdomain, set `__QUICKBACK_API_URL__` explicitly instead (or alongside) — it takes precedence over the catch-all:\n\n```tsx\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com'; // catch-all\n(globalThis as any).__QUICKBACK_API_URL__ = 'https://api.example.com'; // explicit override\n```\n\nOr with Vite environment variables:\n\n```tsx title=\"src/main.tsx\"\n(globalThis as any).__QUICKBACK_URL__ = import.meta.env.VITE_QUICKBACK_URL;\n(globalThis as any).__QUICKBACK_API_URL__ = import.meta.env.VITE_QUICKBACK_API_URL;\n(globalThis as any).__QUICKBACK_APP_URL__ = import.meta.env.VITE_QUICKBACK_APP_URL;\n\nPromise.all([\n import('quickback-better-auth-account-ui'),\n import('quickback-better-auth-account-ui/styles.css'),\n]).then(([{ AuthApp, setAppConfig }]) => {\n setAppConfig({\n authRoute: 'quickback',\n name: import.meta.env.VITE_APP_NAME || 'My App',\n companyName: import.meta.env.VITE_COMPANY_NAME || 'My Company',\n tagline: import.meta.env.VITE_APP_TAGLINE || 'Welcome',\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n );\n});\n```\n\n## Cloudflare Worker\n\nThe library exports a Cloudflare Worker entry point for SPA routing and static asset serving:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nOr extend it with custom logic:\n\n```ts title=\"src/worker.ts\"\n\nexport default createAuthWorker();\n```\n\n## Configuration via `setAppConfig()`\n\nIn library mode, all configuration happens through `setAppConfig()` instead of environment variables.\n\n### Auth Route Mode\n\n```ts\nsetAppConfig({\n authRoute: 'quickback', // Quickback API: /auth/v1, /api/v1, /storage/v1\n // or\n authRoute: 'better-auth', // Better Auth default: /api/auth\n});\n```\n\n### Branding\n\n```ts\nsetAppConfig({\n name: 'Acme SaaS',\n companyName: 'Acme Corporation',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n### Labels and Messages\n\n```ts\nsetAppConfig({\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n },\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n },\n});\n```\n\n### Routes\n\n```ts\nsetAppConfig({\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n },\n },\n});\n```\n\n### Password and Session\n\n```ts\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n```\n\nSee [Customization](/account-ui/customization) for the full reference of all configurable options.\n\n## Exports\n\nThe library provides the following exports:\n\n### Main Entry (`quickback-better-auth-account-ui`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `AuthApp` | Component | The main React application component |\n| `authClient` | Object | Pre-configured Better Auth client |\n| `appConfig` | Object | Current app configuration |\n| `setAppConfig` | Function | Set app configuration overrides |\n| `createAppConfig` | Function | Create a new config object |\n| `getApiBase` | Function | Get the current API base URL |\n| `setApiBase` | Function | Override the API base URL |\n| `getAuthApiUrl` | Function | Get the auth API URL |\n| `getDataApiUrl` | Function | Get the data API URL |\n| `getStorageApiUrl` | Function | Get the storage API URL |\n\n### Styles (`quickback-better-auth-account-ui/styles.css`)\n\nThe compiled CSS for the Account UI. Must be imported for the UI to render correctly.\n\n### Worker (`quickback-better-auth-account-ui/worker`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `default` | Worker | Cloudflare Worker with SPA routing |\n| `createAuthWorker` | Function | Factory for creating a worker instance |\n\n## Custom Styles\n\nOverride styles by importing your CSS after the library styles:\n\n```ts\n\n```\n\n```css title=\"my-overrides.css\"\n:root {\n --primary: 59 130 246;\n --primary-foreground: 255 255 255;\n}\n```\n\n## Updating\n\nUpdate to the latest version:\n\n```bash\nnpm update quickback-better-auth-account-ui\n```\n\nThe library follows semantic versioning. Check the [changelog](https://github.com/Kardoe-com/quickback-better-auth-account-ui/releases) for breaking changes.\n\n## Next Steps\n\n- **[Customization](/account-ui/customization)** — Full configuration reference\n- **[Feature Flags](/account-ui/features)** — Enable and disable features\n- **[Worker Setup](/account-ui/worker)** — Deploy to Cloudflare Workers\n- **[With Quickback](/account-ui/with-quickback)** — Quickback-specific configuration"
|
|
55
|
-
},
|
|
56
|
-
"account-ui/standalone": {
|
|
57
|
-
"title": "Standalone Usage",
|
|
58
|
-
"content": "Account UI can be used with **any Better Auth-powered backend**, not just Quickback-compiled projects. This makes it a drop-in authentication frontend for any app using Better Auth.\n\n## Requirements\n\n- A backend running [Better Auth](https://better-auth.com) with API endpoints\n- Node.js 18+ and npm/pnpm/bun\n- A Cloudflare account (for deployment)\n\n## Setup\n\n### 1. Clone or Install the Account UI\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### 2. Configure the Auth Route Mode\n\nThe key difference from Quickback mode is the `VITE_AUTH_ROUTE` variable. Set it to `better-auth` to use Better Auth's default API paths:\n\n```bash title=\".env\"\n# Auth route mode — use 'better-auth' for standalone\nVITE_AUTH_ROUTE=better-auth\n\n# Your Better Auth backend URL (single catch-all — see below)\nVITE_QUICKBACK_URL=https://secure.example.com\n\n# Where this Account UI is hosted\nVITE_ACCOUNT_APP_URL=https://account.example.com\n```\n\n`VITE_QUICKBACK_URL` is the recommended one-variable setup. If your API lives on a separate subdomain, set `VITE_QUICKBACK_API_URL` explicitly — it takes precedence.\n\nThis configures the auth client to use `/api/auth` as the base path (Better Auth's default), instead of Quickback's `/auth/v1`.\n\n### 3. Configure Your App\n\n```bash title=\".env\"\n# App identity\nVITE_APP_NAME=My App\nVITE_APP_TAGLINE=Welcome to My App\n\n# Redirect after login\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Feature flags\nENABLE_SIGNUP=true\nENABLE_ORGANIZATIONS=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\n```\n\nSee [Environment Variables](/account-ui/environment-variables) for the complete reference.\n\n### 4. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Auth Route Modes\n\nAccount UI supports three routing modes, controlled by `VITE_AUTH_ROUTE`:\n\n| Mode | Value | Auth Path | Data Path | Storage Path |\n|------|-------|-----------|-----------|--------------|\n| Better Auth | `better-auth` | `/api/auth` | — | — |\n| Quickback | `quickback` | `/auth/v1` | `/api/v1` | `/storage/v1` |\n| Custom | `custom` | Custom | Custom | Custom |\n\n### Better Auth Mode (Default)\n\nRoutes all auth requests to `/api/auth/*` — the standard Better Auth convention:\n\n```bash\nVITE_AUTH_ROUTE=better-auth\n```\n\n### Custom Mode\n\nFor non-standard setups, use custom mode with explicit paths:\n\n```bash\nVITE_AUTH_ROUTE=custom\nVITE_AUTH_BASE_PATH=/my-auth\nVITE_DATA_BASE_PATH=/my-api\nVITE_STORAGE_BASE_PATH=/my-storage\n```\n\n## Backend Requirements\n\nYour Better Auth backend must have the following plugins enabled for full Account UI functionality:\n\n| Feature | Required Plugin | Required For |\n|---------|----------------|--------------|\n| Organizations | `organization` | Multi-tenant org management |\n| Admin panel | `admin` | User management dashboard |\n| API keys | `apiKey` | API key generation UI |\n| Passkeys | `@better-auth/passkey` | WebAuthn authentication |\n| Email OTP | `emailOTP` | One-time password login |\n| CLI login | `deviceAuthorization` | `quickback login` flow |\n\nOnly enable the features that match your backend's plugin configuration. Disable features for plugins you haven't installed:\n\n```bash\n# If your backend doesn't have the organization plugin:\nENABLE_ORGANIZATIONS=false\n\n# If you haven't set up passkeys:\nENABLE_PASSKEYS=false\n```\n\n## CORS Configuration\n\nYour Better Auth backend must allow requests from the Account UI's domain. Configure CORS to include:\n\n```typescript\n// In your Better Auth config\ntrustedOrigins: [\n \"https://account.example.com\", // Account UI domain\n],\n```\n\n## Differences from Quickback Mode\n\n| Aspect | Standalone | With Quickback |\n|--------|-----------|----------------|\n| Auth routes | `/api/auth/*` | `/auth/v1/*` |\n| Data API | Not used | `/api/v1/*` |\n| Storage API | Not used | `/storage/v1/*` |\n| File uploads | Manual setup | Auto-configured |\n| Backend | Any Better Auth app | Quickback-compiled |\n\n## Next Steps\n\n- [Environment Variables](/account-ui/environment-variables) — Complete configuration reference\n- [Customization](/account-ui/customization) — Branding, labels, and theming\n- [Worker Setup](/account-ui/worker) — Cloudflare Workers deployment\n- [Feature Flags](/account-ui/features) — Enable and disable features"
|
|
59
|
-
},
|
|
60
|
-
"account-ui/with-quickback": {
|
|
61
|
-
"title": "With Quickback",
|
|
62
|
-
"content": "When using Account UI with a Quickback-compiled backend, the recommended approach is to let the compiler build and embed the SPA directly into your Worker.\n\n## Compiler-Embedded (Recommended)\n\nAdd `account` to your `quickback.config.ts`:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\nThen compile and deploy:\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\n### What Happens During Compilation\n\n1. The compiler reads your `account` config and generates a `.env` file with the correct Vite environment variables (`VITE_QUICKBACK_URL`, `VITE_QUICKBACK_API_URL`, `VITE_ENABLE_PASSWORD`, branding, etc.)\n2. The Account SPA source is copied to a temp directory, with disabled feature routes excluded\n3. Pre-installed dependencies are symlinked (no `npm install` during build)\n4. Vite builds the SPA with your settings baked in\n5. Built assets (content-hashed filenames) are placed in the output directory\n\nWhen CMS is also enabled, Account assets go to `src/apps/account/` and are served at `/account/`. When Account is the only SPA, assets go to `src/apps/` and are served at root.\n\n### Custom Domains\n\nWith a custom domain, the Account SPA is served at root (`/`) on that domain:\n\n```typescript\naccount: { domain: \"auth.example.com\" }\n```\n\nAdd an admin domain to serve the admin panel on its own subdomain:\n\n```typescript\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n}\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing and cross-subdomain cookies.\n\n### Auth Feature Flags\n\nFeature flags control which pages are included in the build:\n\n```typescript\nauth: {\n password: true, // Email/password login + inline password change\n emailOTP: false, // Email OTP login flow\n passkey: true, // WebAuthn passkey setup + management\n organizations: true, // Dashboard, org management, invitations\n admin: true, // Admin panel (user management)\n}\n```\n\nDisabled features are excluded at compile time — their route files are removed before the Vite build. See [Configuration](/compiler/config) for all options.\n\n## Manual Deployment\n\nIf you need Account UI as a separate Worker (not embedded in the API Worker), you can deploy it standalone.\n\n### 1. Clone the Template\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### 2. Configure for Quickback\n\nSet the auth route mode to `quickback` to match Quickback's API paths:\n\n```bash title=\".env\"\nVITE_AUTH_ROUTE=quickback\n# One variable points at the Quickback origin — API, Account, and CMS are all derived from it.\nVITE_QUICKBACK_URL=https://secure.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\n```\n\nIn Quickback mode, Account UI routes requests to three API paths:\n\n| Path | Purpose | Examples |\n|------|---------|---------|\n| `/auth/v1/*` | Authentication | Login, signup, sessions, passkeys |\n| `/api/v1/*` | Data API | Organizations, API keys |\n| `/storage/v1/*` | File storage | Avatar uploads, file management |\n\n### 3. Configure Features\n\nMatch your `quickback.config.ts` plugins:\n\n```bash title=\".env\"\nVITE_APP_NAME=My App\nVITE_APP_TAGLINE=Build faster, ship sooner\nENABLE_SIGNUP=true\nENABLE_ORGANIZATIONS=true\nENABLE_PASSKEY=true\nENABLE_ADMIN=true\n```\n\n### 4. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Library Mode\n\nInstall as a dependency instead of cloning:\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n```tsx\n\nsetAppConfig({\n authRoute: 'quickback',\n name: 'My App',\n companyName: 'My Company',\n});\n```\n\nSee [Library Usage](/account-ui/library-usage) for the complete guide.\n\n## Next Steps\n\n- [Configuration](/compiler/config) — CMS and Account config reference\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Environment Variables](/account-ui/environment-variables) — Complete variable reference\n- [Feature Flags](/account-ui/features) — Enable and disable features\n- [Customization](/account-ui/customization) — Branding, labels, and theming"
|
|
63
|
-
},
|
|
64
|
-
"account-ui/worker": {
|
|
65
|
-
"title": "Worker Setup",
|
|
66
|
-
"content": "# Worker Setup\n\nDeploy the Account UI as a Cloudflare Worker with static asset serving.\n\n## Quick Start\n\n### Using the Template\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### Using the Library\n\nIf you're consuming Account UI as an npm package, re-export the worker from the library:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nThen continue with the Wrangler configuration below.\n\n### 2. Configure Wrangler\n\nThe template includes a `wrangler.toml` pre-configured for Cloudflare Workers:\n\n```toml title=\"wrangler.toml\"\nname = \"my-account-app\"\ncompatibility_date = \"2025-01-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n# Custom domain (uncomment and set your domain)\n# routes = [\n# { pattern = \"account.example.com\", custom_domain = true }\n# ]\n\n# Worker entry point\nmain = \"src/worker.ts\"\n\n# Static assets\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\"\n```\n\n### 3. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Worker Entry Point\n\nThe worker is at `src/worker.ts`. It serves static assets and handles SPA routing:\n\n- Static asset serving via the `ASSETS` binding\n- SPA routing (all routes serve `index.html`)\n- Health check endpoint (`/health`)\n\n### Custom Worker Logic\n\nEdit `src/worker.ts` directly to add custom logic:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise\n\n### Multiple Environments\n\n```toml title=\"wrangler.toml\"\n# Development\n[env.dev]\nname = \"my-account-app-dev\"\nroute = \"account-dev.example.com/*\"\n\n[env.dev.vars]\nVITE_QUICKBACK_URL = \"https://secure-dev.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-dev.example.com\"\n\n# Staging\n[env.staging]\nname = \"my-account-app-staging\"\nroute = \"account-staging.example.com/*\"\n\n[env.staging.vars]\nVITE_QUICKBACK_URL = \"https://secure-staging.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-staging.example.com\"\n\n# Production\n[env.production]\nname = \"my-account-app\"\nroute = \"account.example.com/*\"\n\n[env.production.vars]\nVITE_QUICKBACK_URL = \"https://secure.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\n```\n\nDeploy to specific environment:\n\n```bash\nwrangler deploy --env staging\nwrangler deploy --env production\n```\n\n## Cloudflare Pages Alternative\n\nYou can also deploy to Cloudflare Pages instead of Workers:\n\n### 1. Configure Build\n\n```toml title=\"wrangler.toml\"\n# Remove [assets] section - Pages handles this\n\nname = \"my-account-app\"\npages_build_output_dir = \"dist/client\"\n```\n\n### 2. Deploy to Pages\n\n```bash\n# First time setup\nwrangler pages project create my-account-app\n\n# Deploy\nwrangler pages deploy dist/client\n```\n\n### 3. Configure Environment Variables\n\nSet environment variables in Cloudflare Pages dashboard:\n1. Go to your Pages project\n2. **Settings** → **Environment Variables**\n3. Add `VITE_*` variables\n4. Redeploy\n\n## Local Development\n\n### Option 1: Vite Dev Server\n\nThe fastest way to develop locally:\n\n```bash\nnpx vite dev\n```\n\nThis starts the Vite dev server with hot module replacement on `localhost:5173`.\n\n### Option 2: Wrangler Dev\n\nTest the worker locally with `wrangler dev`:\n\n```bash\nnpm run build && wrangler dev\n```\n\nThis runs the worker on `localhost:8787`.\n\n## Health Check\n\nThe worker includes a built-in health check endpoint:\n\n```bash\ncurl https://account.example.com/health\n```\n\nResponse:\n\n```json\n{\n \"status\": \"ok\",\n \"app\": \"auth-ui\"\n}\n```\n\nUse this for:\n- Uptime monitoring\n- Load balancer health checks\n- Deployment verification\n\n## Security Headers\n\nAdd security headers by editing `src/worker.ts`:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n // ... routing logic ...\n\n // Add security headers to response\n const response = await env.ASSETS.fetch(request);\n\n const headers = new Headers(response.headers);\n headers.set('X-Frame-Options', 'DENY');\n headers.set('X-Content-Type-Options', 'nosniff');\n headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n headers.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n },\n};\n```\n\n## Custom 404 Page\n\nServe a custom 404 page for unmatched routes:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n const url = new URL(request.url);\n\n // Try to serve static asset\n const assetResponse = await env.ASSETS.fetch(request);\n\n if (assetResponse.status !== 404) {\n return assetResponse;\n }\n\n // Serve index.html for SPA routes\n if (!url.pathname.startsWith('/api/')) {\n const indexRequest = new Request(`${url.origin}/index.html`, request);\n return env.ASSETS.fetch(indexRequest);\n }\n\n // Custom 404 for API routes\n return new Response('Not Found', { status: 404 });\n },\n};\n```\n\n## Deployment Checklist\n\nBefore deploying to production:\n\n- [ ] Set all required environment variables (`VITE_QUICKBACK_URL` or `VITE_QUICKBACK_API_URL`, etc.)\n- [ ] Configure custom domain in Cloudflare\n- [ ] Add SSL certificate (automatic with Cloudflare)\n- [ ] Test all authentication flows\n- [ ] Configure DNS records\n- [ ] Set up monitoring/health checks\n- [ ] Test email sending\n- [ ] Verify passkey functionality (requires HTTPS)\n- [ ] Check CORS configuration on API\n- [ ] Review security headers\n- [ ] Test organization invitations\n- [ ] Verify redirection to main app works\n\n## Troubleshooting\n\n### Assets Not Loading\n\n**Problem**: 404 errors for static assets (JS, CSS)\n\n**Solution**: Check `directory` path in `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\" # Must point to Vite's client build output\n```\n\n### Environment Variables Not Working\n\n**Problem**: Config values are undefined\n\n**Solution**: Remember that `VITE_*` variables are build-time. Either:\n1. Set them in `.env.production` before building\n2. Use `setAppConfig()` in `src/main.tsx` for runtime overrides\n3. Edit `src/config/app.ts` defaults directly\n\n### SPA Routing Issues\n\n**Problem**: Refreshing on `/profile` returns 404\n\n**Solution**: Ensure your worker serves `index.html` for all non-asset routes:\n\n```ts\nif (assetResponse.status === 404 && !url.pathname.startsWith('/api/')) {\n return env.ASSETS.fetch(new Request(`${url.origin}/index.html`, request));\n}\n```\n\n## Next Steps\n\n- **[Environment Variables](/account-ui/environment-variables)** - Configure your deployment\n- **[Feature Flags](/account-ui/features)** - Enable features\n- **[Customization](/account-ui/customization)** - Brand your UI"
|
|
67
|
-
},
|
|
68
4
|
"changelog": {
|
|
69
5
|
"title": "Changelog",
|
|
70
|
-
"content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. The filename is the action name AND the URL segment.\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names must be unique within a feature.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/docs/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nAction names must be unique within a feature — the runtime actions module merges every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would silently overwrite. Disambiguate (`publishEpisode`, `publishShow`); the compiler emits a named error pointing at both locations on collision.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now a targeted error signal.** When a table carries `ownerId` but no isolation column AND no explicit `firewall:`, the compiler raises a specific error: `\\`ownerId\\` is business-logic ownership, not access control — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-read-views)\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `?view={name}` (or `/views/{name}`)\n\n**Pre-record access ordering on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/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
|
-
},
|
|
72
|
-
"cms/actions": {
|
|
73
|
-
"title": "Actions",
|
|
74
|
-
"content": "# Actions\n\nActions are custom operations defined in your feature files (e.g., `approve`, `void`, `post`, `applyPayment`). The CMS renders them as clickable buttons with auto-generated input forms — no UI code required.\n\n## Where Actions Appear\n\nActions show up in two places:\n\n### Row Action Menu (Table Mode)\n\nIn Table mode, the three-dot menu on each row includes a section for custom actions. Actions are separated from standard operations (view, edit, delete) by a divider.\n\n### Action Bar (Detail View)\n\nIn the record detail view, an \"Actions\" card displays all available actions as buttons. Each button shows the action name, and hovering reveals the description as a tooltip.\n\n## Action Dialog\n\nClicking an action opens a modal dialog with:\n\n1. **Header** — Action name with an icon (lightning bolt for standard, warning triangle for destructive, download for file responses)\n2. **Description** — The action's description text\n3. **Side effects warning** — If the action has `sideEffects: \"sync\"`, an amber warning banner appears: \"This action has synchronous side effects (e.g., GL entries).\"\n4. **Confirmation step** — If the action has `cms.confirm`, a confirmation message appears before the input form\n5. **Input fields** — Auto-generated from the action's `inputFields` schema\n6. **Execute button** — Submits the action. Shows \"Executing...\" while in progress.\n7. **Cancel button** — Closes the dialog without executing\n\n### Input Field Types\n\nThe dialog generates the appropriate input control for each field:\n\n| Zod Type | Input Control | Notes |\n|----------|--------------|-------|\n| `string` | Text input | Free-text entry |\n| `number` | Number input | Step 0.01, supports decimals |\n| `boolean` | Checkbox | With label text |\n| `array<string>` | Text input | Comma-separated values, split on save |\n\nRequired fields are marked with a red asterisk. Default values from the schema are pre-filled.\n\n### Example\n\nGiven this action definition:\n\n```typescript\nactions: {\n applyPayment: {\n description: \"Apply a payment to this invoice\",\n input: 'z.object({ amount: z.number(), reference: z.string().optional() })',\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'posted' } },\n },\n sideEffects: \"sync\",\n cms: {\n label: \"Apply Payment\",\n icon: \"dollar-sign\",\n confirm: \"This will create GL entries. Continue?\",\n category: \"payments\",\n successMessage: \"Payment applied successfully\",\n order: 1,\n },\n },\n}\n```\n\nThe CMS renders a dialog with:\n\n- A number input for `amount` (required)\n- A text input for `reference` (optional)\n- A sync side effects warning\n- A confirmation step with the custom message\n- Only visible to admins and owners\n- Only visible on records where `status === \"posted\"`\n\n## Access Filtering\n\nActions are filtered based on two criteria:\n\n### Role Check\n\nThe action's `access.roles` array is compared against the current user's role. If the user's role is not in the list, the action is hidden.\n\n### Record Condition\n\nThe action's `access.record` conditions are evaluated against the current record's data. Supported conditions:\n\n| Operator | Example | Meaning |\n|----------|---------|---------|\n| `equals` | `{ status: { equals: 'pending' } }` | Field must equal value |\n| `notEquals` | `{ status: { notEquals: 'void' } }` | Field must not equal value |\n| `in` | `{ status: { in: ['pending', 'draft'] } }` | Field must be one of values |\n\nAll conditions must pass for the action to be visible. This means \"approve\" actions naturally disappear after a record is approved, and \"void\" actions only appear on voidable records.\n\n## CMS Metadata\n\nActions can include an optional `cms` property for enhanced CMS rendering. Actions without `cms` render with default behavior.\n\n| Property | Type | Default | Purpose |\n|----------|------|---------|---------|\n| `label` | `string` | camelCase split | Display name override |\n| `icon` | `string` | `\"zap\"` | Lucide icon name |\n| `confirm` | `string \\| boolean` | `false` | `true` = generic confirm, string = custom message |\n| `destructive` | `boolean` | `false` | Red styling + requires confirmation |\n| `category` | `string` | none | Group actions under a header |\n| `hidden` | `boolean` | `false` | Hide from CMS entirely (API-only actions) |\n| `successMessage` | `string` | none | Toast message after success |\n| `onSuccess` | `\"refresh\" \\| \"redirect:list\" \\| \"close\"` | `\"refresh\"` | Behavior after successful execution |\n| `order` | `number` | `0` | Sort priority (lower = first) |\n\n### Example with CMS metadata\n\n```typescript\n// features/invoices/actions/post.ts\n\nexport default defineAction({\n description: \"Post this invoice to accounts receivable\",\n input: z.object({}),\n access: { roles: [\"owner\", \"admin\"], record: { status: { equals: \"draft\" } } },\n sideEffects: \"sync\",\n cms: {\n label: \"Post Invoice\",\n icon: \"send\",\n confirm: \"This will post the invoice to AR and create GL entries. Continue?\",\n category: \"lifecycle\",\n successMessage: \"Invoice posted successfully\",\n onSuccess: \"refresh\",\n order: 1,\n },\n async execute({ db, record, auditFields }) {\n // ... post invoice\n return { ok: true };\n },\n});\n```\n\n### Hiding API-only actions\n\n```typescript\n// features/invoices/actions/internal-recalc.ts\n\nexport default defineAction({\n description: \"Recalculate internal totals\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n cms: { hidden: true }, // Never shown in CMS\n async execute({ db, record }) {\n // ... recalc totals\n return { ok: true };\n },\n});\n```\n\n## Destructive Actions\n\nActions are styled as destructive when either:\n\n- The action's `cms.destructive` is `true`\n- The action is named `void` or `delete` (legacy fallback)\n\nDestructive actions receive:\n\n- **Red text** in the row action menu\n- **Warning triangle icon** (unless overridden by `cms.icon`)\n- **Red execute button** in the dialog (using `bg-destructive` styling)\n- **Automatic confirmation step** (unless `cms.confirm` is explicitly `false`)\n\nThis provides a visual cue that the action has permanent consequences.\n\n## Standalone Actions\n\nActions with `path:` set are standalone — not tied to a specific record. They appear in a separate section and don't receive a `recordId` when executed. The CMS passes `null` as the record ID for standalone actions.\n\n## File Response Actions\n\nActions with `responseType: \"file\"` show a download icon instead of the lightning bolt. When executed, the response is treated as a file download rather than a JSON result.\n\n## Execution Flow\n\n1. User clicks action in row menu or action bar\n2. Dialog opens with description, inputs, and warnings\n3. If `cms.confirm` is set, user sees confirmation step first\n4. User fills in required fields\n5. User clicks \"Execute\" (or \"Confirm\" after confirmation step)\n6. CMS calls `client.executeAction(table, actionName, recordId, input)`\n7. On success: `cms.successMessage` shown as toast (if set), then `cms.onSuccess` behavior\n8. On error: error message displayed in dialog\n\n## Next Steps\n\n- **[Security](/cms/security)** — Access conditions and role-based access\n- **[Table Views](/cms/table-views)** — Where actions appear in the UI\n- **[Schema Format Reference](/cms/schema-format)** — ActionMeta type definition"
|
|
6
|
+
"content": "# Changelog\n\nRelease notes for the Quickback compiler, CLI, and platform.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. The filename is the action name AND the URL segment.\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now a targeted error signal.** When a table carries `ownerId` but no isolation column AND no explicit `firewall:`, the compiler raises a specific error: `\\`ownerId\\` is business-logic ownership, not access control — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-read-views)\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `?view={name}` (or `/views/{name}`)\n\n**Pre-record access ordering on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now Enforced Server-Side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\n// \"Org owner OR platform admin\"\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or`/`and` combinators. See [Access - userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"short\",\n }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access - Role Hierarchy](/compiler/definitions/access#role-hierarchy) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now receive a **security-scoped database** instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nThe scoped DB uses duck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **automatically cascades** to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade UPDATE statements.\n\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- KV and R2 storage integrations\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial Release\n\n- **Quickback Compiler** — TypeScript-first backend compiler\n- **Four Security Pillars** — Firewall, Access, Guards, Masking\n- **`defineTable()`** — Schema + security configuration in a single file\n- **Templates** — Cloudflare Workers, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\n- **Better Auth Integration** — Organizations, roles, sessions\n- **Drizzle ORM** — Schema-first with automatic migrations\n- **Cloudflare D1** — Split database support (auth + features)"
|
|
75
7
|
},
|
|
76
|
-
"
|
|
77
|
-
"title": "
|
|
78
|
-
"content": "# Components Reference\n\nThe CMS is built from composable React components organized by function. Every component reads metadata from the schema registry and adapts its behavior based on the current role.\n\n## Layout\n\n### Sidebar\n\nThe main navigation sidebar. Reads the schema registry to build a collapsible feature-grouped table list.\n\n```typescript\ninterface SidebarProps {\n // No props — reads schema registry directly\n}\n```\n\n| Behavior | Description |\n|----------|-------------|\n| Feature grouping | Tables grouped by feature with collapsible sections |\n| Feature icons | Each feature gets a contextual icon (e.g., Calculator for accounting) |\n| Active state | Current table highlighted with primary color |\n| Internal filter | Tables with `internal: true` are hidden |\n| Footer stats | Shows total feature and table counts |\n\n### Header\n\nTop bar with tagline and role switcher.\n\n```typescript\ninterface HeaderProps {\n // No props — renders tagline and RoleSwitcher\n}\n```\n\n### RoleSwitcher\n\nDropdown to switch between `owner`, `admin`, and `member` roles. Available in demo mode. In live mode, the role is read from the authenticated session.\n\n```typescript\n// Uses RoleContext internally\n// Provides: role, setRole, session\n```\n\n## Table\n\n### DataTable\n\nStandard browse table with clickable rows and sortable columns.\n\n```typescript\ninterface DataTableProps {\n data: Record[];\n columns: ColumnDef[];\n onRowClick?: (row: Record) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `data` | Array of records to display |\n| `columns` | Column definitions (built by `ColumnFactory`) |\n| `onRowClick` | Handler when a row is clicked (navigates to detail view) |\n\n### SpreadsheetTable\n\nExcel/Google Sheets-like editable table with cell selection and keyboard navigation.\n\n```typescript\ninterface SpreadsheetTableProps {\n data: Record[];\n columns: ColumnDef[];\n onCellEdit: (recordId: string, field: string, value: unknown) => Promise<void>;\n editableFields: Set<string>;\n onFKSearch: (targetTable: string, query: string) => Promise<FKOption[]>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `data` | Array of records to display |\n| `columns` | Column definitions |\n| `onCellEdit` | Called when a cell value is saved (auto-saves on blur/Enter) |\n| `editableFields` | Set of field names that can be edited (from guards) |\n| `onFKSearch` | Async function for FK typeahead search |\n\n### Toolbar\n\nSearch bar, view selector, view mode toggle, and refresh button.\n\n```typescript\ninterface ToolbarProps {\n table: TableMeta;\n search: string;\n onSearchChange: (search: string) => void;\n onRefresh: () => void;\n selectedView?: string;\n onViewChange: (view: string | undefined) => void;\n viewMode: \"table\" | \"dataTable\";\n onViewModeChange: (mode: \"table\" | \"dataTable\") => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used to build view dropdown) |\n| `search` | Current search query |\n| `onSearchChange` | Handler for search input changes |\n| `onRefresh` | Refreshes the table data |\n| `selectedView` | Currently selected view name (undefined = all fields) |\n| `onViewChange` | Handler for view selection changes |\n| `viewMode` | Current view mode |\n| `onViewModeChange` | Handler for toggling between Table and Data Table |\n\n### Pagination\n\nPage navigation controls with range indicator.\n\n```typescript\ninterface PaginationProps {\n page: number;\n pageSize: number;\n total: number;\n onPageChange: (page: number) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `page` | Current page number (1-indexed) |\n| `pageSize` | Records per page |\n| `total` | Total record count |\n| `onPageChange` | Handler for page changes |\n\n### RowActions\n\nThree-dot dropdown menu on each table row with view, edit, delete, and custom actions.\n\n```typescript\ninterface RowActionsProps {\n table: TableMeta;\n record: Record;\n onDelete?: (id: string) => void;\n onAction?: (action: ActionMeta, record: Record) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used for CRUD access checks and action filtering) |\n| `record` | The row's record data |\n| `onDelete` | Handler for delete action |\n| `onAction` | Handler for custom action selection |\n\n### ColumnFactory\n\nUtility function (not a component) that builds column definitions from table metadata.\n\n```typescript\nfunction buildColumns(\n table: TableMeta,\n role: Role,\n options?: { viewFields?: string[] }\n): ColumnDef[];\n```\n\nGenerates columns with appropriate formatters for each field type: dates, money, booleans, enums, FK references, masked values, and plain text. Respects view field projections when provided.\n\n## Record\n\n### RecordDetail\n\nGrouped field display for a single record. Auto-groups fields by category (Identity, Contact, Financial, References, Settings, Dates, Audit).\n\n```typescript\ninterface RecordDetailProps {\n table: TableMeta;\n record: Record;\n role: Role;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (columns, masking, validation) |\n| `record` | The record data to display |\n| `role` | Current user role (affects masking) |\n\n### FieldDisplay\n\nRenders a single field value with appropriate formatting: masking, booleans, enums, FK links, dates, money, percentages, and numbers.\n\n```typescript\ninterface FieldDisplayProps {\n column: ColumnMeta;\n value: unknown;\n role: Role;\n masking?: Record<string, MaskingRule>;\n validation?: Record<string, ValidationRule>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `column` | Column metadata (type, mode, name) |\n| `value` | The raw value to display |\n| `role` | Current role (for masking checks) |\n| `masking` | Masking rules for the table |\n| `validation` | Validation rules (used for enum detection) |\n\n### ActionBar\n\nCard displaying available actions as buttons for the current record.\n\n```typescript\ninterface ActionBarProps {\n table: TableMeta;\n record: Record;\n onAction: (action: ActionMeta) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata |\n| `record` | Current record (used for access condition evaluation) |\n| `onAction` | Handler when an action button is clicked |\n\n### RelatedRecords\n\nCard showing incoming FK relationships with record counts. Lists tables that reference the current record.\n\n```typescript\ninterface RelatedRecordsProps {\n table: TableMeta;\n recordId: string;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used to discover incoming FK relationships) |\n| `recordId` | Current record ID (used to count related records) |\n\n## Form\n\n### AutoForm\n\nAuto-generated create/edit form built from the table's guard configuration.\n\n```typescript\ninterface AutoFormProps {\n table: TableMeta;\n mode: \"create\" | \"edit\";\n initialData?: Record;\n onSubmit: (data: Record) => Promise<void>;\n onCancel: () => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (guards, columns, validation) |\n| `mode` | `\"create\"` uses createable fields, `\"edit\"` uses updatable fields |\n| `initialData` | Pre-filled values for edit mode |\n| `onSubmit` | Handler for form submission |\n| `onCancel` | Handler for cancel button |\n\nFeatures:\n\n- Fields determined from guards (createable for create, updatable for edit)\n- Immutable fields shown as disabled with lock icon\n- Protected fields shown as disabled with \"Updated via actions only\" note\n- Client-side validation from schema rules\n- Boolean fields grouped in a \"Settings\" section\n- Required fields marked with red asterisk\n\n### FieldInput\n\nSingle form input that adapts to the column type and validation rules.\n\n```typescript\ninterface FieldInputProps {\n column: ColumnMeta;\n validation?: ValidationRule;\n value: unknown;\n onChange: (value: unknown) => void;\n error?: string;\n disabled?: boolean;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `column` | Column metadata (determines input type) |\n| `validation` | Validation rules (enum values, min/max, email) |\n| `value` | Current field value |\n| `onChange` | Handler for value changes |\n| `error` | Error message to display |\n| `disabled` | Whether the input is disabled |\n\nRenders as: text input, number input, email input, URL input, date picker, select dropdown (for enums), textarea (for long text), or checkbox (for booleans).\n\n## Actions\n\n### ActionDialog\n\nModal dialog for executing a custom action with auto-generated input fields.\n\n```typescript\ninterface ActionDialogProps {\n action: ActionMeta;\n record: Record;\n tableName: string;\n onClose: () => void;\n onExecute: (input: Record) => Promise<void>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `action` | Action metadata (name, description, inputFields, sideEffects) |\n| `record` | The record the action applies to |\n| `tableName` | Table name (for context) |\n| `onClose` | Handler to close the dialog |\n| `onExecute` | Handler to execute the action with form data |\n\nFeatures:\n\n- Auto-generates input fields from action schema\n- Destructive actions get red styling and warning icon\n- File response actions get download icon\n- Side effects warning banner for `sideEffects: \"sync\"`\n- Loading state during execution\n- Error display on failure\n\n## Pages\n\n### PageRenderer\n\nTop-level component that receives a `PageMeta` object and delegates to the appropriate layout component.\n\n```typescript\ninterface PageRendererProps {\n page: PageMeta;\n}\n```\n\nCurrently supports the `split-panel` layout type. Falls back to an error message for unknown layout types.\n\n### SplitPanelLayout\n\nRenders a two-panel layout with drag-and-drop support (via `@dnd-kit/core`), matching engine integration, and page action dialogs.\n\n```typescript\ninterface SplitPanelLayoutProps {\n page: PageMeta;\n}\n```\n\n| Behavior | Description |\n|----------|-------------|\n| Panel rendering | Renders left and right `DataPanel` components side by side |\n| Drag-and-drop | Enables DnD between panels based on panel `features` |\n| Match scoring | Computes match suggestions using `computeMatches()` and passes scores to panels |\n| Action trigger | Opens `PageActionDialog` when a record is dragged from one panel to another |\n| Refresh | Refreshes both panels after a successful action |\n\n### DataPanel\n\nA single panel within a page layout. Fetches data from the API, displays rows with column headers, and supports search.\n\n```typescript\ninterface DataPanelProps {\n panel: PagePanel;\n dataSource: PageDataSource;\n matchScores?: Map<string, number>;\n onDataLoaded?: (records: Record_[]) => void;\n refreshKey?: number;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `panel` | Panel metadata (id, title, position, features) |\n| `dataSource` | Data source config (table, filters, sort, display columns) |\n| `matchScores` | Map of record ID to best match score (for confidence badges) |\n| `onDataLoaded` | Callback when records are fetched (used by parent for match computation) |\n| `refreshKey` | Incrementing key to trigger a re-fetch |\n\n### PanelRow\n\nA single row within a `DataPanel`. Integrates with `@dnd-kit` for drag-source and drop-target behavior.\n\n```typescript\ninterface PanelRowProps {\n record: Record_;\n columns: string[];\n panelId: string;\n features?: string[];\n matchScore?: number;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `record` | The record data for this row |\n| `columns` | Column names to display |\n| `panelId` | Parent panel ID (used for DnD context) |\n| `features` | Panel features (`\"drag-source\"`, `\"drop-target\"`) |\n| `matchScore` | Match confidence score (renders `ConfidenceBadge` when present) |\n\n### PageActionDialog\n\nModal dialog triggered by drag-and-drop. Resolves input mappings from source and target records and executes a page action.\n\n```typescript\ninterface PageActionDialogProps {\n pageAction: PageAction;\n sourceRecord: Record_;\n targetRecord: Record_;\n sourceDataSource: string;\n targetDataSource: string;\n onClose: () => void;\n onSuccess: () => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `pageAction` | The page action definition (table, action, inputMapping, label, icon, confirm) |\n| `sourceRecord` | The dragged record |\n| `targetRecord` | The drop-target record |\n| `sourceDataSource` | Data source name for the source record |\n| `targetDataSource` | Data source name for the target record |\n| `onClose` | Close handler |\n| `onSuccess` | Called after successful action execution (triggers panel refresh) |\n\n### ConfidenceBadge\n\nDisplays a match confidence score as a colored percentage badge.\n\n```typescript\ninterface ConfidenceBadgeProps {\n score: number; // 0-1\n}\n```\n\n| Score Range | Color |\n|-------------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n### computeMatches (utility)\n\nNot a component — a utility function that runs the matching engine. Compares left and right record arrays using the page's matching rules and returns sorted match suggestions.\n\n```typescript\nfunction computeMatches(\n leftRecords: Record_[],\n rightRecords: Record_[],\n page: PageMeta\n): MatchSuggestion[];\n\ninterface MatchSuggestion {\n leftId: string;\n rightId: string;\n score: number;\n ruleScores: { rule: string; score: number }[];\n}\n```\n\nReturns an array of suggestions sorted by score (highest first). Only includes matches above the page's `confidenceThreshold`.\n\n## Next Steps\n\n- **[Schema Format Reference](/cms/schema-format)** — TypeScript types consumed by these components\n- **[Table Views](/cms/table-views)** — How DataTable and SpreadsheetTable are used\n- **[Inline Editing](/cms/inline-editing)** — SpreadsheetTable editing details"
|
|
79
|
-
},
|
|
80
|
-
"cms/connecting": {
|
|
81
|
-
"title": "Connecting",
|
|
82
|
-
"content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for non-admins.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view` CRUD** is gated on `userRole: [\"admin\"]` rather than org membership, so saved views can't be listed or modified without admin rights.\n- **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource CRUD endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `crud.access.roles` you defined.\n\nTo allow any authenticated user to access the CMS, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.\n\n## Multi-Tenant vs Single-Tenant\n\nThe CMS supports two authentication modes depending on your project's organization configuration.\n\n### Multi-Tenant (Default)\n\nIn multi-tenant mode, the CMS gates access behind organization membership:\n\n1. User logs in via Better Auth session\n2. CMS fetches the user's organization memberships\n3. If the user belongs to multiple organizations, an **org selector** is displayed\n4. Once an org is selected, the user's role within that org determines their CMS permissions\n\nThis is the default behavior for all Quickback projects.\n\n### Single-Tenant Mode\n\nWhen your project disables organizations (`features.organizations: false` in config), the compiler sets `singleTenant: true` in the schema registry. In this mode:\n\n- No org gate or org selector is shown\n- The user's role is read directly from `user.role` on the session\n- All data is unscoped (no `organizationId` filtering)\n\nSingle-tenant mode is useful for internal tools, personal projects, or apps that don't need multi-org isolation.\n\n## Next Steps\n\n- **[Table Views](/cms/table-views)** — Browse and Data Table view modes\n- **[Security](/cms/security)** — How roles, guards, and masking work in the CMS"
|
|
83
|
-
},
|
|
84
|
-
"cms/dashboard": {
|
|
85
|
-
"title": "Dashboard",
|
|
86
|
-
"content": "# Dashboard\n\nThe CMS dashboard is the home page you see when opening the admin interface. It provides an at-a-glance overview of your entire schema and quick navigation to any table.\n\n## Stats Grid\n\nThe top of the dashboard displays aggregate statistics across your entire schema:\n\n| Stat | Description |\n|------|-------------|\n| **Tables** | Total non-internal tables (excludes join tables and system tables) |\n| **Columns** | Total columns across all tables |\n| **Actions** | Total custom actions across all tables |\n| **Views** | Total named views across all tables |\n| **Masked Fields** | Total fields with masking rules |\n\n## Feature Cards\n\nBelow the stats grid, the dashboard displays a card for each feature group. Each card lists the feature's tables with metadata:\n\n- **Column count** — number of columns in the table\n- **Action count** — number of custom actions (shown with a lightning icon)\n- **View count** — number of named views (shown with an eye icon)\n- **Mask count** — number of masked fields (shown with a shield icon)\n\nClicking a table name navigates directly to that table's browse view.\n\n## Role Context\n\nThe dashboard shows the current user's role. In demo mode, this reflects the role selected in the role switcher. In live mode, it shows the role from the authenticated session.\n\n## Internal Tables\n\nTables marked as `internal: true` in the schema registry (those without a `defineTable()` resource config) are excluded from the dashboard. These are typically join tables or system tables that don't need direct admin access.\n\n## Next Steps\n\n- **[Table Views](/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/cms/pages)** — Multi-panel pages with matching and drag-drop"
|
|
87
|
-
},
|
|
88
|
-
"cms": {
|
|
89
|
-
"title": "Quickback CMS",
|
|
90
|
-
"content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (admin-only by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for non-admins.\n2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"admin\"` and returns `403` otherwise.\n4. **`custom_view` CRUD** — the CMS-internal saved-views table is gated on `userRole: [\"admin\"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.\n\nYour resource CRUD endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `crud.access.roles` you defined.\n\nTo allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\n### Optional: Skip SPA rebuild\n\nAfter the first compile, you can skip rebuilding the CMS SPA on subsequent compiles:\n\n```typescript\ncms: { build: false }\n```\n\nThis is useful when you're iterating on API features and don't need to rebuild the CMS UI each time — it saves significant compile time. Set `build: true` (or omit it) when you need to update the CMS assets.\n\n### Optional: Custom output directory\n\n```typescript\ncms: { outputDir: \"my-custom-path/cms\" }\n```\n\nThis changes where the compiled CMS assets are placed (relative to project root), instead of the default `src/apps/cms/`.\n\n## Next Steps\n\n- **[Schema Registry](/cms/schema-registry)** — Understand the JSON format the compiler generates\n- **[Connecting](/cms/connecting)** — Demo mode, live mode, CLI command, and auth modes\n- **[Dashboard](/cms/dashboard)** — Stats grid and feature navigation\n- **[Table Views](/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/cms/pages)** — Split-panel layouts, matching engine, and drag-drop\n- **[Inline Editing](/cms/inline-editing)** — Spreadsheet-style editing and FK typeahead\n- **[Security](/cms/security)** — How the CMS enforces all four security layers\n- **[Actions](/cms/actions)** — Custom actions with input forms, access filtering, and CMS metadata\n- **[Schema Format Reference](/cms/schema-format)** — Full TypeScript types for schema-registry.json\n- **[Components Reference](/cms/components)** — All CMS components and their props"
|
|
91
|
-
},
|
|
92
|
-
"cms/inline-editing": {
|
|
93
|
-
"title": "Inline Editing",
|
|
94
|
-
"content": "# Inline Editing\n\nThe CMS provides spreadsheet-style inline editing in Data Table mode, plus auto-generated create and edit forms in the record detail view. All editable fields are determined from your table's guard configuration.\n\n## Spreadsheet Editing\n\nIn Data Table mode, every editable cell becomes an inline editor. Select a cell, start typing, and the value is saved automatically when you move to another cell or press Enter.\n\n### Editable Fields\n\nThe CMS determines which fields are editable from the table's guards:\n\n- **`guards.updatable`** fields are editable in existing records\n- **`guards.createable`** fields are editable in new record forms\n- **`guards.immutable`** fields are locked after creation (shown as disabled in edit mode)\n- **`guards.protected`** fields can only be changed via actions (marked \"Updated via actions only\")\n\nIf a table has no explicit guard config, the CMS falls back to making all non-system columns editable (excluding `id`, audit fields, `organizationId`, and `deletedAt`).\n\n## Cell Types\n\nEach column type gets a specialized editor:\n\n### Text\n\nStandard text input. Type freely and press Enter or Tab to save.\n\n### Number\n\nNumeric input with step controls. Supports decimal values (step `0.01` for currency fields). The CMS detects money fields from column names containing `amount`, `total`, `price`, `cost`, `balance`, `rate`, etc.\n\n### Boolean\n\nA Yes/No dropdown. Click to toggle between the two values.\n\n### FK Typeahead\n\nForeign key columns (ending in `Id`) get a typeahead dropdown with server-side search:\n\n- **Debounced search** — Queries are debounced at 200ms to avoid flooding the API\n- **Server-side filtering** — Sends `?search=query&pageSize=20` to the FK target table's list endpoint\n- **Keyboard navigation** — Arrow keys to navigate options, Enter to select, Escape to close\n- **Auto-loads initial options** — Opens with the first 20 records sorted by display column\n- **Display labels** — Shows the target table's display column value (e.g., \"John Smith\" instead of `usr_abc123`)\n\nThe FK target table is derived by stripping the `Id` suffix from the column name. For example, `contactId` searches the `contact` table, and `accountCodeId` searches the `accountCode` table.\n\n### Enum / Select\n\nColumns with `validation.enum` render as a select dropdown with all allowed values.\n\n## Display Labels\n\nFK cells in the table view show human-readable names instead of raw IDs. The API enriches list responses with `_label` fields:\n\n```\ncontactId: \"cnt_abc123\" → displays \"Acme Corporation\"\nprojectId: \"prj_xyz789\" → displays \"Beach House Renovation\"\n```\n\nThe label comes from the referenced table's display column (auto-detected from `name`, `title`, `code`, etc.). This works in both Table mode and Data Table mode.\n\n## Keyboard Shortcuts\n\n| Shortcut | Action |\n|----------|--------|\n| Arrow keys | Navigate between cells |\n| Tab | Move to next editable cell |\n| Shift + Tab | Move to previous editable cell |\n| Enter | Start editing / confirm edit and move down |\n| Escape | Cancel current edit / deselect cell |\n| Type any character | Start editing the selected cell |\n\n### Navigation Flow\n\n1. **Select** a cell by clicking or using arrow keys\n2. **Edit** by pressing Enter, Tab, or just typing\n3. **Save** by pressing Enter (moves down), Tab (moves right to next editable), or clicking elsewhere\n4. **Cancel** by pressing Escape (reverts to previous value)\n\nWhen you press Tab, the cursor skips non-editable cells and jumps to the next editable cell in the row. At the end of a row, it wraps to the first editable cell of the next row.\n\n## Record Detail View\n\nClicking a row in Table mode navigates to the record detail view. Fields are automatically grouped by type:\n\n| Group | Fields Included |\n|-------|----------------|\n| Identity | `name`, `code`, `status`, `title`, `companyName`, fields ending in `Type` or `Status` |\n| Contact Info | `email`, `phone`, `mobile`, `website`, `address1`, `address2`, `city`, `state`, `zip`, `country` |\n| Financial | Money fields, fields with `Percent`, `Rate`, `Markup`, `Discount`, `Currency`, `exchange` |\n| References | All FK columns (ending in `Id`, excluding `id` and `organizationId`) |\n| Settings | Boolean fields |\n| Dates | Date/time fields |\n| Audit | `createdAt`, `createdBy`, `modifiedAt`, `modifiedBy` |\n| Other | Remaining ungrouped fields |\n\nEach group is rendered as a card with the group label as a header. Fields display formatted values — dates are localized, money shows currency formatting, booleans render as Yes/No badges, enums use color-coded pills, and FK references are clickable links to the target record.\n\n## Auto-Generated Forms\n\nThe CMS generates create and edit forms from the table's guard configuration:\n\n### Create Form\n\nShows all fields listed in `guards.createable`. Required fields (notNull without a default) are marked with a red asterisk. Validation rules from the schema (min/max length, enum constraints, email format) are enforced client-side.\n\n### Edit Form\n\nShows all fields listed in `guards.updatable`. Additionally:\n\n- **Immutable fields** appear as disabled inputs with a lock icon\n- **Protected fields** appear as disabled inputs with the note \"Updated via actions only\"\n- **Validation** is applied on submit, with error messages shown per field\n\n### Field Input Types\n\nThe auto-form selects the appropriate input control based on column type and validation:\n\n| Detection | Input Type |\n|-----------|-----------|\n| `mode: \"boolean\"` | Checkbox |\n| `validation.enum` present | Select dropdown |\n| Column name matches date pattern | Date/time picker |\n| Column name matches money pattern | Number input (step 0.01) |\n| Column name matches URL pattern | URL input |\n| `validation.email: true` | Email input |\n| `type: \"integer\"` or `type: \"real\"` | Number input |\n| Long text (description, notes) | Textarea |\n| Default | Text input |\n\n## Next Steps\n\n- **[Table Views](/cms/table-views)** — Browse mode and view projections\n- **[Security](/cms/security)** — How guards control editability\n- **[Actions](/cms/actions)** — Trigger actions from the detail view"
|
|
95
|
-
},
|
|
96
|
-
"cms/pages": {
|
|
97
|
-
"title": "Custom Pages",
|
|
98
|
-
"content": "# Custom Pages\n\nCustom pages extend the CMS beyond standard table views. Define split-panel layouts, matching rules for record reconciliation, drag-and-drop interactions, and page-level actions — all from a single `definePage()` call.\n\n## Defining a Page\n\nPages are defined in your feature directory under a `pages/` folder:\n\n```\nquickback/definitions/features/\n banking/\n bank-accounts.ts # One table per file — any filename\n bank-transactions.ts\n actions.ts\n pages/\n bank-reconciliation.ts\n```\n\nEach page file exports a `definePage()` call:\n\n```typescript title=\"features/banking/pages/bank-reconciliation.ts\"\n\nexport default definePage({\n slug: 'bank-reconciliation',\n title: 'Bank Reconciliation',\n description: 'Match bank transactions to ledger entries',\n icon: 'landmark',\n feature: 'banking',\n\n access: { roles: ['owner', 'admin'] },\n\n dataSources: {\n bankTransactions: {\n table: 'bankTransaction',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n ledgerEntries: {\n table: 'ledgerEntry',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'memo', 'amount'],\n },\n },\n\n layout: {\n type: 'split-panel',\n panels: [\n {\n id: 'bank',\n title: 'Bank Transactions',\n dataSource: 'bankTransactions',\n position: 'left',\n features: ['drag-source'],\n },\n {\n id: 'ledger',\n title: 'Ledger Entries',\n dataSource: 'ledgerEntries',\n position: 'right',\n features: ['drop-target'],\n },\n ],\n },\n\n matching: {\n enabled: true,\n confidenceThreshold: 0.5,\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5,\n condition: {\n left: 'bankTransactions.amount',\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n {\n name: 'Date Proximity',\n weight: 0.3,\n condition: {\n left: 'bankTransactions.date',\n right: 'ledgerEntries.date',\n operator: 'within-days',\n value: 7,\n },\n },\n {\n name: 'Description Match',\n weight: 0.2,\n condition: {\n left: 'bankTransactions.description',\n right: 'ledgerEntries.memo',\n operator: 'fuzzy-match',\n },\n },\n ],\n },\n\n pageActions: {\n reconcile: {\n table: 'bankTransaction',\n action: 'reconcile',\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this bank transaction to the selected ledger entry?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n },\n});\n```\n\n## Data Sources\n\nEach page declares one or more named data sources that bind to tables in your schema:\n\n```typescript\ndataSources: {\n bankTransactions: {\n table: 'bankTransaction', // Table name from your schema\n defaultFilters: { status: 'pending' }, // Applied on load\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `table` | `string` | Table name to query (required) |\n| `defaultFilters` | `Record<string, unknown>` | Filters applied on initial load |\n| `defaultSort` | `{ field, order }` | Default sort column and direction |\n| `displayColumns` | `string[]` | Columns shown in the panel (defaults to `[\"id\"]`) |\n\n## Layout\n\nPages use a layout configuration to arrange panels. Currently the only layout type is `split-panel`:\n\n```typescript\nlayout: {\n type: 'split-panel',\n panels: [\n { id: 'bank', title: 'Bank Txs', dataSource: 'bankTransactions', position: 'left', features: ['drag-source'] },\n { id: 'ledger', title: 'Ledger', dataSource: 'ledgerEntries', position: 'right', features: ['drop-target'] },\n ],\n}\n```\n\n### Panel Features\n\nPanels can enable interactive features:\n\n| Feature | Description |\n|---------|-------------|\n| `drag-source` | Rows in this panel can be dragged |\n| `drop-target` | Rows in this panel accept drops |\n\nWhen a row is dragged from one panel and dropped onto a row in the other panel, the first page action is triggered with both records as context.\n\n## Matching Engine\n\nThe matching engine compares records across two panels and computes confidence scores for potential matches. Matched rows display a colored confidence badge.\n\n### Rules\n\nEach rule defines a comparison between fields from two data sources:\n\n```typescript\nmatching: {\n enabled: true,\n confidenceThreshold: 0.5, // Minimum score to show (0-1)\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5, // Weight in final score (0-1)\n condition: {\n left: 'bankTransactions.amount', // dataSourceName.fieldName\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n ],\n}\n```\n\n### Operators\n\n| Operator | Description | Returns |\n|----------|-------------|---------|\n| `abs-equals` | Absolute values are equal | `1.0` if match, `0` otherwise |\n| `within-days` | Dates are within N days | `1 - (daysDiff / maxDays)`, clamped to 0 |\n| `fuzzy-match` | Word overlap between strings | Overlap ratio (0-1) |\n\nThe `within-days` operator uses the `value` parameter to set the maximum number of days (defaults to 7).\n\n### Confidence Scoring\n\nThe final confidence score is the weighted average of all rule scores:\n\n```\nscore = sum(ruleScore * ruleWeight) / sum(ruleWeights)\n```\n\nOnly matches above `confidenceThreshold` are shown. Confidence badges are color-coded:\n\n| Score | Color |\n|-------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n## Page Actions\n\nPage actions trigger table actions using data from both the source (dragged) and target (dropped-on) records:\n\n```typescript\npageActions: {\n reconcile: {\n table: 'bankTransaction', // Target table for the action\n action: 'reconcile', // Action name on that table\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this transaction?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n}\n```\n\n### Input Mapping\n\nInput mapping resolves field references from the source and target records into the action's input fields. The format is `\"dataSourceName.$fieldName\"`:\n\n- `bankTransactions.$id` — resolves to the `id` field of the dragged record from the `bankTransactions` data source\n- `ledgerEntries.$amount` — resolves to the `amount` field of the drop-target record from the `ledgerEntries` data source\n\nThe `$` prefix denotes a field reference on the record. The data source name determines which record (source or target) to read from.\n\n## Access Control\n\nRestrict page access by role:\n\n```typescript\naccess: { roles: ['owner', 'admin'] }\n```\n\nWhen set, only users with the specified roles can view the page. The page link is hidden from the sidebar for unauthorized users.\n\n## Sidebar Navigation\n\nCustom pages appear in the CMS sidebar under their feature group. Each page is listed alongside the feature's tables, making them easily discoverable.\n\n## Validation\n\nThe compiler validates page definitions at compile time:\n\n- `slug` must start with a lowercase letter and contain only lowercase letters, digits, and hyphens\n- At least one data source is required\n- Every panel's `dataSource` must reference a declared data source\n- Matching rule weights must be between 0 and 1\n- `confidenceThreshold` must be between 0 and 1\n\n## Next Steps\n\n- **[Dashboard](/cms/dashboard)** — The CMS home page with schema stats\n- **[Components Reference](/cms/components)** — Page-related component details\n- **[Schema Format Reference](/cms/schema-format)** — PageMeta type definition"
|
|
99
|
-
},
|
|
100
|
-
"cms/record-layouts": {
|
|
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: [{ 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
|
-
},
|
|
104
|
-
"cms/schema-format": {
|
|
105
|
-
"title": "Schema Format Reference",
|
|
106
|
-
"content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n singleTenant?: boolean;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Per-operation (create, read, update, delete) access config |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions for this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, successMessage, onSuccess, order) |\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/cms/components)** — All CMS React components"
|
|
107
|
-
},
|
|
108
|
-
"cms/schema-registry": {
|
|
109
|
-
"title": "Schema Registry",
|
|
110
|
-
"content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"singleTenant\": false,\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `singleTenant` | `boolean?` | When `true`, no organization layer |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; // Per-operation access rules\n guards: {\n createable: string[]; // Fields allowed on create\n updatable: string[]; // Fields allowed on update\n immutable: string[]; // Fields locked after creation\n protected: Record<string, string[]>; // Fields only updatable via actions\n };\n masking: Record<string, MaskingRule>; // Per-field masking rules\n views: Record<string, ViewConfig>; // Named column projections\n validation: Record<string, ValidationRule>; // Per-field validation\n actions: ActionMeta[]; // Available actions for this table\n displayColumn?: string; // Human-readable label column\n internal?: boolean; // Hidden from CMS sidebar when true\n}\n```\n\n## ColumnMeta\n\nEach column in the `columns` array:\n\n```typescript\ninterface ColumnMeta {\n name: string; // Property name (camelCase)\n dbName: string; // SQL column name (snake_case)\n type: \"text\" | \"integer\" | \"real\" | \"blob\"; // SQLite type\n mode?: \"boolean\"; // When an integer represents a boolean\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string; // Target table name for FK columns\n}\n```\n\nThe compiler automatically includes audit fields (`id`, `organizationId`, `createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`) at the beginning of every table's column list.\n\n### fkTarget — FK Resolution\n\nColumns ending in `Id` may have a `fkTarget` property indicating which table they reference. This is resolved in priority order:\n\n1. **Explicit `references`** — from your `defineTable()` config (highest priority)\n2. **Drizzle `.references()`** — parsed from schema source code\n3. **Convention** — strip `Id` suffix, match table name directly\n\n```json\n{\n \"name\": \"vendorId\",\n \"type\": \"text\",\n \"fkTarget\": \"contact\"\n}\n```\n\nThe CMS uses `fkTarget` to render typeahead/lookup inputs that search the correct table instead of showing raw IDs.\n\n## Input Hints\n\nTables with `inputHints` configured in `defineTable()` include an `inputHints` map in their metadata:\n\n```json\n{\n \"name\": \"invoice\",\n \"inputHints\": {\n \"status\": \"select\",\n \"sortOrder\": \"radio\",\n \"isPartialPaymentDisabled\": \"checkbox\",\n \"headerMessage\": \"textarea\",\n \"description\": \"richtext\"\n }\n}\n```\n\nThe CMS reads these hints to render the appropriate form control for each field. The `\"richtext\"` hint renders a tiptap editor in edit mode and formatted HTML in view mode. See [Input Hints](/compiler/definitions/schema#input-hints) for the full list of supported values.\n\n## Display Column\n\nThe `displayColumn` field tells the CMS which column to use as a human-readable label for a record. This is used in:\n\n- FK typeahead dropdowns (showing names instead of IDs)\n- Record titles in detail views\n- Breadcrumb labels\n\n### Auto-Detection\n\nIf you don't explicitly set `displayColumn` in your resource config, the compiler auto-detects it by scanning column names in priority order:\n\n1. `name`\n2. `title`\n3. `label`\n4. `headline`\n5. `subject`\n6. `code`\n7. `displayName`\n8. `fullName`\n9. `description`\n\nThe first match wins. If no candidate matches, the table has no display column and the CMS falls back to showing IDs.\n\n### Explicit Config\n\nSet it explicitly in your table definition:\n\n```typescript\nexport default defineTable(contacts, {\n displayColumn: \"companyName\",\n // ...\n});\n```\n\n## FK Label Resolution\n\nWhen a table has foreign key columns (ending in `Id`), the API enriches list responses with `_label` fields. For example, a `roomTypeId` column gets a corresponding `roomType_label` field containing the display column value from the referenced table.\n\nThe CMS uses these `_label` fields to show human-readable names in table cells and FK typeahead dropdowns instead of raw UUIDs.\n\n```\nroomTypeId: \"rt_abc123\" → displayed as \"Master Bedroom\"\naccountCodeId: \"ac_xyz789\" → displayed as \"4100 - Revenue\"\n```\n\nThe FK target table is resolved from the `fkTarget` property on each column. For simple cases like `roomTypeId` → `roomType`, the compiler auto-detects it. For non-obvious mappings (e.g., `vendorId` → `contact`), use explicit [`references`](/compiler/definitions/schema#references) in your `defineTable()` config.\n\n## Pages\n\nWhen features include `definePage()` files (in `features/{name}/pages/`), the compiler includes them in the registry under two fields:\n\n- **`pages`** — Map of page slug to full `PageMeta` object (data sources, layout, matching rules, page actions)\n- **`pagesByFeature`** — Map of feature name to array of page slugs belonging to that feature\n\nThe CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/cms/pages) for the full `definePage()` API.\n\n## Single-Tenant Mode\n\nWhen `singleTenant` is `true` in the registry (set when the project config has `features.organizations: false`), the CMS skips the organization gate and reads the user's role directly from `user.role` on the session instead of from organization membership.\n\n## Next Steps\n\n- **[Connecting](/cms/connecting)** — Demo mode vs. live mode setup\n- **[Schema Format Reference](/cms/schema-format)** — Full TypeScript types"
|
|
111
|
-
},
|
|
112
|
-
"cms/security": {
|
|
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## CMS Access (admin-only by default)\n\nThe CMS is restricted to Better Auth platform admins (`user.role === \"admin\"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach 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 redirects the user to `/account/profile`.\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
|
-
},
|
|
116
|
-
"cms/table-views": {
|
|
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\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"
|
|
8
|
+
"compiler/claude-code-skill": {
|
|
9
|
+
"title": "AI Developer Tools",
|
|
10
|
+
"content": "Build Quickback apps faster with AI. The Quickback CLI ships with an MCP server, Claude Code skill, and Cursor IDE rules — so any AI tool can help you write security configurations, define features, and understand your project.\n\n## Quick Install\n\n```bash\n# Install the CLI (includes all AI tools)\nnpm install -g @quickback-dev/cli\n\n# Claude Code skill\nquickback claude install\n\n# Cursor IDE rules\nquickback cursor install\n\n# MCP server (configure in your AI tool, see below)\nquickback mcp\n```\n\n## MCP Server\n\nThe MCP server makes Quickback documentation and project context available to **any** MCP-compatible AI tool.\n\n### Configuration\n\nAdd to your AI tool's MCP config:\n\n```json\n{\n \"mcpServers\": {\n \"quickback\": {\n \"command\": \"npx\",\n \"args\": [\"@quickback-dev/cli\", \"mcp\"]\n }\n }\n}\n```\n\n| Tool | Config File |\n|------|-------------|\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) |\n| Cursor | `.cursor/mcp.json` in your project |\n| VS Code | `.vscode/mcp.json` in your project |\n\n### Available Tools\n\n| Tool | Description |\n|------|-------------|\n| `list_topics` | List all 100+ documentation topics |\n| `get_doc` | Get a specific doc (supports fuzzy matching — e.g., \"firewall\") |\n| `search_docs` | Search documentation by keyword |\n| `read_config` | Read your project's `quickback.config.ts` |\n| `list_features` | List features and their table files |\n| `read_feature` | Read a specific feature's source code |\n| `read_schema_registry` | Read the compiled `schema-registry.json` |\n\nAll documentation topics are also registered as MCP resources at `quickback://docs/{topic}`.\n\n## Claude Code Skill\n\n### Installation\n\nInstall via the CLI (recommended):\n\n```bash\nquickback claude install --global # All projects (~/.claude/)\nquickback claude install --local # This project only\n```\n\nOr install the standalone npm package:\n\n```bash\nnpm install -g @quickback-dev/skill\n```\n\nOr when creating a new project, the skill is included automatically:\n\n```bash\nnpx @quickback-dev/cli create cloudflare my-app\n```\n\n## What You Get\n\nWhen you install the Quickback skill, you get:\n\n### Quickback Skill\n\nClaude understands Quickback concepts and can answer questions about:\n\n- **Security layers** - Firewall, Access, Guards, Masking, Actions\n- **Common patterns** - Multi-tenant, owner-scoped, hierarchical access\n- **Best practices** - Field protection, role-based access, PII handling\n- **Database dialects** - SQLite/D1, PostgreSQL, MySQL syntax\n\n### Quickback Specialist Agent\n\nClaude also gets a specialized agent that activates automatically when you're:\n\n- Creating new resources with schemas and security configurations\n- Configuring security layers (Firewall, Access, Guards, Masking)\n- Defining actions for business logic\n- Debugging configuration issues\n\nThe agent generates complete, working code in your `quickback/features/` directory.\n\n## Usage\n\n### Let Claude help automatically\n\nJust describe what you need. Claude will use Quickback knowledge when relevant:\n\n```\n\"Create a tasks resource where users can only see their own tasks,\nbut admins can see all tasks in the organization\"\n```\n\n### Invoke directly\n\nUse `/quickback` to explicitly activate the skill:\n\n```\n/quickback How do I configure soft delete?\n```\n\n## Example Conversations\n\n### Building a New Resource\n\n**You:** \"I need a resource for invoices. Users should only see invoices from their organization. The status field should only be changeable through approve/reject actions. Mask the customer email for non-admins.\"\n\n**Claude:** Creates complete configuration with:\n- Firewall scoped to organization\n- Protected status field with approve/reject actions\n- Email masking with admin bypass\n- Appropriate guards for createable/updatable fields\n\n### Understanding Existing Code\n\n**You:** \"Explain what this firewall configuration does\"\n\n**Claude:** Breaks down the WHERE clauses, explains the security implications, and identifies potential issues.\n\n### Debugging Configuration\n\n**You:** \"My users can see records from other organizations. What's wrong?\"\n\n**Claude:** Analyzes your firewall setup, checks for `exception: true` or missing organization scope, and suggests fixes.\n\n## What Claude Knows\n\n### Security Layers\n\n| Layer | What Claude Helps With |\n|-------|------------------------|\n| **Firewall** | Data isolation patterns, WHERE clause generation, soft delete |\n| **Access** | Role-based permissions, record-level conditions, combining rules |\n| **Guards** | Field protection, createable vs updatable, immutable fields |\n| **Masking** | PII redaction, role-based visibility, mask types |\n| **Actions** | Custom endpoints, protected field updates, input validation |\n\n### Common Patterns\n\nClaude recognizes and can implement these patterns:\n\n- **Multi-tenant SaaS** - Organization-scoped with role hierarchy\n- **Personal data apps** - Owner-scoped resources\n- **Hierarchical access** - Admins see all, users see own\n- **Public resources** - Reference data, system tables\n- **Workflow resources** - Status fields with action-based transitions\n\n### Database Support\n\nClaude generates correct syntax for your database:\n\n```typescript\n// SQLite / Cloudflare D1\ncreatedAt: integer('created_at', { mode: 'timestamp' })\n\n// PostgreSQL / Supabase\ncreatedAt: timestamp('created_at').defaultNow()\n\n// MySQL\ncreatedAt: timestamp('created_at')\n```\n\n## Tips for Best Results\n\n**Be specific about security requirements:**\n\n```\n// Good\n\"Users can only see their own tasks. Admins can see all tasks\nin the organization. The priority field can only be set by admins.\"\n\n// Less helpful\n\"Create a tasks resource\"\n```\n\n**Describe your user types:**\n\n```\n\"We have three roles: admin (full access), manager (can approve),\nand member (can only edit their own records)\"\n```\n\n**Mention sensitive fields:**\n\n```\n\"The ssn field should be masked for everyone except HR admins\"\n```\n\n## Common Tasks\n\n### Create a complete resource\n\n```\n\"Create an employees resource for a multi-tenant HR app. Include\nfields for name, email, department, salary. Mask salary for\nnon-admins. Only HR can create/delete employees.\"\n```\n\n### Add an action to existing resource\n\n```\n\"Add an 'approve' action to the expenses resource that sets\nstatus to 'approved' and records the approver\"\n```\n\n### Configure access control\n\n```\n\"Update the projects resource so managers can edit any project\nin their organization, but members can only edit projects they created\"\n```\n\n### Set up masking\n\n```\n\"Add masking to the customers resource: email partially masked,\nphone last 4 digits only, SSN fully redacted except for finance role\"\n```\n\n## Troubleshooting\n\n### Skill not found\n\nVerify the skill is installed:\n\n```bash\nls ~/.claude/skills/quickback/SKILL.md\n```\n\nIf missing, reinstall:\n\n```bash\nnpm install -g @quickback-dev/skill\n```\n\n### Claude doesn't understand Quickback\n\nMake sure the skill file exists and Claude Code is restarted. You can also invoke it directly with `/quickback` to force it to load.\n\n### Generated code has errors\n\nRun `quickback compile` to validate. Share the error messages with Claude for fixes.\n\n## Cursor IDE Rules\n\nCursor rules provide Quickback context when editing `quickback/**/*.ts` files.\n\n### Installation\n\n```bash\nquickback cursor install\n```\n\nThis installs `quickback.mdc` to `.cursor/rules/` in your project. Commit this file so your team gets the rules automatically.\n\n### Management\n\n```bash\nquickback cursor status # Check installation\nquickback cursor update # Update to latest version\nquickback cursor remove # Remove the rules\n```\n\n## Updating\n\nTo update all AI tools to the latest version:\n\n```bash\nnpm update -g @quickback-dev/cli\nquickback claude update # Update Claude skill\nquickback cursor update # Update Cursor rules\n```\n\nThe MCP server always uses the latest installed version automatically.\n\n## Resources\n\n- [Getting Started with AI Tools](/compiler/getting-started/claude-code) - Setup guide\n- [Getting Started](/compiler/getting-started) - Get your first Quickback project running\n- [Definitions Overview](/compiler/definitions) - Understand the security layer model\n- [npm package](https://www.npmjs.com/package/@quickback-dev/cli) - CLI package\n\n## Feedback\n\nFound an issue with the AI tools integration?\n\n- [GitHub Issues](https://github.com/kardoe/quickback/issues)\n- [Quickback Documentation](https://docs.quickback.dev)"
|
|
119
11
|
},
|
|
120
12
|
"compiler/cloud-compiler/authentication": {
|
|
121
13
|
"title": "Authentication",
|
|
@@ -151,11 +43,11 @@ export const DOCS = {
|
|
|
151
43
|
},
|
|
152
44
|
"compiler/config/domains": {
|
|
153
45
|
"title": "Multi-Domain Architecture",
|
|
154
|
-
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, and Admin panel on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, or Admin, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll five domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n auth: { password: true, admin: true },\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com` and `admin.example.com` — no additional setup needed.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/cms) — Schema-driven admin interface\n- [Account UI](/account-ui) — Authentication and account management"
|
|
46
|
+
"content": "A single Quickback-compiled Cloudflare Worker can serve your API, CMS, Account UI, and Admin panel on separate custom domains. The compiler generates hostname-based routing so each domain serves the right content.\n\n## How It Works\n\nWhen you configure custom domains for CMS, Account, or Admin, the compiler:\n\n1. Adds `custom_domain` routes to `wrangler.toml`\n2. Generates hostname-based middleware in the Worker\n3. Auto-configures cross-subdomain cookies for shared authentication\n4. Auto-infers a unified `quickback.{baseDomain}` fallback domain\n\nAll five domains point to the **same Worker** — there's only one deployment.\n\n## Domain Types\n\n| Domain | Config | Serves | API Routes |\n|--------|--------|--------|-----------|\n| `api.example.com` | `providers.runtime.config.routes` | API only | All |\n| `cms.example.com` | `cms: { domain }` | CMS SPA | Blocked (404) |\n| `auth.example.com` | `account: { domain }` | Account SPA | Pass-through |\n| `admin.example.com` | `account: { adminDomain }` | Account SPA | Pass-through |\n| `quickback.example.com` | Auto-inferred | Everything | All |\n\n### CMS Domain\n\nServes the CMS SPA at root (`/`). API routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) return 404 — preventing direct API access on the CMS domain.\n\n### Account Domain\n\nServes the Account SPA at root (`/`). API and auth routes pass through to the Worker so authentication flows work directly on this domain.\n\n### Admin Domain\n\nIdentical behavior to the Account domain — serves the same Account SPA at root. The Account SPA's client-side router handles the `/admin` route, restricting access to users with the `admin` role.\n\n### Unified Domain\n\nThe compiler auto-infers a `quickback.{baseDomain}` domain from your configured custom domains. For example, if you have `cms.example.com`, it creates `quickback.example.com`.\n\nOn this domain, **everything is available** on a single origin:\n\n| Path | Content |\n|------|---------|\n| `/` | Redirects to `/cms/` |\n| `/cms/` | CMS SPA |\n| `/account/` | Account SPA |\n| `/api/v1/...` | API routes |\n| `/auth/...` | Auth routes |\n| `/admin/...` | Admin API routes |\n| `/storage/...` | File storage |\n| `/health` | Health check |\n| `/openapi.json` | OpenAPI spec |\n\nThe unified domain is useful for development and debugging. You can override it with an explicit `domain` field in your config.\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n auth: { password: true, admin: true },\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n // ...database, auth\n },\n};\n```\n\nThis generates the following `wrangler.toml` routes:\n\n```toml\nroutes = [\n { pattern = \"api.example.com\", custom_domain = true },\n { pattern = \"cms.example.com\", custom_domain = true },\n { pattern = \"auth.example.com\", custom_domain = true },\n { pattern = \"admin.example.com\", custom_domain = true },\n { pattern = \"quickback.example.com\", custom_domain = true }\n]\n```\n\n## Cross-Subdomain Authentication\n\nWhen two or more custom domains share a parent domain (e.g., `cms.example.com` + `auth.example.com`), the compiler automatically configures Better Auth for cross-subdomain cookie sharing:\n\n- Sets `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`\n- Sets `sameSite: 'none'` and `secure: true` on auth cookies\n\nThis means a user who logs in on `auth.example.com` is automatically authenticated on `cms.example.com` and `admin.example.com` — no additional setup needed.\n\n## Compile-Time Feature Gating\n\nWhen the compiler builds the Account SPA, it excludes route files for disabled features **before** the Vite build. This means disabled features never appear in the JavaScript bundle.\n\n| Feature Flag | Routes Excluded When `false` |\n|-------------|------------------------------|\n| `auth.organizations` | Dashboard, organization CRUD, org switching (`$slug`) |\n| `auth.passkey` | Passkey management and setup |\n| `auth.admin` | Admin panel routes |\n\nThis keeps bundle sizes minimal and prevents dead code in production. Users can't access disabled features even if they navigate to the URL directly — the routes don't exist in the build.\n\n## Hostname Routing Details\n\nThe compiler generates middleware that checks `new URL(c.req.url).hostname` on every request:\n\n**CMS domain** — Blocks API routes with 404. All other paths are mapped to the `/cms/` asset prefix and served with SPA fallback to `/cms/index.html`.\n\n**Account/Admin domain** — API and auth routes (`/api/`, `/auth/`, `/admin/`, `/storage/`, `/health`) pass through to Hono handlers. All other paths are mapped to the `/account/` asset prefix and served with SPA fallback to `/account/index.html`.\n\n**Unified domain** — No hostname filtering. CMS is served at `/cms/`, Account at `/account/`. Root (`/`) redirects to `/cms/`. API routes work at their standard paths.\n\n## Without Custom Domains\n\nIf you enable `cms` and `account` without custom domains, everything is served on a single domain:\n\n- CMS at `/cms/` (root `/` redirects to `/cms/`)\n- Account UI at `/account/`\n- API at `/api/v1/`\n- Auth at `/auth/`\n\nThis is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.\n\n## See Also\n\n- [Configuration](/compiler/config) — CMS and Account config options\n- [Output Structure](/compiler/config/output) — Generated file and directory layout\n- [CMS](/stack/cms) — Schema-driven admin interface\n- [Account UI](/stack/account-ui) — Authentication and account management"
|
|
155
47
|
},
|
|
156
48
|
"compiler/config": {
|
|
157
49
|
"title": "Configuration",
|
|
158
|
-
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects six audit fields (`createdAt`, `modifiedAt`, `deletedAt`, `createdBy`, `modifiedBy`, `deletedBy`) into every feature table. These drive soft-delete filtering, record-provenance queries, and the CMS audit panel.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/cms/connecting) for the full enforcement model. |\n\n## Account UI Configuration\n\nEmbed the [Account UI](/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are included in the Account UI bundle. Disabled features are excluded at compile time — their routes are removed before the Vite build, keeping bundle sizes minimal.\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `auth.password` | `boolean` | `true` | Email/password authentication |\n| `auth.emailOTP` | `boolean` | `false` | Email one-time password login |\n| `auth.passkey` | `boolean` | `false` | WebAuthn/FIDO2 passkey authentication |\n| `auth.signup` | `boolean` | `true` | Self-service account registration |\n| `auth.organizations` | `boolean` | `false` | Multi-tenant organization management (dashboard, invitations, roles) |\n| `auth.admin` | `boolean` | `false` | Admin panel for user management (requires Better Auth admin plugin) |\n| `auth.emailVerification` | `boolean` | `false` | Require email verification after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
50
|
+
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: { organizations: true },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ── Project ──\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ── Embedded UIs (CMS / Account) ──\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** — the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // ← lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template (`\"nextjs\"` is experimental) |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `features` | `object` | Feature flags — see [Single-Tenant Mode](/compiler/config/single-tenant) |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |\n| `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |\n| `dev` | `object` | Local development settings (`port`) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Disable Audit Field Injection\n\nBy default, Quickback auto-injects four **audit fields** (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) into every feature table, plus two **soft-delete fields** (`deletedAt`, `deletedBy`) into tables that use soft delete (the default delete mode). The audit fields drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nTo opt out project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema → Audit Fields](/compiler/definitions/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## CMS Configuration\n\nEmbed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.\n\n```typescript\n// Simple — embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"user\"` | Controls who can access the CMS. When `\"admin\"`, only users with `user.role === \"admin\"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |\n\n## Account UI Configuration\n\nEmbed the [Account UI](/stack/account-ui) in your compiled Worker. Provides login, signup, profile management, organization management, and admin — all built from your config at compile time.\n\nFor post-signup logic — auto-provisioning a workspace, gating signup, setting an active organization — drop a file in `quickback/hooks/`. See [Auth Hooks](/stack/account-ui/hooks).\n\n```typescript\n// Simple — embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA — the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application — where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are included in the Account UI bundle. Disabled features are excluded at compile time — their routes are removed before the Vite build, keeping bundle sizes minimal.\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `auth.password` | `boolean` | `true` | Email/password authentication |\n| `auth.emailOTP` | `boolean` | `false` | Email one-time password login |\n| `auth.passkey` | `boolean` | `false` | WebAuthn/FIDO2 passkey authentication |\n| `auth.signup` | `boolean` | `true` | Self-service account registration |\n| `auth.organizations` | `boolean` | `false` | Multi-tenant organization management (dashboard, invitations, roles) |\n| `auth.admin` | `boolean` | `false` | Admin panel for user management (requires Better Auth admin plugin) |\n| `auth.emailVerification` | `boolean` | `false` | Require email verification after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | — | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | — | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config — no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) — uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES — requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n\n…whenever any auth surface needs to send mail — `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins — or you set the top-level `email: {…}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/compiler/config/providers) — Runtime, database, and auth options\n- [Variables](/compiler/config/variables) — Environment variables and flags\n- [Output](/compiler/config/output) — Generated file structure\n- [Single-Tenant Mode](/compiler/config/single-tenant) — Admin-only and public-facing apps without organizations\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains, hostname routing, and cross-subdomain auth"
|
|
159
51
|
},
|
|
160
52
|
"compiler/config/output": {
|
|
161
53
|
"title": "Output Structure",
|
|
@@ -179,7 +71,7 @@ export const DOCS = {
|
|
|
179
71
|
},
|
|
180
72
|
"compiler/definitions/actions": {
|
|
181
73
|
"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` (required) |\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\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nAction names must be unique within a feature — both `actions/foo.ts` and\n`actions/<table>/foo.ts` would collide on the same URL segment.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, auditFields, whereTransition }) {\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(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record`, `input`, and audit field types from the\n> rest of the action config.\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 async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\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 code |\n| `unsafe` | No | Unsafe raw DB mode. 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| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\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\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/advance.ts\n\nexport default defineAction({\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 async execute({ db, 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### Request Example\n\n```\nPOST /applications/app_123/advance\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. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\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### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\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 async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\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/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\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 async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\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\nasync execute({ 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\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\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 async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\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, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\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## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files 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// features/applications/actions/advance.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\n```\n\n**Path pattern from `features/{name}/actions/`:**\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 whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition 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// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ 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\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\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### 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\nasync execute({ 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\nasync execute({ 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 the table file (defineTable config)\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// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\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 async execute({ db, record, auditFields, whereTransition }) { /* … */ },\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### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\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 async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
74
|
+
"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` (required) |\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\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment.\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper that infers `record` and `input` types from the rest of the\n> action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\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 async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\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 code |\n| `unsafe` | No | Unsafe raw DB mode. 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| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\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\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/advance.ts\n\nexport default defineAction({\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 async execute({ db, 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### Request Example\n\n```\nPOST /applications/app_123/advance\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. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\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### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\n\nexport default defineAction({\n description: \"Generate trial balance report\",\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 async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\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/submit.ts\n\nexport default defineAction({\n description: \"Public contact form submission\",\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 async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\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\nasync execute({ 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\n// features/admin/actions/cross-tenant-report.ts\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\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 async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\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, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\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## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files 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// features/applications/actions/advance.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\n```\n\n**Path pattern from `features/{name}/actions/`:**\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 whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition 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// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()`.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\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### 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\nasync execute({ 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\nasync execute({ 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 the table file (defineTable config)\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// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\n\nexport default defineAction({\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 async execute({ db, record, whereTransition }) { /* … */ },\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### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\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 async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
183
75
|
},
|
|
184
76
|
"compiler/definitions/concepts": {
|
|
185
77
|
"title": "Glossary",
|
|
@@ -187,7 +79,7 @@ export const DOCS = {
|
|
|
187
79
|
},
|
|
188
80
|
"compiler/definitions/feature": {
|
|
189
81
|
"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: [{ 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## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](
|
|
82
|
+
"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## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).\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
83
|
},
|
|
192
84
|
"compiler/definitions/firewall": {
|
|
193
85
|
"title": "Firewall - Data Isolation",
|
|
@@ -199,7 +91,7 @@ export const DOCS = {
|
|
|
199
91
|
},
|
|
200
92
|
"compiler/definitions": {
|
|
201
93
|
"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: [{ 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"
|
|
94
|
+
"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](/stack/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](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/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](/stack/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](/stack/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
95
|
},
|
|
204
96
|
"compiler/definitions/masking": {
|
|
205
97
|
"title": "Masking - Field Redaction",
|
|
@@ -207,11 +99,11 @@ export const DOCS = {
|
|
|
207
99
|
},
|
|
208
100
|
"compiler/definitions/read": {
|
|
209
101
|
"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"
|
|
102
|
+
"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/targets/hono-api/using-the-api/views-api) — Calling views from clients"
|
|
211
103
|
},
|
|
212
104
|
"compiler/definitions/schema": {
|
|
213
105
|
"title": "Database Schema",
|
|
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 })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\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.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\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## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\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"
|
|
106
|
+
"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 })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.\n\n### Column Types\n\n| Builder | Drizzle equivalent | Zod type |\n|---------|---------------------|----------|\n| `q.text()` | `text(...)` | `z.string()` |\n| `q.url()` | `text(...)` | `z.string().url()` |\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.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).\n\n`q.url()` is `q.text()` plus `z.string().url()` at the validation edge, so `javascript:` / `data:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.\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 whenever the resource uses soft delete, which is the default — the `isNull(deletedAt)` 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. Add a `// @quickback-internal` marker so the compiler skips the \"no defineTable found\" warning:\n\n```typescript\n// quickback/features/jobs/interview-scores.ts\n\n// @quickback-internal — child table, no CRUD routes intentionally.\n\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. Without the `@quickback-internal` marker the compiler emits a warning per table, since the missing `defineTable` is more often a bug than a deliberate choice.\n\nThe compiler automatically injects the four **[audit fields](#audit-fields)** (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`), the soft-delete pair (`deletedAt`/`deletedBy`, when soft delete is enabled), 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 adds four audit columns to **every table** (including child/junction tables without `defineTable`) — never declare them in your schemas:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `createdAt` | timestamp | Set on insert |\n| `createdBy` | text | Actor that performed the insert (`ctx.userId`) |\n| `modifiedAt` | timestamp | Set on every insert and update |\n| `modifiedBy` | text | Actor that performed the latest insert/update (`ctx.userId`) |\n\nAudit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`) — they're always present, regardless of delete mode. See [Soft-Delete Fields](#soft-delete-fields) below.\n\nOpt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)\n\n### How auto-injection works (two layers)\n\n\"Auto-injection\" covers two distinct steps. Conflating them is the most common source of confusion:\n\n1. **Schema injection (compile-time)** — the compiler adds the four columns to every Drizzle table. Idempotent: if you've authored a column with the same name yourself, the compiler leaves yours alone.\n2. **Runtime injection (per-write)** — a Proxy around the request-context `db` (`createAuditDb`, generated to `src/lib/audit-wrapper.ts`) intercepts `.insert(...).values(...)` and `.update(...).set(...)` and writes the audit columns from `ctx.userId` and the actual write moment.\n\nThe runtime layer **hard-stamps** every audit field on every write. Caller-supplied values for `createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` are silently overwritten. This is intentional: the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.\n\n```ts\n// In a custom action handler — caller cannot fake audit attribution\nawait db.insert(records).values({\n id: createId(),\n status: 'active',\n createdBy: 'admin', // ← ignored; wrapper writes ctx.userId\n modifiedAt: '1999-01-01', // ← ignored; wrapper writes \"now\"\n});\n```\n\nWhat the caller is responsible for: `id` (the framework doesn't mint ids for you) and the domain fields.\n\nWhat the caller does *not* need to set: any of the four audit fields, ever.\n\n### Actors: who shows up in `createdBy` / `modifiedBy`\n\nThe wrapper writes whatever string is in `ctx.userId`. For user-driven requests this is the authenticated user's id — set by auth middleware before the handler runs. For non-user-driven entry points (inbound webhooks, cron, queue workers), you mint a synthetic actor id at the boundary so the audit log preserves provenance.\n\n**Inherit before you mint.** If a real user's request triggers cascades, hooks, or enqueues background jobs, every downstream write should carry that user's id — not a synthetic one. The cascade is part of the user's action. Only mint when there is genuinely no upstream user.\n\nWhen you do mint, use a single namespace and a stable convention:\n\n| Boundary | Actor id |\n|----------|----------|\n| Inbound webhook | `system:webhook-<provider>` (e.g. `system:webhook-stripe`) |\n| Scheduled / cron | `system:cron-<job>` (e.g. `system:cron-cleanup-stale`) |\n| Queue worker | `system:queue-<queue>` (e.g. `system:queue-embeddings-retry`) |\n| Quickback platform-internal write with no user upstream | `system:quickback` |\n| Out-of-band operator script | `system:script-<name>` |\n\nThe `system:` prefix marks \"not a real user\" — readable by anyone joining the audit columns to `users`, and cheap to filter on. Don't use `tenant:admin` or `quickback:admin`: those imply a human role nobody is actually playing. The tenant context is already on the row (in `organizationId`); the actor id is purely about *source*.\n\n### Failure mode: missing `ctx.userId`\n\nIf a write reaches the wrapper without a `ctx.userId`, the wrapper throws:\n\n```\naudit-wrapper: insert reached without ctx.userId.\nIf this is an intentional system-side write, use the unwrapped db directly.\n```\n\nTwo paths to fix it, depending on intent:\n\n- **Mint a synthetic actor** (preferred — preserves attribution) — populate `ctx.userId` with one of the conventions above before calling into your handler.\n- **Bypass the wrapper entirely** — use the unwrapped `createDb` instead of the request-context `db`. Use this only for migrations, schema repair, or backfill scripts where you genuinely don't want any audit attribution. The audit columns will fall back to DB defaults (`createdAt`/`modifiedAt` populate from `defaultNow()`; `createdBy`/`modifiedBy` end up `NULL`).\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\nThis turns off both layers — schema injection and the runtime wrapper.\n\n## Soft-Delete Fields\n\n`deletedAt` and `deletedBy` are **not** audit fields. They're a separate, per-table mechanism for soft delete:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `deletedAt` | timestamp | Set when the record is soft-deleted |\n| `deletedBy` | text | Actor that performed the soft delete (`ctx.userId`) |\n\nThe compiler injects them only when the resource uses soft delete — i.e. when neither `crud.delete.mode` nor `crud.batchDelete.mode` is explicitly `'hard'`. Soft is the default, so most tables get the columns. Tables with both delete paths set to `'hard'` skip them entirely, which also drops the `isNull(deletedAt)` predicate from the firewall WHERE clause.\n\n```typescript\n// soft delete (default) — table gets deletedAt + deletedBy\ncrud: { delete: {} }\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ncrud: { delete: { mode: 'hard' }, batchDelete: { mode: 'hard' } }\n```\n\n### Caller contract\n\nIn custom-action handlers, **passing `deletedAt` in `.set({})` is the signal** that this update is a soft delete. Any value works — the wrapper detects the field and overwrites both `deletedAt` and `deletedBy` with `now` and `ctx.userId`:\n\n```ts\nawait db.update(records)\n .set({ deletedAt: new Date() }) // signal — value is overwritten\n .where(eq(records.id, id));\n```\n\nYou don't set `deletedBy` yourself; the wrapper pairs it with the `deletedAt` signal.\n\n### Protected system fields\n\nThe audit and soft-delete columns are always protected from client input, even with `guards: false`:\n\n- `id` (when `generateId` is not `false`)\n- `createdAt`, `createdBy` *(audit — always present)*\n- `modifiedAt`, `modifiedBy` *(audit — always present)*\n- `deletedAt`, `deletedBy` *(soft-delete — present when delete mode allows soft)*\n\nProtection is enforced by the runtime wrapper — even if a request body passes one of these, it gets overwritten before the SQL is built.\n\n## Auto-Indexes\n\nThe compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.\n\n| Trigger | Index | Why |\n|---------|-------|-----|\n| Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |\n| Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |\n| Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |\n\nIndexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.\n\nYou can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.\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"
|
|
215
107
|
},
|
|
216
108
|
"compiler/definitions/validation": {
|
|
217
109
|
"title": "Validation",
|
|
@@ -223,11 +115,11 @@ export const DOCS = {
|
|
|
223
115
|
},
|
|
224
116
|
"compiler/getting-started/claude-code": {
|
|
225
117
|
"title": "AI Tools",
|
|
226
|
-
"content": "The Quickback CLI ships with built-in support for AI developer tools. One install gets you a Claude Code skill, Cursor IDE rules, and an MCP server that works with any AI tool.\n\n## MCP Server\n\nThe MCP server exposes Quickback documentation, project config, and feature definitions to any MCP-compatible AI tool — Claude Desktop, Cursor, VS Code Copilot, Windsurf, and more.\n\n### Setup\n\nAdd to your AI tool's MCP configuration:\n\n```json\n{\n \"mcpServers\": {\n \"quickback\": {\n \"command\": \"npx\",\n \"args\": [\"@quickback-dev/cli\", \"mcp\"]\n }\n }\n}\n```\n\n**Where to put this:**\n\n| Tool | Config File |\n|------|-------------|\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) |\n| Cursor | `.cursor/mcp.json` in your project root |\n| VS Code (Copilot) | `.vscode/mcp.json` in your project root |\n\n### What the MCP Server Provides\n\n**Documentation tools:**\n\n| Tool | Description |\n|------|-------------|\n| `list_topics` | List all 100+ documentation topics |\n| `get_doc` | Get a specific doc by name (supports fuzzy matching) |\n| `search_docs` | Search documentation content by keyword |\n\n**Project-aware tools** (when running inside a Quickback project):\n\n| Tool | Description |\n|------|-------------|\n| `read_config` | Read your `quickback.config.ts` |\n| `list_features` | List all features and their table files |\n| `read_feature` | Read the source code of a specific feature |\n| `read_schema_registry` | Read the compiled `schema-registry.json` |\n\nThe MCP server also registers every documentation topic as an MCP resource at `quickback://docs/{topic}`.\n\n---\n\n## Claude Code Skill\n\nThe Claude Code skill gives Claude deep knowledge of Quickback's security layers, patterns, and APIs. It also activates a specialist agent for generating complete feature definitions.\n\n### Install\n\n```bash\nquickback claude install\n```\n\n**Options:**\n\n| Flag | Description |\n|------|-------------|\n| `--global` | Install to `~/.claude/` (available in all projects) |\n| `--local` | Install to `./quickback/.claude/` (project-specific) |\n\n### Manage\n\n```bash\nquickback claude status # Check installation\nquickback claude update # Update to latest version\nquickback claude remove # Remove the skill\n```\n\n### What You Get\n\n- **Quickback Skill** — Claude understands `defineTable()`, `defineActions()`, security pillars, provider options, and the compiler workflow\n- **Specialist Agent** — Automatically activates when creating resources, configuring security, or defining actions. Generates complete, working code in your `quickback/features/` directory.\n\n---\n\n## Cursor IDE Rules\n\nCursor rules provide Quickback context directly to Cursor's AI, activated automatically when editing `quickback/**/*.ts` files.\n\n### Install\n\n```bash\nquickback cursor install\n```\n\nThis copies `quickback.mdc` to `.cursor/rules/` in your project. Consider committing this file to your repo so your team gets the rules automatically.\n\n### Manage\n\n```bash\nquickback cursor status # Check installation\nquickback cursor update # Update to latest version\nquickback cursor remove # Remove the rules\n```\n\n---\n\n## Usage Examples\n\nWith any of these tools installed, you can ask your AI to:\n\n```\n\"Create a candidates feature with org-scoped firewall and email/phone masking\"\n\n\"Add an 'approve' action to expenses that sets status and records the approver\"\n\n\"Show me the firewall documentation\"\n\n\"What security layers does my current project have configured?\"\n```\n\n## See Also\n\n- [Claude Code Plugin](/
|
|
118
|
+
"content": "The Quickback CLI ships with built-in support for AI developer tools. One install gets you a Claude Code skill, Cursor IDE rules, and an MCP server that works with any AI tool.\n\n## MCP Server\n\nThe MCP server exposes Quickback documentation, project config, and feature definitions to any MCP-compatible AI tool — Claude Desktop, Cursor, VS Code Copilot, Windsurf, and more.\n\n### Setup\n\nAdd to your AI tool's MCP configuration:\n\n```json\n{\n \"mcpServers\": {\n \"quickback\": {\n \"command\": \"npx\",\n \"args\": [\"@quickback-dev/cli\", \"mcp\"]\n }\n }\n}\n```\n\n**Where to put this:**\n\n| Tool | Config File |\n|------|-------------|\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) |\n| Cursor | `.cursor/mcp.json` in your project root |\n| VS Code (Copilot) | `.vscode/mcp.json` in your project root |\n\n### What the MCP Server Provides\n\n**Documentation tools:**\n\n| Tool | Description |\n|------|-------------|\n| `list_topics` | List all 100+ documentation topics |\n| `get_doc` | Get a specific doc by name (supports fuzzy matching) |\n| `search_docs` | Search documentation content by keyword |\n\n**Project-aware tools** (when running inside a Quickback project):\n\n| Tool | Description |\n|------|-------------|\n| `read_config` | Read your `quickback.config.ts` |\n| `list_features` | List all features and their table files |\n| `read_feature` | Read the source code of a specific feature |\n| `read_schema_registry` | Read the compiled `schema-registry.json` |\n\nThe MCP server also registers every documentation topic as an MCP resource at `quickback://docs/{topic}`.\n\n---\n\n## Claude Code Skill\n\nThe Claude Code skill gives Claude deep knowledge of Quickback's security layers, patterns, and APIs. It also activates a specialist agent for generating complete feature definitions.\n\n### Install\n\n```bash\nquickback claude install\n```\n\n**Options:**\n\n| Flag | Description |\n|------|-------------|\n| `--global` | Install to `~/.claude/` (available in all projects) |\n| `--local` | Install to `./quickback/.claude/` (project-specific) |\n\n### Manage\n\n```bash\nquickback claude status # Check installation\nquickback claude update # Update to latest version\nquickback claude remove # Remove the skill\n```\n\n### What You Get\n\n- **Quickback Skill** — Claude understands `defineTable()`, `defineActions()`, security pillars, provider options, and the compiler workflow\n- **Specialist Agent** — Automatically activates when creating resources, configuring security, or defining actions. Generates complete, working code in your `quickback/features/` directory.\n\n---\n\n## Cursor IDE Rules\n\nCursor rules provide Quickback context directly to Cursor's AI, activated automatically when editing `quickback/**/*.ts` files.\n\n### Install\n\n```bash\nquickback cursor install\n```\n\nThis copies `quickback.mdc` to `.cursor/rules/` in your project. Consider committing this file to your repo so your team gets the rules automatically.\n\n### Manage\n\n```bash\nquickback cursor status # Check installation\nquickback cursor update # Update to latest version\nquickback cursor remove # Remove the rules\n```\n\n---\n\n## Usage Examples\n\nWith any of these tools installed, you can ask your AI to:\n\n```\n\"Create a candidates feature with org-scoped firewall and email/phone masking\"\n\n\"Add an 'approve' action to expenses that sets status and records the approver\"\n\n\"Show me the firewall documentation\"\n\n\"What security layers does my current project have configured?\"\n```\n\n## See Also\n\n- [Claude Code Plugin](/compiler/claude-code-skill) — Full plugin reference\n- [Getting Started](/compiler/getting-started) — Project setup guide"
|
|
227
119
|
},
|
|
228
120
|
"compiler/getting-started/full-example": {
|
|
229
121
|
"title": "Complete Example",
|
|
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"
|
|
122
|
+
"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\") + soft-delete 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"
|
|
231
123
|
},
|
|
232
124
|
"compiler/getting-started/hand-crafted": {
|
|
233
125
|
"title": "Hand-Crafted Setup",
|
|
@@ -235,7 +127,7 @@ export const DOCS = {
|
|
|
235
127
|
},
|
|
236
128
|
"compiler/getting-started": {
|
|
237
129
|
"title": "Getting Started",
|
|
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"
|
|
130
|
+
"content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Install the CLI\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Create a Project\n\n```bash\nquickback create cloudflare my-app\ncd my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth (free)\n- `bun` — Bun + SQLite + Better Auth (free)\n- `turso` — Turso/LibSQL + Better Auth (pro)\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n department: q.text().required(),\n status: q.text().default('draft').required(), // draft | open | closed\n salaryMin: q.int().optional(),\n salaryMax: q.int().optional(),\n // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. CRUD — Write operations\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no CRUD routes ship until you opt in with `crud: { … }`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **CRUD Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Log in (first time only)\nquickback login\n\n# Compile your definitions\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/api/auth/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/api/auth/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
|
|
239
131
|
},
|
|
240
132
|
"compiler/getting-started/patterns": {
|
|
241
133
|
"title": "Common Patterns",
|
|
@@ -263,87 +155,163 @@ export const DOCS = {
|
|
|
263
155
|
},
|
|
264
156
|
"compiler": {
|
|
265
157
|
"title": "Quickback Compiler",
|
|
266
|
-
"content": "The Quickback
|
|
158
|
+
"content": "The **Quickback Compiler** is the build tool at the center of Quickback. You write declarative definitions in TypeScript — schema, security rules, validation, custom actions — and the compiler emits production-ready output for your chosen target.\n\n```\ndefineTable() ─┐ ┌─► Hono API (Cloudflare D1 / Neon)\n ├─► quickback compile┤\ndefineActions()─┘ └─► RLS policies (Supabase)\n```\n\nThe same definitions, the same DSL — pick the target that fits where you're deploying.\n\n## What the compiler does\n\nWhen you run `quickback compile`, it:\n\n1. **Reads your definitions** — every `defineTable()`, `defineActions()`, and `defineConfig()` in your project\n2. **Validates security** — firewall, access, guards, and masking are checked for consistency\n3. **Generates target output** — Hono routes + middleware + types + OpenAPI + MCP, or RLS migrations + helper functions\n4. **Emits database migrations** — runs `drizzle-kit generate` for schema changes\n\n```\nquickback/\n├── quickback.config.ts # Compiler configuration (target + providers)\n└── features/\n └── jobs/\n ├── jobs.ts # defineTable(...)\n └── actions.ts # defineActions(...)\n```\n\n## Two compile targets\n\n### [Quickback for Hono API](/compiler/targets/hono-api)\n\nGenerates a complete Hono application: routes, middleware, types, OpenAPI spec, MCP server. Pair with **Cloudflare D1** for SQLite-at-the-edge or **Neon** for full PostgreSQL with database-level RLS.\n\n```typescript\nproviders: {\n runtime: defineRuntime('cloudflare'),\n database: defineDatabase('cloudflare-d1'),\n auth: defineAuth('better-auth'),\n}\n```\n\n### [Quickback for Supabase](/compiler/targets/supabase-rls)\n\nGenerates PostgreSQL Row Level Security policies for Supabase. Keep Supabase Auth, Storage, and Realtime — Quickback adds the security layer beneath your existing app code.\n\n```typescript\nproviders: {\n runtime: defineRuntime('supabase'),\n database: defineDatabase('supabase'),\n auth: defineAuth('supabase-auth'),\n}\n```\n\n## The shared core\n\nWhichever target you pick, the **input language is the same**:\n\n- **[Definitions](/compiler/definitions)** — Schema, Firewall, Access, Guards, Masking, Views, Actions\n- **[Configuration](/compiler/config)** — `quickback.config.ts`, providers, domains, bindings\n- **[Getting Started](/compiler/getting-started)** — Templates and full examples\n\n## The cloud and the CLI\n\nYou don't run the compiler binary locally — it runs as a hosted service:\n\n- **[Cloud Compiler](/compiler/cloud-compiler)** — `compiler.quickback.dev`, CLI, authentication, MCP server for editors\n- **[Claude Code Skill](/compiler/claude-code-skill)** — AI-powered authoring assistance\n\n## Development workflow\n\n1. **Define resources** in `quickback/features/`\n2. **Compile** with `quickback compile`\n3. **Apply migrations** for your provider\n4. **Test locally** with `npm run dev`\n5. **Deploy** with `npm run deploy` (Hono target) or `supabase db push` (Supabase target)\n\n## Next steps\n\n- [Getting Started](/compiler/getting-started) — Create your first project\n- [Definitions](/compiler/definitions) — The shared DSL\n- [Quickback for Hono API](/compiler/targets/hono-api) — Compile to a Hono app\n- [Quickback for Supabase](/compiler/targets/supabase-rls) — Compile to RLS policies"
|
|
267
159
|
},
|
|
268
|
-
"compiler/
|
|
160
|
+
"compiler/targets/hono-api/cloudflare": {
|
|
269
161
|
"title": "Cloudflare Workers",
|
|
270
|
-
"content": "The Cloudflare target generates a complete Hono-based API running on Cloudflare Workers with D1 as the database. This is the recommended target for production deployments.\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Generated Output\n\n```\nsrc/\n├── routes/ # Hono route handlers (one per resource)\n├── middleware/ # Auth, firewall, access middleware\n├── features/ # Feature-specific helpers (security, masking)\n├── types/ # TypeScript interfaces\n├── db/\n│ └── schema.ts # Drizzle schema\n└── index.ts # Hono app entry point\n\nquickback/drizzle/\n├── migrations/ # SQL migration files\n└── meta/ # Drizzle metadata\n```\n\n## Security Model\n\nAll four security layers run at the application level:\n\n1. **Firewall** — Drizzle WHERE clauses for data isolation\n2. **Access** — Role checks in middleware\n3. **Guards** — Field filtering in request handlers\n4. **Masking** — Response transformation before sending\n\nSince D1 is only accessible through your Worker (no external connection string), the application layer is the only entry point. See [D1 Security Architecture](/
|
|
162
|
+
"content": "The Cloudflare target generates a complete Hono-based API running on Cloudflare Workers with D1 as the database. This is the recommended target for production deployments.\n\n## Configuration\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Generated Output\n\n```\nsrc/\n├── routes/ # Hono route handlers (one per resource)\n├── middleware/ # Auth, firewall, access middleware\n├── features/ # Feature-specific helpers (security, masking)\n├── types/ # TypeScript interfaces\n├── db/\n│ └── schema.ts # Drizzle schema\n└── index.ts # Hono app entry point\n\nquickback/drizzle/\n├── migrations/ # SQL migration files\n└── meta/ # Drizzle metadata\n```\n\n## Security Model\n\nAll four security layers run at the application level:\n\n1. **Firewall** — Drizzle WHERE clauses for data isolation\n2. **Access** — Role checks in middleware\n3. **Guards** — Field filtering in request handlers\n4. **Masking** — Response transformation before sending\n\nSince D1 is only accessible through your Worker (no external connection string), the application layer is the only entry point. See [D1 Security Architecture](/compiler/targets/hono-api/database/d1#security-architecture) for details.\n\n## Features\n\n- Full CRUD with batch operations (create, update, delete, upsert)\n- Custom actions with inline or handler-based execution\n- Soft delete with cascading to child tables\n- Pagination, filtering, sorting, field selection, and full-text search\n- Views (column-level projections with per-view access control)\n- OpenAPI specification generation at `/openapi.json`\n\n## Deployment\n\n```bash\n# Local development\nnpm run dev\n\n# Apply migrations to remote D1\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare Workers\nnpm run deploy\n```\n\n## Environment & Bindings\n\nYour `wrangler.toml` needs these bindings:\n\n| Binding | Type | Required | Purpose |\n|---------|------|----------|---------|\n| `DB` | D1 | Yes | Feature database |\n| `AUTH_DB` | D1 | Yes | Better Auth database |\n| `AUDIT_DB` | D1 | No* | Unsafe cross-tenant action audit logs |\n| `KV` | KV | Yes | Session storage |\n| `R2` | R2 | No | File storage (avatars, uploads) |\n| `AI` | Workers AI | No | Embeddings generation |\n| `VECTORIZE` | Vectorize | No | Vector search index |\n| `BROADCASTER` | Durable Object | No | Realtime broadcasts (inline DO) |\n\n\\* Required when you define cross-tenant unsafe actions.\n\n## See Also\n\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Step-by-step setup guide with full wrangler.toml configuration\n- [D1 Database](/compiler/targets/hono-api/database/d1) — D1 setup, multi-database pattern, and security architecture\n- [Neon Integration](/compiler/targets/hono-api/database/neon) — Alternative: PostgreSQL with RLS\n- [Supabase Integration](/compiler/targets/supabase-rls) — Alternative: Supabase with RLS"
|
|
271
163
|
},
|
|
272
|
-
"compiler/
|
|
273
|
-
"title": "
|
|
274
|
-
"content": "
|
|
164
|
+
"compiler/targets/hono-api/database/d1": {
|
|
165
|
+
"title": "D1 Database",
|
|
166
|
+
"content": "Cloudflare D1 is SQLite at the edge. Quickback uses D1 as the primary database for Cloudflare deployments, with a multi-database pattern for separation of concerns.\n\n## What is D1?\n\nD1 is Cloudflare's serverless SQL database built on SQLite:\n\n- **Edge-native** - Runs in Cloudflare's global network\n- **SQLite compatible** - Use familiar SQL syntax\n- **Zero configuration** - No connection strings or pooling\n- **Automatic replication** - Read replicas at every edge location\n\n## Multi-Database Pattern\n\nQuickback generates separate D1 databases for different concerns:\n\n| Database | Binding | Purpose |\n|----------|---------|---------|\n| `AUTH_DB` | `AUTH_DB` | Better Auth tables (user, session, account) |\n| `DB` | `DB` | Your application data |\n| `FILES_DB` | `FILES_DB` | File metadata for R2 uploads |\n| `WEBHOOKS_DB` | `WEBHOOKS_DB` | Webhook delivery tracking |\n\nThis separation provides:\n- **Independent scaling** - Auth traffic doesn't affect app queries\n- **Isolation** - Auth schema changes don't touch your data\n- **Clarity** - Clear ownership of each database\n\n## Drizzle ORM Integration\n\nQuickback uses [Drizzle ORM](https://orm.drizzle.team/) for type-safe database access:\n\n```ts\n// schema/tables.ts - Your schema definition\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n content: text(\"content\"),\n authorId: text(\"author_id\").notNull(),\n createdAt: integer(\"created_at\", { mode: \"timestamp\" }),\n});\n```\n\nThe compiler generates Drizzle queries based on your security rules:\n\n```ts\n// Generated query with firewall applied\nconst result = await db\n .select()\n .from(posts)\n .where(eq(posts.authorId, userId)); // Firewall injects ownership\n```\n\n## Migrations\n\nQuickback generates migrations automatically at compile time based on your schema changes:\n\n```bash\n# Compile your project (generates migrations)\nquickback compile\n\n# Apply migrations locally\nwrangler d1 migrations apply DB --local\n\n# Apply to production D1\nwrangler d1 migrations apply DB --remote\n```\n\nMigration files are generated in `quickback/drizzle/` and version-controlled with your code. You never need to manually generate migrations—just define your schema and compile.\n\n## wrangler.toml Bindings\n\nThe compiler generates D1 bindings in `wrangler.toml` automatically. To get production-ready IDs in the output, set them in your `quickback.config.ts`:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n databaseId: \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\", // Features DB → binding \"DB\"\n authDatabaseId: \"yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\", // Auth DB → binding \"AUTH_DB\"\n filesDatabaseId: \"zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz\", // Files DB → binding \"FILES_DB\"\n }),\n}\n```\n\nThis generates:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"\n\n[[d1_databases]]\nbinding = \"FILES_DB\"\ndatabase_name = \"my-app-files\"\ndatabase_id = \"zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz\"\n```\n\nIf database IDs are omitted, the compiler uses local-dev placeholders — you'll need to replace them manually before deploying.\n\nCreate databases via Wrangler:\n\n```bash\nwrangler d1 create my-app-features\nwrangler d1 create my-app-auth\nwrangler d1 create my-app-files\n```\n\n## Accessing Data via API\n\nAll data access in Quickback goes through the generated API endpoints—never direct database queries. This ensures security rules (firewall, access, guards, masking) are always enforced.\n\n### CRUD Operations\n\n```bash\n# List posts (firewall automatically filters by ownership)\nGET /api/v1/posts\n\n# Get a single post\nGET /api/v1/posts/:id\n\n# Create a post (guards validate allowed fields)\nPOST /api/v1/posts\n{ \"title\": \"Hello World\", \"content\": \"...\" }\n\n# Update a post (guards validate updatable fields)\nPATCH /api/v1/posts/:id\n{ \"title\": \"Updated Title\" }\n\n# Delete a post\nDELETE /api/v1/posts/:id\n```\n\n### Filtering and Pagination\n\n```bash\n# Filter by field\nGET /api/v1/posts?status=published\n\n# Pagination\nGET /api/v1/posts?limit=10&offset=20\n\n# Sort\nGET /api/v1/posts?sort=createdAt&order=desc\n```\n\n### Why No Direct Database Access?\n\nDirect database queries bypass Quickback's security layers:\n- **Firewall** - Data isolation by user/org/team\n- **Access** - Role-based permissions\n- **Guards** - Field-level create/update restrictions\n- **Masking** - Sensitive data redaction\n\nAlways use the API endpoints. For custom business logic, use [Actions](/compiler/definitions/actions).\n\n## Local Development\n\nD1 works locally with Wrangler:\n\n```bash\n# Start local dev server with D1\nwrangler dev\n\n# D1 data persists in .wrangler/state/\n```\n\nLocal D1 uses SQLite files in `.wrangler/state/v3/d1/`, which you can inspect with any SQLite client.\n\n## Security Architecture\n\nFor all Quickback-generated code, D1's application-layer security provides equivalent protection to Supabase RLS. The key difference is where enforcement happens — and this matters if you write custom routes.\n\n### How Security Works\n\n| Component | Enforcement | Notes |\n|-----------|-------------|-------|\n| CRUD endpoints | ✅ Firewall auto-applied | All generated routes enforce security |\n| Actions | ✅ Firewall auto-applied | Both standalone and record-based |\n| Manual routes | ⚠️ Must apply firewall | Use `withFirewall` helper |\n\n### Why D1 is Secure\n\n1. **No external database access** - D1 can only be queried through your Worker. There's no connection string or external endpoint.\n2. **Generated code enforces rules** - All CRUD and Action endpoints automatically apply firewall, access, guards, and masking.\n3. **Single entry point** - Every request flows through your API where security is enforced.\n\nUnlike Supabase where PostgreSQL RLS provides database-level enforcement (protecting data even if application code has bugs), D1's security comes from architecture: the database is inaccessible except through your Worker, and all generated routes apply the four security pillars. The trade-off is that **custom routes you write outside Quickback must manually apply security** — there is no database-level safety net.\n\n### Comparison with Supabase RLS\n\n| Scenario | Supabase | D1 |\n|----------|----------|-----|\n| CRUD endpoints | ✅ Secure (RLS + App) | ✅ Secure (App) |\n| Actions | ✅ Secure (RLS + App) | ✅ Secure (App) |\n| Manual routes | ✅ RLS still protects | ⚠️ Must apply firewall |\n| External DB access | ⚠️ Possible with credentials | ✅ Not possible |\n| Dashboard queries | Via Supabase Studio | ⚠️ Admin only (audit logged) |\n\n### Writing Manual Routes\n\nIf you write custom routes outside of Quickback compilation (e.g., custom reports, integrations), use the generated `withFirewall` helper to ensure security:\n\n```ts\n\napp.get('/reports/monthly', async (c) => {\n return withFirewall(c, async (ctx, firewall) => {\n const results = await db.select()\n .from(invoices)\n .where(firewall);\n return c.json(results);\n });\n});\n```\n\nThe `withFirewall` helper:\n- Validates authentication\n- Builds the correct WHERE conditions for the current user/org\n- Returns 401 if not authenticated\n\n### Best Practices\n\n1. **Use generated endpoints** - Prefer CRUD and Actions over manual routes\n2. **Always apply firewall** - When writing manual routes, always use `withFirewall`\n3. **Avoid raw SQL** - Raw SQL bypasses application security; use Drizzle ORM\n4. **Review custom code** - Manual routes should be code-reviewed for security\n\n## Limitations\n\nD1 is built on SQLite, which means:\n\n- **No stored procedures** - Business logic lives in your Worker\n- **Single-writer** - One write connection at a time (reads scale horizontally)\n- **Size limits** - 10GB per database (free tier: 500MB)\n- **No PostgreSQL extensions** - Use Supabase if you need PostGIS, etc.\n\nFor most applications, these limits are non-issues. D1's edge distribution and zero-config setup outweigh the constraints."
|
|
275
167
|
},
|
|
276
|
-
"compiler/
|
|
168
|
+
"compiler/targets/hono-api/database": {
|
|
169
|
+
"title": "Database",
|
|
170
|
+
"content": "The Quickback Stack supports multiple database providers. Choose the one that fits your deployment target.\n\n## Providers\n\n| Provider | Best For | Features |\n|----------|----------|----------|\n| [Cloudflare D1](/compiler/targets/hono-api/database/d1) | Edge-first apps | SQLite at the edge, zero-latency reads |\n| [Neon](/compiler/targets/hono-api/database/neon) | Postgres apps | Serverless Postgres, branching, autoscaling |\n\n## Getting Started\n\n- **[D1 Setup](/compiler/targets/hono-api/database/d1)** — Bindings, wrangler config, migrations\n- **[Using D1](/compiler/targets/hono-api/database/using-d1)** — Drizzle queries, dual-DB mode, schema patterns\n- **[Neon](/compiler/targets/hono-api/database/neon)** — Serverless Postgres setup and usage"
|
|
171
|
+
},
|
|
172
|
+
"compiler/targets/hono-api/database/neon": {
|
|
277
173
|
"title": "Neon",
|
|
278
|
-
"content": "
|
|
174
|
+
"content": "Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP connections. Choose Neon when you need PostgreSQL features (JSON operators, full-text search, advanced indexing) or want database-level Row Level Security alongside the generated Hono API.\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 the API is bypassed\n- **Serverless** — HTTP connection mode for Cloudflare Workers\n- **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function\n- **Better Auth integration** — Works seamlessly with the Quickback auth provider\n\n## Configuration\n\n```typescript title=\"quickback/quickback.config.ts\"\n\nexport default defineConfig({\n name: \"my-app\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"auto\", // detects runtime\n pooled: true,\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Connection modes\n\n| Mode | Best for | How it works |\n|------|----------|--------------|\n| **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |\n| **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |\n| **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |\n\n## Environment variables\n\n```bash\n# For Cloudflare Workers\nnpx wrangler secret put DATABASE_URL\n# Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n\n# For local development (.env)\nDATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require\n```\n\n## Migrations\n\nNeon uses PostgreSQL migrations, distinct from D1's SQLite migrations:\n\n```bash\nquickback compile # generates migrations under quickback/drizzle/\nnpm run db:migrate # applies them\n```\n\n## Row Level Security\n\nQuickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\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\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```sql\nCREATE POLICY \"preferences_select\" ON preferences FOR SELECT\nUSING (user_id = auth.user_id());\n```\n\n**Public tables:**\n\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### Helper functions\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any specified role |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `is_owner(owner_id)` | Checks record ownership |\n\n## Setting up Neon Authorize\n\n1. Open **Project Settings → Authorize** in the Neon console\n2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`\n3. The `auth.user_id()` function will return the authenticated user's ID from the JWT\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/schema.ts # Drizzle schema\n├── auth/schema.ts # Better Auth schema\n└── lib/neon.ts # Connection helper\n```\n\n## When to choose Neon vs D1\n\n| Factor | Neon | D1 |\n|--------|------|-----|\n| SQL dialect | PostgreSQL | SQLite |\n| Security model | RLS + application-layer | Application-layer only |\n| Multi-region | Built-in replication | Single region per database |\n| Pricing | Free tier, then usage-based | Free tier, then usage-based |\n| Best for | Complex queries, existing Postgres apps | Edge-first, simple schemas |\n\n## See also\n\n- [D1](/compiler/targets/hono-api/database/d1) — SQLite at the edge\n- [Providers](/compiler/config/providers) — All database provider options\n- [Quickback for Supabase](/compiler/targets/supabase-rls) — A different Postgres+RLS path that uses Supabase Auth instead of Better Auth"
|
|
279
175
|
},
|
|
280
|
-
"compiler/
|
|
281
|
-
"title": "
|
|
282
|
-
"content": "
|
|
176
|
+
"compiler/targets/hono-api/database/using-d1": {
|
|
177
|
+
"title": "Using D1",
|
|
178
|
+
"content": "This page covers how to use Cloudflare D1 with Drizzle ORM in your Quickback Stack application.\n\n## Drizzle Queries\n\nThe generated API uses Drizzle ORM for all database operations:\n\n```typescript\n\n// Select\nconst allRooms = await db.select().from(rooms);\n\n// Where clause\nconst room = await db.select().from(rooms).where(eq(rooms.id, id));\n\n// Insert\nawait db.insert(rooms).values({ name: 'Conference A' });\n```\n\n## Dual-DB Mode\n\nQuickback supports separate databases for auth and application data, useful for multi-tenant SaaS apps.\n\n## Migrations\n\nMigrations are generated by the compiler using `drizzle-kit generate`. Apply them with:\n\n```bash\nnpx wrangler d1 migrations apply my-db\n```\n\n## Related\n\n- [D1 Setup](/compiler/targets/hono-api/database/d1) — Bindings and wrangler config\n- [Schema](/compiler/definitions/schema) — Defining your database schema"
|
|
283
179
|
},
|
|
284
|
-
"compiler/
|
|
285
|
-
"title": "
|
|
286
|
-
"content": "
|
|
180
|
+
"compiler/targets/hono-api": {
|
|
181
|
+
"title": "Quickback for Hono API",
|
|
182
|
+
"content": "**Quickback for Hono API** is the default compile target. Your `defineTable()` and `defineActions()` files become a complete Hono application: routes, middleware, types, OpenAPI spec, and an MCP server, all generated and ready to deploy.\n\n## What you ship\n\n```\nsrc/\n├── routes/ # One file per resource — GET/POST/PATCH/DELETE + batch\n├── middleware/ # Auth, firewall, access, guards, masking\n├── types/ # TypeScript interfaces inferred from your schema\n├── openapi.json # Generated spec, served at /openapi.json\n└── index.ts # Hono app entry point\n```\n\nThe generated app runs on **Cloudflare Workers** (recommended) or any Hono-compatible runtime. Pair it with **Cloudflare D1** for SQLite-at-the-edge or **Neon** for full PostgreSQL with database-level RLS.\n\n## Pick your database\n\n| Database | Best for | Notes |\n|----------|----------|-------|\n| [**Cloudflare D1**](/compiler/targets/hono-api/database/d1) | Most projects | SQLite at the edge. Application-level security. Free tier covers a lot. |\n| [**Neon**](/compiler/targets/hono-api/database/neon) | PostgreSQL features needed | Full Postgres with database-level RLS via Neon Authorize. |\n\n## Pick your runtime\n\n| Runtime | Notes |\n|---------|-------|\n| [**Cloudflare Workers**](/compiler/targets/hono-api/cloudflare) | Default. Edge-native, integrates with the rest of [Quickback Stack](/stack). |\n| Bun / Node | Supported via the same Hono output. Less first-class for Stack services. |\n\n## In this section\n\n- **[Cloudflare](/compiler/targets/hono-api/cloudflare)** — Compile and deploy to Workers\n- **[Neon](/compiler/targets/hono-api/database/neon)** — Compile to PostgreSQL with RLS\n- **[Database](/compiler/targets/hono-api/database)** — D1, Neon, schema and migrations\n- **[Using the API](/compiler/targets/hono-api/using-the-api)** — CRUD, batch operations, query params, OpenAPI, errors"
|
|
287
183
|
},
|
|
288
|
-
"compiler/using-the-api/actions-api": {
|
|
184
|
+
"compiler/targets/hono-api/using-the-api/actions-api": {
|
|
289
185
|
"title": "Actions API",
|
|
290
|
-
"content": "Actions provide custom endpoints beyond CRUD operations. They support input validation, access conditions, and multiple response types including streaming.\n\n## Record-Based Actions\n\nRecord-based actions operate on a specific record identified by ID.\n\n```\nPOST /api/v1/{resource}/:id/{action-name}\n```\n\n### Request\n\n```bash\n# With JSON body\ncurl -X POST /api/v1/applications/app_123/advance-stage \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"notes\": \"Strong technical interview, moving to offer stage\" }'\n```\n\nThe action's input schema validates the request body using Zod. Invalid input returns a 400 error.\n\n### Response\n\n```json\n{\n \"success\": true,\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"offer\",\n \"previousStage\": \"interview\",\n \"notes\": \"Strong technical interview, moving to offer stage\"\n }\n}\n```\n\n### Security Flow\n\n1. **Authentication** — User must be logged in (401 if not)\n2. **Firewall** — Record must exist and be accessible to the user (404 if not found or not owned)\n3. **Access** — User must have the required role (403 if insufficient)\n4. **Input validation** — Request body validated against the action's Zod schema (400 if invalid)\n5. **Access conditions** — Record must match access conditions (400 if not met)\n6. **Masking** — Applied to the response data\n\n### Access Conditions\n\nActions can require the record to be in a specific state:\n\n```typescript\n// In actions.ts\nreject: {\n access: {\n roles: [\"owner\", \"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n}\n```\n\nIf the record doesn't match (`stage` is already `rejected`), the action returns 400.\n\n## Standalone Actions\n\nStandalone actions don't require a record ID. They're for operations that aren't tied to a specific record.\n\n```\nPOST /api/v1/{resource}/{action-name}\n```\n\n### Request\n\n```bash\ncurl -X POST /api/v1/candidates/bulk-import \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"source\": \"LinkedIn\", \"candidates\": [{\"name\": \"Alice Johnson\", \"email\": \"alice@example.com\"}, {\"name\": \"Bob Martinez\", \"email\": \"bob@example.com\"}] }'\n```\n\n### Response\n\nSame format as record-based actions. The difference is no record lookup or firewall check.\n\n### Security Flow\n\n1. **Authentication** — Required (401)\n2. **Organization check** — For org-scoped resources, user must have an active organization (403)\n3. **Access** — Role-based check (403)\n4. **Scoped DB** — The `db` passed to the handler is auto-scoped based on table columns (org isolation, owner filtering, soft delete)\n5. **Input validation** — Zod schema validation (400)\n\n### Scoped Database\n\nAll actions (both standalone and record-based) receive a **scoped `db`** instance that automatically enforces security based on the table's columns:\n\n- Tables with `organizationId` — org isolation (`WHERE organizationId = ?`)\n- Tables with `ownerId` — owner isolation (`WHERE ownerId = ?`)\n- Tables with `deletedAt` — soft delete filter (`WHERE deletedAt IS NULL`)\n- `INSERT` operations auto-inject `organizationId` and `ownerId` from context\n\n```typescript\n// Your handler receives a scoped db — no manual filtering needed\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND ownerId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId and ownerId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\nIf you need unscoped access (for example, audited platform admin operations), declare `unsafe` on the action:\n\n```typescript\nadminReport: {\n unsafe: {\n reason: 'Platform support report',\n adminOnly: true,\n crossTenant: true,\n targetScope: 'all',\n },\n execute: async ({ db, unsafeDb, ctx, input }) => {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n}\n```\n\nCross-tenant unsafe actions are generated with:\n\n- Better Auth authentication required\n- platform admin gate (`ctx.userRole === 'admin'`)\n- mandatory audit logging on denial/success/error\n\nWithout unsafe mode, `unsafeDb` is `undefined`.\n\nRaw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.\n\n### Explicit scope with `unsafeDb.scopeTo`\n\nUnsafe handlers often need to derive the tenant from somewhere other than the ambient request context — an inbound webhook reads it from a mailbox record, a cron job iterates over every organization, a background worker acts on behalf of a specific user. `unsafeDb.scopeTo({ organizationId?, userId?, teamId? })` returns a scoped db that applies the firewall with your explicit scope instead of `ctx`:\n\n```typescript\n// Inbound mail webhook — PUBLIC + unsafe:true\ningestInbound: {\n standalone: true,\n access: { roles: ['PUBLIC'] },\n unsafe: {\n reason: 'Inbound mail webhook — tenant derived from mailbox record',\n targetScope: 'organization',\n },\n input: z.object({ mailboxId: z.string(), body: z.string() }),\n execute: async ({ unsafeDb, input }) => {\n // Look up the mailbox without a tenant in ctx (unsafe handler, unscoped client)\n const [mailbox] = await unsafeDb.select().from(mailboxes)\n .where(eq(mailboxes.id, input.mailboxId));\n if (!mailbox) return { ok: false };\n\n // Pin scope to the mailbox's organization — every downstream query gets\n // WHERE organizationId = mailbox.organizationId, inserts get it injected.\n const db = unsafeDb.scopeTo({ organizationId: mailbox.organizationId });\n await db.insert(messages).values({ mailboxId: mailbox.id, body: input.body });\n return { ok: true };\n },\n}\n```\n\nWhy this is safer than hand-rolling `organizationId` on every query:\n\n- The firewall still runs. `scopeTo` just tells it which scope to use.\n- `insert().values()` auto-injects `organizationId` / `ownerId` / `teamId` per the scope.\n- Soft-delete and team-isolation filters continue to apply unchanged.\n- No chance of forgetting a `WHERE organizationId = ?` clause on a single query.\n\n`x-unsafe: true` is emitted on each unsafe operation in `openapi.json`, and MCP tool lists prefix the description with `[UNSAFE]` and set `annotations.destructiveHint` so agents and reviewers can see at a glance which endpoints cross trust boundaries.\n\n## Input Validation\n\nActions use Zod schemas for input validation. The schema is defined in your `actions.ts` file:\n\n```typescript\n\nexport default defineActions(\"applications\", {\n \"advance-stage\": {\n type: \"record\",\n input: z.object({\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"hired\" } },\n },\n },\n reject: {\n type: \"record\",\n input: z.object({\n reason: z.string().min(1),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n },\n});\n```\n\nWhen validation fails:\n\n```json\n{\n \"error\": \"Validation failed\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_VALIDATION_FAILED\",\n \"details\": {\n \"issues\": [\n { \"path\": [\"reason\"], \"message\": \"String must contain at least 1 character(s)\" }\n ]\n }\n}\n```\n\n## Response Types\n\nActions support three response types:\n\n### JSON (Default)\n\nReturns a JSON object wrapped in `{ success: true, data: ... }`. Masking is applied to the data.\n\n### Streaming\n\nFor long-running operations, actions can return a streaming response:\n\n```typescript\ngenerateReport: {\n type: \"standalone\",\n responseType: \"stream\",\n // ...\n}\n```\n\nThe action handler returns a `ReadableStream` directly — no JSON wrapper.\n\n### File\n\nFor file downloads, actions can return a raw `Response` object:\n\n```typescript\nexportCsv: {\n type: \"record\",\n responseType: \"file\",\n // ...\n}\n```\n\n## Action Handler\n\nThe compiler generates a handler skeleton. Your action receives:\n\n```typescript\n{\n db, // Scoped database (auto-enforces org/owner/soft-delete filters)\n unsafeDb, // Raw database (only available when unsafe mode is enabled)\n ctx, // Auth context (user, session, org)\n record, // The existing record (record-based only, undefined for standalone)\n input, // Validated input from Zod schema\n services, // Injected services\n c, // Hono context\n env, // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auditFields, // { createdAt, modifiedAt } timestamps\n}\n```\n\n## HTTP Methods\n\nActions default to `POST` but can use any HTTP method:\n\n```typescript\ngetStatus: {\n type: \"record\",\n method: \"GET\",\n // GET actions receive input from query parameters instead of body\n}\n```\n\nWhen using `GET`, input is parsed from query parameters instead of the request body.\n\n## Cascading Soft Delete\n\nWhen soft-deleting a parent record, Quickback automatically soft-deletes related records in child/junction tables **within the same feature**. The compiler detects foreign key references at build time.\n\nFor example, if your feature has `jobs` and `applications` tables where `applications` has a `.references(() => jobs.id)`, deleting a job will also soft-delete all its applications:\n\n```\nDELETE /api/v1/jobs/job_123\n```\n\nGenerated code:\n```typescript\n// Soft delete parent\nawait db.update(jobs).set({ deletedAt: now, modifiedAt: now })\n .where(and(buildFirewallConditions(ctx), eq(jobs.id, id)));\n\n// Cascade soft delete to child tables\nawait db.update(applications).set({ deletedAt: now, modifiedAt: now })\n .where(eq(applications.jobId, id));\n```\n\n**Cascade rules:**\n- **Soft delete (default)**: Application-level cascade via generated UPDATE statements\n- **Hard delete (`mode: 'hard'`)**: No compiler cascade — relies on DB-level `ON DELETE CASCADE`\n- **Cross-feature**: No cascade — only within the same feature's tables\n\n## See Also\n\n- [Defining Actions](/compiler/definitions/actions) — How to define actions in your feature\n- [Guards](/compiler/definitions/guards) — Guard conditions reference\n- [Error Responses](/compiler/using-the-api/errors) — Error format reference"
|
|
186
|
+
"content": "Actions provide custom endpoints beyond CRUD operations. They support input validation, access conditions, and multiple response types including streaming.\n\n## Record-Based Actions\n\nRecord-based actions operate on a specific record identified by ID.\n\n```\nPOST /api/v1/{resource}/:id/{action-name}\n```\n\n### Request\n\n```bash\n# With JSON body\ncurl -X POST /api/v1/applications/app_123/advance-stage \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"notes\": \"Strong technical interview, moving to offer stage\" }'\n```\n\nThe action's input schema validates the request body using Zod. Invalid input returns a 400 error.\n\n### Response\n\n```json\n{\n \"success\": true,\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"offer\",\n \"previousStage\": \"interview\",\n \"notes\": \"Strong technical interview, moving to offer stage\"\n }\n}\n```\n\n### Security Flow\n\n1. **Authentication** — User must be logged in (401 if not)\n2. **Firewall** — Record must exist and be accessible to the user (404 if not found or not owned)\n3. **Access** — User must have the required role (403 if insufficient)\n4. **Input validation** — Request body validated against the action's Zod schema (400 if invalid)\n5. **Access conditions** — Record must match access conditions (400 if not met)\n6. **Masking** — Applied to the response data\n\n### Access Conditions\n\nActions can require the record to be in a specific state:\n\n```typescript\n// In actions.ts\nreject: {\n access: {\n roles: [\"owner\", \"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n}\n```\n\nIf the record doesn't match (`stage` is already `rejected`), the action returns 400.\n\n## Standalone Actions\n\nStandalone actions don't require a record ID. They're for operations that aren't tied to a specific record.\n\n```\nPOST /api/v1/{resource}/{action-name}\n```\n\n### Request\n\n```bash\ncurl -X POST /api/v1/candidates/bulk-import \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"source\": \"LinkedIn\", \"candidates\": [{\"name\": \"Alice Johnson\", \"email\": \"alice@example.com\"}, {\"name\": \"Bob Martinez\", \"email\": \"bob@example.com\"}] }'\n```\n\n### Response\n\nSame format as record-based actions. The difference is no record lookup or firewall check.\n\n### Security Flow\n\n1. **Authentication** — Required (401)\n2. **Organization check** — For org-scoped resources, user must have an active organization (403)\n3. **Access** — Role-based check (403)\n4. **Scoped DB** — The `db` passed to the handler is auto-scoped based on table columns (org isolation, owner filtering, soft delete)\n5. **Input validation** — Zod schema validation (400)\n\n### Scoped Database\n\nAll actions (both standalone and record-based) receive a **scoped `db`** instance that automatically enforces security based on the table's columns:\n\n- Tables with `organizationId` — org isolation (`WHERE organizationId = ?`)\n- Tables with `ownerId` — owner isolation (`WHERE ownerId = ?`)\n- Tables with `deletedAt` — soft delete filter (`WHERE deletedAt IS NULL`)\n- `INSERT` operations auto-inject `organizationId` and `ownerId` from context\n\n```typescript\n// Your handler receives a scoped db — no manual filtering needed\nexecute: async ({ db, ctx, input }) => {\n // This query automatically includes WHERE organizationId = ? AND ownerId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId and ownerId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\nIf you need unscoped access (for example, audited platform admin operations), declare `unsafe` on the action:\n\n```typescript\nadminReport: {\n unsafe: {\n reason: 'Platform support report',\n adminOnly: true,\n crossTenant: true,\n targetScope: 'all',\n },\n execute: async ({ db, unsafeDb, ctx, input }) => {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n}\n```\n\nCross-tenant unsafe actions are generated with:\n\n- Better Auth authentication required\n- platform admin gate (`ctx.userRole === 'admin'`)\n- mandatory audit logging on denial/success/error\n\nWithout unsafe mode, `unsafeDb` is `undefined`.\n\nRaw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.\n\n### Explicit scope with `unsafeDb.scopeTo`\n\nUnsafe handlers often need to derive the tenant from somewhere other than the ambient request context — an inbound webhook reads it from a mailbox record, a cron job iterates over every organization, a background worker acts on behalf of a specific user. `unsafeDb.scopeTo({ organizationId?, userId?, teamId? })` returns a scoped db that applies the firewall with your explicit scope instead of `ctx`:\n\n```typescript\n// Inbound mail webhook — PUBLIC + unsafe:true\ningestInbound: {\n standalone: true,\n access: { roles: ['PUBLIC'] },\n unsafe: {\n reason: 'Inbound mail webhook — tenant derived from mailbox record',\n targetScope: 'organization',\n },\n input: z.object({ mailboxId: z.string(), body: z.string() }),\n execute: async ({ unsafeDb, input }) => {\n // Look up the mailbox without a tenant in ctx (unsafe handler, unscoped client)\n const [mailbox] = await unsafeDb.select().from(mailboxes)\n .where(eq(mailboxes.id, input.mailboxId));\n if (!mailbox) return { ok: false };\n\n // Pin scope to the mailbox's organization — every downstream query gets\n // WHERE organizationId = mailbox.organizationId, inserts get it injected.\n const db = unsafeDb.scopeTo({ organizationId: mailbox.organizationId });\n await db.insert(messages).values({ mailboxId: mailbox.id, body: input.body });\n return { ok: true };\n },\n}\n```\n\nWhy this is safer than hand-rolling `organizationId` on every query:\n\n- The firewall still runs. `scopeTo` just tells it which scope to use.\n- `insert().values()` auto-injects `organizationId` / `ownerId` / `teamId` per the scope.\n- Soft-delete and team-isolation filters continue to apply unchanged.\n- No chance of forgetting a `WHERE organizationId = ?` clause on a single query.\n\n`x-unsafe: true` is emitted on each unsafe operation in `openapi.json`, and MCP tool lists prefix the description with `[UNSAFE]` and set `annotations.destructiveHint` so agents and reviewers can see at a glance which endpoints cross trust boundaries.\n\n## Input Validation\n\nActions use Zod schemas for input validation. The schema is defined in your `actions.ts` file:\n\n```typescript\n\nexport default defineActions(\"applications\", {\n \"advance-stage\": {\n type: \"record\",\n input: z.object({\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"hired\" } },\n },\n },\n reject: {\n type: \"record\",\n input: z.object({\n reason: z.string().min(1),\n }),\n access: {\n roles: [\"hiring-manager\", \"recruiter\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n },\n});\n```\n\nWhen validation fails:\n\n```json\n{\n \"error\": \"Validation failed\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_VALIDATION_FAILED\",\n \"details\": {\n \"issues\": [\n { \"path\": [\"reason\"], \"message\": \"String must contain at least 1 character(s)\" }\n ]\n }\n}\n```\n\n## Response Types\n\nActions support three response types:\n\n### JSON (Default)\n\nReturns a JSON object wrapped in `{ success: true, data: ... }`. Masking is applied to the data.\n\n### Streaming\n\nFor long-running operations, actions can return a streaming response:\n\n```typescript\ngenerateReport: {\n type: \"standalone\",\n responseType: \"stream\",\n // ...\n}\n```\n\nThe action handler returns a `ReadableStream` directly — no JSON wrapper.\n\n### File\n\nFor file downloads, actions can return a raw `Response` object:\n\n```typescript\nexportCsv: {\n type: \"record\",\n responseType: \"file\",\n // ...\n}\n```\n\n## Action Handler\n\nThe compiler generates a handler skeleton. Your action receives:\n\n```typescript\n{\n db, // Scoped database (auto-enforces org/owner/soft-delete filters)\n unsafeDb, // Raw database (only available when unsafe mode is enabled)\n ctx, // Auth context (user, session, org)\n record, // The existing record (record-based only, undefined for standalone)\n input, // Validated input from Zod schema\n services, // Injected services\n c, // Hono context\n env, // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n}\n```\n\n## HTTP Methods\n\nActions default to `POST` but can use any HTTP method:\n\n```typescript\ngetStatus: {\n type: \"record\",\n method: \"GET\",\n // GET actions receive input from query parameters instead of body\n}\n```\n\nWhen using `GET`, input is parsed from query parameters instead of the request body.\n\n## Cascading Soft Delete\n\nWhen soft-deleting a parent record, Quickback automatically soft-deletes related records in child/junction tables **within the same feature**. The compiler detects foreign key references at build time.\n\nFor example, if your feature has `jobs` and `applications` tables where `applications` has a `.references(() => jobs.id)`, deleting a job will also soft-delete all its applications:\n\n```\nDELETE /api/v1/jobs/job_123\n```\n\nGenerated code:\n```typescript\n// Soft delete parent\nawait db.update(jobs).set({ deletedAt: now, modifiedAt: now })\n .where(and(buildFirewallConditions(ctx), eq(jobs.id, id)));\n\n// Cascade soft delete to child tables\nawait db.update(applications).set({ deletedAt: now, modifiedAt: now })\n .where(eq(applications.jobId, id));\n```\n\n**Cascade rules:**\n- **Soft delete (default)**: Application-level cascade via generated UPDATE statements\n- **Hard delete (`mode: 'hard'`)**: No compiler cascade — relies on DB-level `ON DELETE CASCADE`\n- **Cross-feature**: No cascade — only within the same feature's tables\n\n## See Also\n\n- [Defining Actions](/compiler/definitions/actions) — How to define actions in your feature\n- [Guards](/compiler/definitions/guards) — Guard conditions reference\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference"
|
|
291
187
|
},
|
|
292
|
-
"compiler/using-the-api/batch-operations": {
|
|
188
|
+
"compiler/targets/hono-api/using-the-api/batch-operations": {
|
|
293
189
|
"title": "Batch Operations",
|
|
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"
|
|
190
|
+
"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/targets/hono-api/using-the-api/crud) — Single-record operations\n- [Error Responses](/compiler/targets/hono-api/using-the-api/errors) — Error format reference\n- [Guards](/compiler/definitions/guards) — Field-level write protection"
|
|
295
191
|
},
|
|
296
|
-
"compiler/using-the-api/caching": {
|
|
192
|
+
"compiler/targets/hono-api/using-the-api/caching": {
|
|
297
193
|
"title": "Caching & ETags",
|
|
298
194
|
"content": "Quickback APIs include automatic [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) support on all read endpoints. This lets clients and edge caches avoid re-transferring unchanged data, reducing latency and bandwidth.\n\n## How it works\n\n1. Every GET, LIST, and VIEW response includes a weak ETag header computed from the JSON body:\n ```\n ETag: W/\"a1b2c3d4e5f60718\"\n ```\n\n2. On subsequent requests, the client sends the ETag back:\n ```\n If-None-Match: W/\"a1b2c3d4e5f60718\"\n ```\n\n3. If the data hasn't changed, the server returns `304 Not Modified` with no body — saving bandwidth and parse time.\n\n4. If the data has changed, the server returns the full response with a new ETag.\n\n## Which endpoints support ETags\n\n| Endpoint | ETag | Notes |\n|----------|------|-------|\n| `GET /` (list) | Yes | |\n| `GET /:id` (get) | Yes | |\n| `GET /views/:name` (view) | Yes | |\n| `POST /` (create) | No | Mutations don't cache |\n| `PUT /:id` (update) | No | |\n| `DELETE /:id` (delete) | No | |\n| Actions | No | Side-effectful |\n| Batch operations | No | Mutations |\n\n## Security\n\nETags are computed **after** all security pillars are applied (Firewall, Access, Guards, Masking). This means:\n\n- Different users with different masking rules get different ETags\n- Firewall-scoped data produces ETags specific to that scope\n- There is no risk of leaking data across users via cached ETags\n\n## Response headers\n\nWhen ETags are enabled, GET responses include:\n\n```\nContent-Type: application/json\nETag: W/\"a1b2c3d4e5f60718\"\nCache-Control: no-cache\n```\n\n`Cache-Control: no-cache` means the browser (or edge cache) **must revalidate** on every request, but can use the cached response if the ETag matches. This is the correct behavior for authenticated APIs — data is always fresh, but unchanged responses avoid re-transfer.\n\n## Client usage\n\n### fetch API\n\n```typescript\n// First request\nconst res = await fetch(\"/api/v1/jobs\");\nconst etag = res.headers.get(\"ETag\");\nconst data = await res.json();\n\n// Subsequent request with ETag\nconst res2 = await fetch(\"/api/v1/jobs\", {\n headers: { \"If-None-Match\": etag },\n});\n\nif (res2.status === 304) {\n // Data hasn't changed, use cached version\n} else {\n const freshData = await res2.json();\n}\n```\n\n### Axios / ky / other clients\n\nMost HTTP clients handle `304` responses automatically when configured with an interceptor or cache adapter.\n\n## Configuration\n\nETags are enabled by default. To disable them, set `etag.enabled` to `false` in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n etag: {\n enabled: false,\n },\n});\n```\n\nWhen disabled, GET responses use standard `c.json()` with no ETag headers or `304` handling.\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `enabled` | `true` | Include ETag headers on GET/LIST/VIEW responses |\n\n## Technical details\n\n- **Weak ETags** (`W/\"...\"`) — semantically equivalent responses, not byte-identical\n- **SHA-256 truncated to 16 hex chars** — sufficient for collision avoidance, keeps the header small\n- **Web Crypto API** — uses `crypto.subtle.digest()`, available in Cloudflare Workers and Node 18+\n- **No dependencies** — zero additional packages required"
|
|
299
195
|
},
|
|
300
|
-
"compiler/using-the-api/crud": {
|
|
196
|
+
"compiler/targets/hono-api/using-the-api/crud": {
|
|
301
197
|
"title": "CRUD Endpoints",
|
|
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#### Cascade\n\nWhen a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** children and **cross-feature** children (e.g. `applications` referencing `jobs` from a different feature directory) — receives the same `deletedAt` / `deletedBy` stamp in the same request. The cascade UPDATE always AND-merges the child's own firewall (`build<Child>FirewallConditions(ctx)`), so a delete in one tenant can never reach a child row in another tenant.\n\nIf a child column declared `.references(() => parent.id, { onDelete: '...' })`, the cascade respects that intent — only `cascade` and `set null` participate. FKs without `onDelete` are cascaded for backwards-compat with the legacy shape.\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."
|
|
198
|
+
"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/targets/hono-api/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#### Cascade\n\nWhen a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** children and **cross-feature** children (e.g. `applications` referencing `jobs` from a different feature directory) — receives the same `deletedAt` / `deletedBy` stamp in the same request. The cascade UPDATE always AND-merges the child's own firewall (`build<Child>FirewallConditions(ctx)`), so a delete in one tenant can never reach a child row in another tenant.\n\nIf a child column declared `.references(() => parent.id, { onDelete: '...' })`, the cascade respects that intent — only `cascade` and `set null` participate. FKs without `onDelete` are cascaded for backwards-compat with the legacy shape.\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/targets/hono-api/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/targets/hono-api/using-the-api/errors) for the complete reference of error codes by security layer."
|
|
303
199
|
},
|
|
304
|
-
"compiler/using-the-api/errors": {
|
|
200
|
+
"compiler/targets/hono-api/using-the-api/errors": {
|
|
305
201
|
"title": "Errors",
|
|
306
202
|
"content": "The generated API returns structured error responses with consistent fields across all security layers.\n\n## Status Codes\n\n| Code | Meaning | When |\n|------|---------|------|\n| `200` | OK | Successful GET, PATCH, DELETE |\n| `201` | Created | Successful POST |\n| `207` | Multi-Status | Batch operation with mixed results |\n| `400` | Bad Request | Guard violation, validation error, invalid input |\n| `401` | Unauthorized | Missing or expired authentication |\n| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |\n| `404` | Not Found | Record doesn't exist (or firewall blocked with `errorMode: 'hide'`) |\n| `429` | Too Many Requests | Rate limit exceeded |\n\n## Error Response Format\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `error` | string | Human-readable error message |\n| `layer` | string | Security layer that rejected the request |\n| `code` | string | Machine-readable error code |\n| `details` | object | Layer-specific context (optional) |\n| `hint` | string | Actionable guidance for resolution (optional) |\n\n## Errors by Security Layer\n\n### Authentication (401)\n\nMissing or invalid authentication tokens.\n\n```json\n{\n \"error\": \"Authentication required\",\n \"layer\": \"authentication\",\n \"code\": \"AUTH_MISSING\",\n \"hint\": \"Include Authorization header with Bearer token\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `AUTH_MISSING` | No Authorization header provided |\n| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |\n| `AUTH_EXPIRED` | Token has expired |\n| `AUTH_RATE_LIMITED` | Too many auth attempts |\n\n### Firewall (403)\n\nRecords outside the user's firewall scope return **403 Forbidden** by default with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nFirewall filtering is transparent — the query is scoped by `WHERE organizationId = ?` so inaccessible records simply don't appear in results.\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `FIREWALL_NOT_FOUND` | Record not found behind firewall (wrong org, soft-deleted, or doesn't exist) |\n| `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |\n| `FIREWALL_USER_ISOLATION` | Record belongs to another user |\n| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |\n\nFor security-hardened deployments, set `errorMode: 'hide'` in your firewall config to return opaque **404 Not Found** responses instead. This prevents attackers from distinguishing between \"record exists but you can't access it\" and \"record doesn't exist\".\n\n### Access (403)\n\nAccess violations return **403 Forbidden** when the user's role doesn't match the required roles for the operation.\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `ACCESS_ROLE_REQUIRED` | User doesn't have the required role |\n| `ACCESS_CONDITION_FAILED` | Record-level access condition not met |\n| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |\n| `ACCESS_NO_ORG` | No active organization set |\n\n### Guards (400)\n\nGuard violations return **400 Bad Request** when the request body contains fields that aren't allowed.\n\n```json\n{\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": {\n \"fields\": [\"stage\"]\n },\n \"hint\": \"These fields are set automatically or must be omitted\"\n}\n```\n\n**Error codes:**\n\n| Code | Description |\n|------|-------------|\n| `GUARD_FIELD_NOT_CREATEABLE` | Field not in `createable` list |\n| `GUARD_FIELD_NOT_UPDATABLE` | Field not in `updatable` list |\n| `GUARD_FIELD_PROTECTED` | Field is action-only (protected) |\n| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |\n| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |\n\n### Masking\n\nMasking doesn't produce errors — it silently transforms field values in the response.\n\n## Batch Errors\n\nBatch operations can return:\n- **201** — All records succeeded\n- **207** — Partial success (some records failed)\n- **400** — Atomic mode and at least one record failed (all rolled back)\n\n### Partial Success (207)\n\n```json\n{\n \"success\": [{ \"id\": \"app_1\", \"candidateId\": \"cand_101\", \"stage\": \"applied\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"record\": { \"candidateId\": \"cand_102\", \"jobId\": \"job_201\", \"stage\": \"interview\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"stage\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": { \"total\": 2, \"succeeded\": 1, \"failed\": 1, \"atomic\": false }\n}\n```\n\n### Atomic Failure (400)\n\n```json\n{\n \"error\": \"Batch operation failed in atomic mode\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_ATOMIC_FAILED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { \"error\": \"Not found\", \"code\": \"NOT_FOUND\" }\n },\n \"hint\": \"Transaction rolled back. Fix the error and retry the entire batch.\"\n}\n```\n\n**Batch error codes:**\n\n| Code | Description |\n|------|-------------|\n| `BATCH_SIZE_EXCEEDED` | Too many records in a single request |\n| `BATCH_ATOMIC_FAILED` | Atomic batch failed, all changes rolled back |\n| `BATCH_MISSING_IDS` | Batch update/delete missing required IDs |"
|
|
307
203
|
},
|
|
308
|
-
"compiler/using-the-api": {
|
|
204
|
+
"compiler/targets/hono-api/using-the-api": {
|
|
309
205
|
"title": "Using the API",
|
|
310
|
-
"content": "When you run `quickback compile`, Quickback generates a complete REST API from your definitions. This section covers how to use the generated endpoints.\n\n## Base URL\n\nAll generated endpoints are served under `/api/v1/`:\n\n```\nhttps://your-api.com/api/v1/{resource}\n```\n\nThe resource name is derived from the filename: `jobs.ts` → `/api/v1/jobs`.\n\n## Endpoint Overview\n\nFor each resource with `export default defineTable(...)`:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/{resource}` | List records (paginated) |\n| `GET` | `/api/v1/{resource}/:id` | Get single record |\n| `POST` | `/api/v1/{resource}` | Create record |\n| `PATCH` | `/api/v1/{resource}/:id` | Update record |\n| `DELETE` | `/api/v1/{resource}/:id` | Delete record |\n| `POST` | `/api/v1/{resource}/batch` | Batch create |\n| `PATCH` | `/api/v1/{resource}/batch` | Batch update |\n| `DELETE` | `/api/v1/{resource}/batch` | Batch delete |\n\n## Guides\n\n- [CRUD Endpoints](/compiler/using-the-api/crud) — Detailed CRUD endpoint reference\n- [Query Parameters](/compiler/using-the-api/query-params) — Filtering, pagination, and sorting\n- [Batch Operations](/compiler/using-the-api/batch-operations) — Bulk create, update, delete with atomic mode\n- [Views API](/compiler/using-the-api/views-api) — Column-level projections\n- [Actions API](/compiler/using-the-api/actions-api) — Custom business logic endpoints\n- [Errors](/compiler/using-the-api/errors) — Error responses and HTTP status codes"
|
|
206
|
+
"content": "When you run `quickback compile`, Quickback generates a complete REST API from your definitions. This section covers how to use the generated endpoints.\n\n## Base URL\n\nAll generated endpoints are served under `/api/v1/`:\n\n```\nhttps://your-api.com/api/v1/{resource}\n```\n\nThe resource name is derived from the filename: `jobs.ts` → `/api/v1/jobs`.\n\n## Endpoint Overview\n\nFor each resource with `export default defineTable(...)`:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/{resource}` | List records (paginated) |\n| `GET` | `/api/v1/{resource}/:id` | Get single record |\n| `POST` | `/api/v1/{resource}` | Create record |\n| `PATCH` | `/api/v1/{resource}/:id` | Update record |\n| `DELETE` | `/api/v1/{resource}/:id` | Delete record |\n| `POST` | `/api/v1/{resource}/batch` | Batch create |\n| `PATCH` | `/api/v1/{resource}/batch` | Batch update |\n| `DELETE` | `/api/v1/{resource}/batch` | Batch delete |\n\n## Guides\n\n- [CRUD Endpoints](/compiler/targets/hono-api/using-the-api/crud) — Detailed CRUD endpoint reference\n- [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params) — Filtering, pagination, and sorting\n- [Batch Operations](/compiler/targets/hono-api/using-the-api/batch-operations) — Bulk create, update, delete with atomic mode\n- [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Column-level projections\n- [Actions API](/compiler/targets/hono-api/using-the-api/actions-api) — Custom business logic endpoints\n- [Errors](/compiler/targets/hono-api/using-the-api/errors) — Error responses and HTTP status codes"
|
|
311
207
|
},
|
|
312
|
-
"compiler/using-the-api/openapi": {
|
|
208
|
+
"compiler/targets/hono-api/using-the-api/openapi": {
|
|
313
209
|
"title": "OpenAPI Spec",
|
|
314
210
|
"content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: 'src/lib/api-types.gen.ts', // emit straight into your client app\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. Skipped automatically when `openapi.generate` is `false`.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```"
|
|
315
211
|
},
|
|
316
|
-
"compiler/using-the-api/query-params": {
|
|
212
|
+
"compiler/targets/hono-api/using-the-api/query-params": {
|
|
317
213
|
"title": "Query Parameters",
|
|
318
214
|
"content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\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### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your definition:\n\n```typescript\ncrud: {\n list: {\n access: { roles: [\"recruiter\"] },\n pageSize: 25, // Default limit\n maxPageSize: 100, // Maximum allowed limit\n },\n},\n```\n\n### Response Shape\n\n```json\n{\n \"data\": [ /* records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 50,\n \"count\": 12\n }\n}\n```\n\n- `count` — number of records returned on this page\n- `total` — total matching records across all pages (only when `?total=true`, see below)\n\n## Sorting\n\nSort by one or more fields. Use the `-` prefix for descending order.\n\n### Multi-Sort (Recommended)\n\n```bash\n# Sort by status ascending, then createdAt descending\nGET /api/v1/jobs?sort=status,-createdAt\n\n# Single field descending\nGET /api/v1/jobs?sort=-createdAt\n\n# Multiple fields\nGET /api/v1/jobs?sort=department,-salaryMax,title\n```\n\n| Prefix | Direction |\n|--------|-----------|\n| (none) | Ascending |\n| `-` | Descending |\n\n### Legacy Format\n\nThe original `sort` + `order` format is still supported for backwards compatibility:\n\n```bash\nGET /api/v1/jobs?sort=title&order=asc\n```\n\n| Parameter | Values | Default | Description |\n|-----------|--------|---------|-------------|\n| `sort` | Any column name | `createdAt` | Field to sort by |\n| `order` | `asc`, `desc` | `desc` | Sort direction |\n\nWhen the multi-sort format is detected (comma or `-` prefix), the `order` parameter is ignored.\n\n## Field Selection\n\nSelect which columns to return using `?fields=`. Available on LIST and GET routes (not Views — they define their own field set).\n\n```bash\n# Return only id, title, and status\nGET /api/v1/jobs?fields=id,title,status\n\n# Combine with other query params\nGET /api/v1/jobs?fields=id,title,status&status=open&sort=-createdAt\n\n# Single record\nGET /api/v1/jobs/job_123?fields=id,title,salaryMin,salaryMax\n```\n\nAll columns are available including system columns (`id`, `organizationId`, `createdAt`, `modifiedAt`, etc.). Invalid field names are silently ignored. If no valid fields are provided, all columns are returned.\n\n**Security**: Masking still applies to selected fields. Requesting `?fields=ssn` will return the masked value, not the raw data.\n\n## Total Count\n\nGet the total number of matching records across all pages by adding `?total=true`. Available on LIST and VIEW routes.\n\n```bash\nGET /api/v1/jobs?status=open&total=true\n```\n\n```json\n{\n \"data\": [ /* 25 records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 0,\n \"count\": 25,\n \"total\": 142\n }\n}\n```\n\nThis is opt-in because it runs an additional `COUNT(*)` query. Only use it when you need the total (e.g., for pagination UI).\n\n## Search\n\nFull-text search across all text columns using `?search=`. Available on LIST and VIEW routes.\n\n```bash\n# Search across all text fields\nGET /api/v1/jobs?search=engineer\n\n# Combine with filters\nGET /api/v1/jobs?search=engineer&status=open\n```\n\nThe search generates an OR'd `LIKE` condition across all `text()` columns in your schema:\n\n```sql\nWHERE (title LIKE '%engineer%' OR department LIKE '%engineer%')\n```\n\nOnly columns defined with `text()` in your Drizzle schema are searchable. Non-text columns (integers, timestamps, UUIDs, blobs) are automatically excluded.\n\n## Complete Example\n\nCombine all query parameters together:\n\n```bash\nGET /api/v1/jobs?fields=id,title,status,salaryMin&status=open&salaryMin.gte=100000&search=engineer&sort=salaryMin,-createdAt&limit=10&offset=20&total=true\n```\n\nThis request:\n1. **Selects** only `id`, `title`, `status`, `salaryMin` fields\n2. **Filters** to open jobs with salaryMin >= 100000\n3. **Searches** text columns for \"engineer\"\n4. **Sorts** by salaryMin ascending, then createdAt descending\n5. **Paginates** with 10 results starting at offset 20\n6. **Counts** total matching records\n\n## Parameter Summary\n\n| Parameter | Applies To | Description |\n|-----------|-----------|-------------|\n| `limit` | LIST, VIEW | Page size (default: 50, max: 100) |\n| `offset` | LIST, VIEW | Skip N records |\n| `sort` | LIST, VIEW | Sort fields (comma-separated, `-` prefix for desc) |\n| `order` | LIST, VIEW | Legacy sort direction (`asc` or `desc`) |\n| `fields` | LIST, GET | Comma-separated column names to return |\n| `total` | LIST, VIEW | Set to `true` to include total count |\n| `search` | LIST, VIEW | Search text across all text columns |\n| `field=value` | LIST, VIEW | Filter by exact match |\n| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |"
|
|
319
215
|
},
|
|
320
|
-
"compiler/using-the-api/views-api": {
|
|
216
|
+
"compiler/targets/hono-api/using-the-api/views-api": {
|
|
321
217
|
"title": "Views API",
|
|
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"
|
|
218
|
+
"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/targets/hono-api/using-the-api/query-params) — Full query parameter reference\n- [Access Control](/compiler/definitions/access) — Role-based access configuration"
|
|
219
|
+
},
|
|
220
|
+
"compiler/targets": {
|
|
221
|
+
"title": "Compile Targets",
|
|
222
|
+
"content": "The Quickback Compiler reads a single set of definitions — schema, firewall, access, guards, masking, views, actions — and emits production output for the target you choose.\n\n## The two targets\n\n### [Quickback for Hono API](/compiler/targets/hono-api)\n\nGenerates a complete Hono application: routes, middleware, types, OpenAPI spec, MCP server. Pair with **Cloudflare D1** for SQLite-at-the-edge or **Neon** for full PostgreSQL with database-level RLS.\n\n```typescript\nproviders: {\n runtime: defineRuntime('cloudflare'),\n database: defineDatabase('cloudflare-d1'),\n auth: defineAuth('better-auth'),\n}\n```\n\nUse this target when you want Quickback to generate the entire API surface, not just security policies.\n\n### [Quickback for Supabase](/compiler/targets/supabase-rls)\n\nGenerates PostgreSQL Row Level Security policies for Supabase. Keep Supabase Auth, Storage, and Realtime — Quickback adds the security layer beneath your application code.\n\n```typescript\nproviders: {\n runtime: defineRuntime('supabase'),\n database: defineDatabase('supabase'),\n auth: defineAuth('supabase-auth'),\n}\n```\n\nUse this target when you're already on Supabase and want a typed DSL for RLS.\n\n## At a glance\n\n| | Hono API | Supabase RLS |\n|---|----------|--------------|\n| What's generated | Routes, middleware, types, OpenAPI, MCP, RLS (Neon only) | RLS policies + helper functions only |\n| Database | Cloudflare D1 or Neon Postgres | Supabase Postgres |\n| Auth | Better Auth | Supabase Auth |\n| Application code | Compiler-generated | You write your own |\n| Deployment | `wrangler deploy` (or any Hono runtime) | `supabase db push` |\n\n## The shared core\n\nWhichever target you pick, the input is the same. See [Definitions](/compiler/definitions) for the DSL that powers both."
|
|
223
|
+
},
|
|
224
|
+
"compiler/targets/supabase-rls": {
|
|
225
|
+
"title": "Quickback for Supabase RLS",
|
|
226
|
+
"content": "**Quickback for Supabase RLS** compiles the same `defineTable()` definitions into PostgreSQL Row Level Security policies for Supabase. You keep Supabase Auth, Storage, and Realtime — Quickback adds the database-level security layer.\n\n## Who this is for\n\nYou're already on Supabase (or want to be) and you want:\n\n- **Database-level security** — RLS policies enforced even if a service role key leaks\n- **A type-safe DSL** — write security rules in TypeScript, compile to SQL\n- **One source of truth** — the same `firewall` and `access` config that powers a Quickback Hono API also generates RLS policies\n\nWhat you don't get from this target: generated API routes, batch endpoints, OpenAPI spec, MCP server. Those live with [Quickback for Hono API](/compiler/targets/hono-api). For Supabase you bring your own application code (PostgREST, Edge Functions, or your own server) and the RLS policies enforce security beneath it.\n\n## What compiles to RLS\n\n| Definition | Compiles to |\n|------------|-------------|\n| `defineTable({ schema })` | `CREATE TABLE` + Drizzle schema |\n| `firewall: [...]` | `FOR ALL USING` policies (data isolation) |\n| `access.roles: [...]` | `FOR SELECT/INSERT/UPDATE/DELETE USING` policies (role checks) |\n| `defineActions()` | **Not compiled** — implement in Edge Functions or your app |\n| `views` | **Not compiled** — use Postgres views or column lists |\n| `masking` | **Not compiled** — runtime concern, handle in app code |\n| `guards` | **Not compiled** — runtime concern, handle in app code |\n\nSee [Mappings](/compiler/targets/supabase-rls/mappings) for full examples and [Limitations](/compiler/targets/supabase-rls/limitations) for what to handle in app code.\n\n## Quick start\n\n```typescript title=\"quickback/quickback.config.ts\"\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```bash\nquickback compile\nsupabase db push\n```\n\nThe compiler emits RLS migrations under `supabase/migrations/`. See [Setup](/compiler/targets/supabase-rls/setup) for the full flow.\n\n## In this section\n\n- **[Setup](/compiler/targets/supabase-rls/setup)** — Configure the target, compile, apply migrations\n- **[Mappings](/compiler/targets/supabase-rls/mappings)** — Which definitions become which RLS policies\n- **[Limitations](/compiler/targets/supabase-rls/limitations)** — What doesn't compile and how to handle it"
|
|
227
|
+
},
|
|
228
|
+
"compiler/targets/supabase-rls/limitations": {
|
|
229
|
+
"title": "Limitations",
|
|
230
|
+
"content": "The Supabase target compiles **schema, firewall, and access** to RLS. The other Quickback primitives are runtime concerns that RLS can't express. This page lists what doesn't compile and where to handle it.\n\n## Actions\n\n`defineActions()` describes custom endpoints with input validation, role checks, and side effects. RLS only governs row access, not arbitrary procedures.\n\n**Where to handle them:**\n\n- **Supabase Edge Functions** — port the action body to a TypeScript Deno function. Role checks happen in the function; the underlying database mutations still pass through your RLS policies.\n- **Postgres functions** — for simple state transitions, write a `CREATE FUNCTION` and call it via `supabase.rpc()`. Use `SECURITY INVOKER` (the default) so RLS still applies.\n- **Your application server** — any backend you already run can host the action, with the JWT forwarded to Supabase for the underlying writes.\n\n## Views\n\nQuickback `views` define column-level projections per role (e.g. \"members see name + email; admins also see salary\"). RLS gates rows, not columns.\n\n**Where to handle them:**\n\n- **Postgres views** — `CREATE VIEW` with `SELECT` lists matching each Quickback view. Apply RLS to the view or the underlying table.\n- **Column lists in queries** — pass the projection at the application layer: `supabase.from('users').select('id, name, email')`.\n- **Column-level grants** — `GRANT SELECT (col1, col2) ON table TO role` for fine-grained server-side restriction.\n\n## Masking\n\nMasking redacts sensitive fields per role at response time (email → `j***@example.com`, SSN → `***-**-1234`). This is purely a runtime transformation — the data is in the row, RLS just decides whether the row is returned.\n\n**Where to handle it:**\n\n- **Edge Functions or your server** — apply the mask in the layer that serializes the response.\n- **Postgres functions** — for SQL-driven masking, write a wrapper view or function that applies the mask conditionally on `auth.jwt() ->> 'role'`.\n\n## Guards\n\n`guards` block field modifications based on row state, role, or external context (e.g. \"members can change `notes` but not `status`; only admins can set `archived`\"). Some of this can be expressed with RLS `WITH CHECK`, but the full Quickback guard model is richer than RLS supports.\n\n**Where to handle them:**\n\n- **`WITH CHECK` clauses** — simple field-level guards (e.g. \"only admins can set `archived = true`\") can sometimes be expressed via more granular `FOR UPDATE` policies.\n- **Triggers** — `BEFORE UPDATE` triggers can `RAISE EXCEPTION` if a guarded field is modified by a non-eligible role.\n- **Edge Functions / app server** — for anything stateful or context-dependent, validate guards in the layer that issues the update.\n\n## Generated API routes, batch ops, OpenAPI, MCP\n\nThese are Hono-target features. The Supabase target doesn't generate application code — your app talks to Supabase directly (PostgREST, Edge Functions, or your own server).\n\nIf you want generated routes alongside RLS, consider compiling to the [Hono target with Neon](/compiler/targets/hono-api/database/neon), which gives you both the generated API and database-level RLS."
|
|
231
|
+
},
|
|
232
|
+
"compiler/targets/supabase-rls/mappings": {
|
|
233
|
+
"title": "Mappings",
|
|
234
|
+
"content": "This page shows how each Quickback primitive maps to RLS policy SQL. The same `firewall` and `access` config used by the [Hono target](/compiler/targets/hono-api) generates these policies — no Supabase-specific re-authoring required.\n\n## Schema → Tables\n\n`defineTable({ schema })` compiles to a Drizzle PostgreSQL schema and a `CREATE TABLE` statement. RLS is enabled on the table by default:\n\n```sql\nALTER TABLE projects ENABLE ROW LEVEL SECURITY;\n```\n\n## Firewall → `FOR ALL USING`\n\nFirewall rules isolate data by tenant or owner. They become a single `FOR ALL USING` policy applied to every operation.\n\n**Org-scoped:**\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n]\n```\n\n```sql\nCREATE POLICY \"projects_firewall\" ON projects FOR ALL\nUSING (organization_id = public.get_active_org_id());\n```\n\n**User-scoped:**\n\n```typescript\nfirewall: [\n { field: 'userId', equals: 'ctx.userId' },\n]\n```\n\n```sql\nCREATE POLICY \"preferences_firewall\" ON preferences FOR ALL\nUSING (user_id = auth.uid());\n```\n\n## Access → `FOR SELECT/INSERT/UPDATE/DELETE USING`\n\nAccess rules layer role-based checks on top of the firewall. Each operation gets its own policy.\n\n```typescript\naccess: {\n roles: ['admin', 'member'],\n list: { roles: ['admin', 'member'] },\n create: { roles: ['admin'] },\n update: { roles: ['admin'] },\n delete: { roles: ['admin'] },\n}\n```\n\n```sql\nCREATE POLICY \"projects_select\" ON projects FOR SELECT\nUSING (\n organization_id = public.get_active_org_id()\n AND public.has_any_role(ARRAY['admin', 'member'])\n);\n\nCREATE POLICY \"projects_insert\" ON projects FOR INSERT\nWITH CHECK (\n organization_id = public.get_active_org_id()\n AND public.has_any_role(ARRAY['admin'])\n);\n```\n\n## Defense in depth — anon deny\n\nEvery generated table gets an explicit deny policy for the `anon` role:\n\n```sql\nCREATE POLICY \"projects_deny_anon\" ON projects FOR ALL\nTO anon\nUSING (false);\n```\n\nUnauthenticated requests are blocked at the database level even if a policy elsewhere is misconfigured.\n\n## Helper functions\n\nQuickback emits a set of helper functions in `0100_create_rls_helpers.sql` that the policies reference:\n\n| Function | Purpose |\n|----------|---------|\n| `get_active_org_id()` | Returns the user's active organization from `user_sessions` |\n| `has_any_role(roles[])` | Checks if the user has any of the listed roles in the active org |\n| `has_org_role(role)` | Checks for a single specific role |\n| `is_org_member()` | Checks org membership |\n| `get_user_role()` | Returns the user's role in the active org |\n\nThese are used by the generated policies but you can also call them from views, triggers, or stored procedures.\n\n## What does not compile\n\n`defineActions()`, `views`, `masking`, and runtime `guards` do **not** become RLS — see [Limitations](/compiler/targets/supabase-rls/limitations)."
|
|
235
|
+
},
|
|
236
|
+
"compiler/targets/supabase-rls/setup": {
|
|
237
|
+
"title": "Setup",
|
|
238
|
+
"content": "## Prerequisites\n\n- A Supabase project (free tier is fine for development)\n- The Supabase CLI installed: `npm install -g supabase`\n- A Quickback project (`quickback create` or existing)\n\n## 1. Configure the target\n\n```typescript title=\"quickback/quickback.config.ts\"\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\nThe `supabase-auth` provider tells Quickback to emit RLS policies that reference `auth.uid()` — Supabase's built-in JWT claim function — rather than the Better Auth equivalents used by the Neon target.\n\n## 2. Compile\n\n```bash\nquickback compile\n```\n\nThis generates:\n\n```\nsupabase/\n├── migrations/\n│ ├── 0100_create_rls_helpers.sql # get_active_org_id(), has_any_role(), etc.\n│ ├── 0101_create_rls_policies.sql # Per-table SELECT/INSERT/UPDATE/DELETE policies\n│ └── 0102_create_audit_triggers.sql # Optional audit logging\nsrc/\n├── db/\n│ └── schema.ts # Drizzle schema (typed access from your app)\n```\n\n## 3. Apply migrations\n\n```bash\nsupabase db push\n```\n\nSupabase applies the migrations to your remote project. RLS is enabled on every generated table and the deny-anon policy is installed.\n\n## 4. Use from your app\n\nQuickback for Supabase doesn't generate API routes. Your application code (PostgREST, Edge Functions, your own server) talks to Supabase as normal — the RLS policies are enforced beneath it.\n\n```typescript\n\nconst supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {\n global: { headers: { Authorization: `Bearer ${userJwt}` } },\n});\n\n// RLS policies generated by Quickback enforce row-level access\nconst { data } = await supabase.from('projects').select('*');\n```\n\n## Updating the schema\n\nEdit your `defineTable()` files, recompile, and push:\n\n```bash\nquickback compile\nsupabase db push\n```\n\nThe compiler diffs against the previous compilation and emits a new migration only for what changed.\n\n## Comparison with the Neon target\n\n| | Supabase | Neon |\n|---|----------|------|\n| Auth function | `auth.uid()` | `auth.user_id()` |\n| Auth provider | Supabase Auth | Better Auth + Neon Authorize |\n| Users table | `auth.users` | `public.users` |\n| API code generated | No | Yes (Hono routes) |\n\nBoth targets emit RLS policies. The difference is who issues the JWTs and where the application logic lives."
|
|
239
|
+
},
|
|
240
|
+
"compiler/troubleshooting": {
|
|
241
|
+
"title": "Troubleshooting",
|
|
242
|
+
"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### Recovering a previous `src/` tree\n\nThe CLI archives the previous `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` before each compile (most recent 3 retained). If a generator regression silently dropped a file you depended on, restore it from the latest archive:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/ ← latest\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n\n# Restore the whole tree (back-out a bad compile):\nrm -rf src\ncp -R quickback/.archives/src-2026-04-27T16-31-02-014 src\n\n# …or grep for what disappeared:\ngrep -r \"missingExportName\" quickback/.archives/src-2026-04-27T16-31-02-014/\n```\n\nAnything in `src/` not produced by the latest compile is removed on every compile — see [CLI → Compile Definitions](/compiler/cloud-compiler/cli#compile-definitions) for the full contract.\n\n## See Also\n\n- [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting) — CLI and authentication issues\n- [Errors](/compiler/targets/hono-api/using-the-api/errors) — Complete error code reference\n- [Firewall](/compiler/definitions/firewall) — Data isolation configuration\n- [Guards](/compiler/definitions/guards) — Field modification rules"
|
|
323
243
|
},
|
|
324
244
|
"index": {
|
|
325
245
|
"title": "Quickback Documentation",
|
|
326
|
-
"content": "# Quickback Documentation\n\nQuickback is a **backend compiler**. Define your database schema and security rules in TypeScript — Quickback compiles them into a
|
|
246
|
+
"content": "# Quickback Documentation\n\nQuickback is a **backend compiler**. Define your database schema and security rules in TypeScript — Quickback compiles them into a Hono API or PostgreSQL Row Level Security policies. Pair the output with the Quickback Stack for a complete Supabase alternative on Cloudflare.\n\n## Quick start\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\nquickback compile\n```\n\n## How it works\n\nWrite ~50 lines of definitions. Get a production codebase.\n\n```\ndefineTable() ─┐\n ├─► Compiler ─► Hono API (Cloudflare D1 / Neon)\ndefineActions()─┘ └► RLS policies (Supabase)\n```\n\nEvery API request passes through four security layers:\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\n```\n\n**Secure by default.** Nothing is accessible until you explicitly open it up. See [Definitions](/compiler/definitions) for the full security model.\n\n---\n\n## The two products\n\n### Quickback Compiler\n\n[**Quickback Compiler**](/compiler) — the build tool. Define your schema and security rules in TypeScript and compile to one of two targets:\n\n- **[Quickback for Hono API](/compiler/targets/hono-api)** — A complete Hono application on Cloudflare D1 or Neon, with CRUD, batch endpoints, OpenAPI, and an MCP server.\n- **[Quickback for Supabase](/compiler/targets/supabase-rls)** — PostgreSQL Row Level Security policies for Supabase. Keep Supabase Auth, Storage, and Realtime; Quickback adds the security layer.\n\nThe same `defineTable()` definitions work for both targets.\n\n**Start here:**\n- **[Getting Started](/compiler/getting-started)** — Create your first project\n- **[Definitions](/compiler/definitions)** — Schema, Firewall, Access, Guards, Masking, Views, Actions\n- **[Cloud Compiler](/compiler/cloud-compiler)** — CLI, MCP server, authentication\n- **[Claude Code Skill](/compiler/claude-code-skill)** — AI-powered authoring assistance\n\n---\n\n### Quickback Stack\n\nThe runtime services around your compiled code. Everything you need for a complete Supabase alternative on Cloudflare:\n\n- **[Auth](/stack/auth)** — Better Auth with email OTP, passkeys, organizations, admin\n- **[Storage](/stack/storage)** — KV (sessions, cache) and R2 (files)\n- **[Realtime](/stack/realtime)** — Durable Objects + WebSocket\n- **[Queues](/stack/queues)** — Background jobs and webhook delivery\n- **[Vector & AI](/stack/vector)** — Embeddings, semantic search\n- **[Webhooks](/stack/webhooks)** — Inbound (signed) and outbound (retried)\n- **[Quickback CMS](/stack/cms)** — Schema-driven admin UI\n- **[Account UI](/stack/account-ui)** — Pre-built auth and profile pages\n\nEverything runs on **your own Cloudflare account** — no Quickback infrastructure between you and your data.\n\n---\n\n### Changelog\n\n[**Changelog**](/changelog) — what's new in Quickback. Release notes, new features, and improvements."
|
|
327
247
|
},
|
|
328
|
-
"
|
|
329
|
-
"title": "
|
|
330
|
-
"content": "
|
|
248
|
+
"stack/account-ui/customization": {
|
|
249
|
+
"title": "Customization",
|
|
250
|
+
"content": "# Customization\n\nCustomize the Account UI to match your brand and messaging.\n\n**Standalone (template):** Configure via environment variables, edit `src/config/app.ts` directly, or use `setAppConfig()` for runtime overrides.\n\n**Library (npm):** Configure entirely via `setAppConfig()`. Import it from `quickback-better-auth-account-ui` instead of `@/config/app`.\n\n## Branding\n\n### App Identity\n\nSet your application's name and description:\n\n```bash\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\n```\n\nThese values appear in:\n- Page titles (`<title>Acme SaaS | Login</title>`)\n- Meta descriptions\n- UI headers and footers\n- Email templates\n\n### Visual Identity\n\n```bash\n# Primary theme color (used for buttons, links, accents)\nVITE_THEME_COLOR=#3b82f6\n\n# Company name (shown in footer, legal pages)\nVITE_COMPANY_NAME=Acme Corporation\n\n# Company address (shown in footer, receipts)\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n### Logo and Favicon\n\nPlace your branding assets in the `public/` directory:\n\n```\npublic/\n├── logo.png # Main logo (shown in header)\n├── favicon.ico # Browser favicon\n└── og-image.png # Social media preview image\n```\n\nThen update the paths in `src/config/app.ts`:\n\n```ts title=\"src/config/app.ts\"\nbranding: {\n primaryColor: \"#1e293b\",\n logoUrl: \"/logo.png\",\n faviconUrl: \"/favicon.ico\"\n},\n```\n\nOr set them at runtime in `src/main.tsx`:\n\n```ts\n\nsetAppConfig({\n branding: {\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n## Custom Labels\n\nOverride default UI labels using runtime configuration:\n\n```ts\n\nsetAppConfig({\n labels: {\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n company: 'My Company',\n organizations: 'Workspaces', // Rename \"Organizations\" to \"Workspaces\"\n },\n});\n```\n\n### Available Labels\n\n| Label | Default | Usage |\n|-------|---------|-------|\n| `terms` | \"Terms of Service\" | Footer link text |\n| `privacy` | \"Privacy Policy\" | Footer link text |\n| `support` | \"Contact Support\" | Footer link text |\n| `company` | (from `VITE_COMPANY_NAME`) | Footer company name |\n| `organizations` | \"Organizations\" | Navigation and page titles |\n\n## Custom Messages\n\nCustomize user-facing messages:\n\n```ts\n\nsetAppConfig({\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n contactAdminForInvite: \"Contact your team lead to get access.\",\n noPendingInvitations: \"No pending invites at this time\",\n createOrganization: \"Create Workspace\",\n // ... more messages\n },\n});\n```\n\n### Available Messages\n\n| Message | Default | Usage |\n|---------|---------|-------|\n| `noOrganizations` | \"You're not a member of any organizations yet.\" | Empty organizations list |\n| `contactAdminForInvite` | \"Contact an admin to be invited to an organization.\" | Organizations page help text |\n| `noPendingInvitations` | \"You have no pending invitations\" | Empty invitations list |\n| `createOrganization` | \"Create Organization\" | Button text |\n| `accountInformation` | \"Account Information\" | Profile section header |\n| `timezone` | \"Timezone\" | Label for timezone field |\n| `serverLocation` | \"Server Location\" | Label for server location |\n| `memberSince` | \"Member since\" | Account age label |\n| `pendingInvitations` | \"Pending Invitations\" | Section header |\n| `invitedAs` | \"Invited as\" | Invitation role label |\n| `accept` | \"Accept\" | Accept invitation button |\n| `decline` | \"Decline\" | Decline invitation button |\n| `userFallback` | \"User\" | Fallback for missing name |\n| `noEmailProvided` | \"No email provided\" | Fallback for missing email |\n| `more` | \"More\" | Pagination/load more text |\n| `total` | \"total\" | Total count label |\n| `active` | \"Active\" | Active status label |\n| `new` | \"New\" | New item label |\n\n## Route Customization\n\nCustomize route paths using runtime configuration:\n\n```ts\n\nsetAppConfig({\n routes: {\n public: {\n home: '/',\n login: '/sign-in', // Change from /login\n signup: '/sign-up', // Change from /signup\n forgotPassword: '/reset-password',\n welcome: '/getting-started',\n },\n authenticated: {\n dashboard: '/dashboard',\n profile: '/my-account',\n settings: '/preferences',\n },\n organizations: {\n list: '/workspaces', // Rename route\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n});\n```\n\n## Password Requirements\n\nCustomize password validation rules:\n\n```ts\n\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12, // Minimum password length\n maxLength: 128, // Maximum password length\n requireUppercase: true, // Must have uppercase letter\n requireLowercase: true, // Must have lowercase letter\n requireNumbers: true, // Must have number\n requireSymbols: true, // Must have special character\n },\n },\n});\n```\n\nPassword requirements are displayed to users during signup and password changes.\n\n## Session Duration\n\nControl how long users stay logged in:\n\n```ts\n\nsetAppConfig({\n auth: {\n sessionDuration: 7 * 24 * 60 * 60, // 7 days in seconds\n },\n});\n```\n\n## Email Customization\n\nConfigure email sender information:\n\n```bash\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=help@acme.com\n```\n\nThe `fromName` is automatically set to `VITE_APP_NAME`:\n\n```ts\n// Emails will show:\n// From: \"Acme SaaS <noreply@acme.com>\"\n```\n\n## URL Configuration\n\nConfigure URLs for external links:\n\n```bash\n# Main application (redirected to after login)\nVITE_QUICKBACK_APP_URL=https://app.acme.com\n\n# Organization/tenant URL pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}\n\n# Support pages\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/legal/privacy\nVITE_TERMS_URL=https://acme.com/legal/terms\n```\n\n### Tenant URL Patterns\n\nThe tenant URL pattern supports flexible organization routing:\n\n```bash\n# Path-based routing\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n# Result: https://app.acme.com/organizations/acme-corp\n\n# Subdomain routing\nVITE_TENANT_URL_PATTERN=https://{slug}.acme.com\n# Result: https://acme-corp.acme.com\n\n# Custom pattern\nVITE_TENANT_URL_PATTERN=/workspace/{slug}/dashboard\n# Result: https://app.acme.com/workspace/acme-corp/dashboard\n```\n\n## Complete Customization Example\n\nHere's a complete example showing all customization options:\n\n```ts title=\"src/main.tsx\"\n\n// Apply customizations before rendering\nsetAppConfig({\n name: 'Acme SaaS',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/acme-logo.png',\n faviconUrl: '/favicon.ico',\n },\n\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n support: 'Help Center',\n },\n\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n contactAdminForInvite: 'Contact your team lead for access.',\n },\n\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n detail: (slug) => `/workspaces/${slug}`,\n },\n },\n\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n\n// Render app\n\nconst root = document.getElementById('root')!;\ncreateRoot(root).render(\n \n);\n```\n\n## Custom Styles\n\nOverride default styles with custom CSS:\n\n```css title=\"custom-styles.css\"\n/* Override primary color */\n:root {\n --primary: 59 130 246; /* Tailwind blue-500 */\n --primary-foreground: 255 255 255;\n}\n\n/* Custom logo size */\n.logo {\n width: 180px;\n height: auto;\n}\n\n/* Custom button styles */\n.btn-primary {\n background-color: var(--primary);\n border-radius: 8px;\n font-weight: 600;\n}\n```\n\nImport your custom CSS after the Account UI styles:\n\n```ts\n\n```\n\n## Next Steps\n\n- **[Worker Setup](/stack/account-ui/worker)** - Deploy your customized UI\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Complete configuration reference\n- **[Feature Flags](/stack/account-ui/features)** - Enable/disable features"
|
|
331
251
|
},
|
|
332
|
-
"
|
|
333
|
-
"title": "
|
|
334
|
-
"content": "
|
|
252
|
+
"stack/account-ui/environment-variables": {
|
|
253
|
+
"title": "Environment Variables",
|
|
254
|
+
"content": "# Environment Variables\n\nConfigure the Account UI by setting environment variables in your `.env` file or deployment platform.\n\n## Quick Setup — Single Variable\n\nFor the common \"unified deployment\" where API, Account, and CMS all live on the same Quickback origin, you only need **one** variable:\n\n```bash\n# Points at the Quickback Worker origin\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen `VITE_QUICKBACK_URL` is set, it's used as a fallback for the individual URL vars:\n\n| Individual var | Used first | Falls back to |\n|---|---|---|\n| `VITE_QUICKBACK_API_URL` | if set | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | if set | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | if set | `${VITE_QUICKBACK_URL}/cms` |\n\n## Required Variables\n\nAt minimum, you need one of:\n\n- **`VITE_QUICKBACK_URL`** — catch-all for the Quickback origin (recommended), **or**\n- **`VITE_QUICKBACK_API_URL`** — explicit API URL (use this if your API lives on a different subdomain from Account/CMS)\n\n### Split-subdomain setup\n\nIf your API, Account, and CMS live on separate custom subdomains, set them explicitly:\n\n```bash\n# Quickback API URL\nVITE_QUICKBACK_API_URL=https://api.example.com\n\n# Account UI URL (where the Account UI is deployed)\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# Optional: override Account/CMS URLs for cross-origin links\nVITE_QUICKBACK_ACCOUNT_URL=https://auth.example.com\nVITE_QUICKBACK_CMS_URL=https://cms.example.com\n```\n\n## App Identity\n\nConfigure your application's basic information:\n\n```bash\n# App name (displayed in UI)\nVITE_APP_NAME=My Application\n\n# Tagline (shown on landing pages)\nVITE_APP_TAGLINE=Build faster, ship sooner\n\n# Full description\nVITE_APP_DESCRIPTION=A complete platform for building modern web applications\n\n# Company information\nVITE_COMPANY_NAME=My Company Inc.\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n```\n\n## URLs\n\n### Main Application\n\n```bash\n# Your main application URL\n# Users will be redirected here after authentication\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Organization/Tenant URL pattern (optional)\n# Use {slug} as placeholder for organization identifier\n# Examples:\n# /organizations/{slug} -> app.example.com/organizations/acme\n# /workspace/{slug} -> app.example.com/workspace/acme\n# https://{slug}.example.com -> acme.example.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\n```\n\n### Support and Legal\n\n```bash\n# Support/help URL\nVITE_SUPPORT_URL=https://support.example.com\n\n# Privacy policy URL\nVITE_PRIVACY_URL=https://example.com/privacy\n\n# Terms of service URL\nVITE_TERMS_URL=https://example.com/terms\n```\n\n## Email Configuration\n\n```bash\n# From address for all emails\nVITE_EMAIL_FROM=noreply@example.com\n\n# Reply-to address\nVITE_EMAIL_REPLY_TO=support@example.com\n\n# Support email address\nVITE_SUPPORT_EMAIL=support@example.com\n\n# AWS Region for SES (if using AWS SES)\nVITE_EMAIL_REGION=us-east-1\n```\n\n## Branding\n\n```bash\n# Primary theme color (hex code)\nVITE_THEME_COLOR=#1e293b\n\n# SEO keywords (comma-separated)\nVITE_SEO_KEYWORDS=saas,authentication,account management\n```\n\n## Feature Flags\n\nEnable or disable features using boolean environment variables:\n\n### Authentication Features\n\n```bash\n# Enable user signup (default: true)\nENABLE_SIGNUP=true\n\n# Enable email verification after signup (default: true)\nENABLE_EMAIL_VERIFICATION=true\n\n# Disable email deliverability checks (default: false)\n# Set to true to skip checking if email addresses are deliverable\nDISABLE_EMAIL_STATUS_CHECK=false\n\n# Enable passkey (WebAuthn) login (default: true)\nENABLE_PASSKEY=true\n\n# Enable email OTP login and signup (default: true)\nENABLE_EMAIL_OTP=true\n\n# Enable email+password login and signup (default: false)\nENABLE_PASSWORD=false\n```\n\n### Account Management Features\n\n```bash\n# Enable file uploads (avatar, etc.) (default: false)\nVITE_ENABLE_FILE_UPLOADS=false\n```\n\n### Organization Features\n\n```bash\n# Enable multi-tenant organizations (default: true)\nENABLE_ORGANIZATIONS=true\n```\n\n### Admin Features\n\n```bash\n# Enable admin panel (default: true)\nENABLE_ADMIN=true\n```\n\n## Complete Example\n\nHere's a complete `.env` file with all common configuration:\n\n```bash title=\".env\"\n# ===== REQUIRED =====\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\n\n# ===== APP IDENTITY =====\nVITE_APP_NAME=Acme SaaS\nVITE_APP_TAGLINE=Build faster, ship sooner\nVITE_APP_DESCRIPTION=The complete platform for modern web applications\nVITE_COMPANY_NAME=Acme Corporation\nVITE_COMPANY_ADDRESS=123 Main St, Suite 100, San Francisco, CA 94105\n\n# ===== URLS =====\nVITE_QUICKBACK_APP_URL=https://app.acme.com\nVITE_TENANT_URL_PATTERN=/organizations/{slug}\nVITE_SUPPORT_URL=https://help.acme.com\nVITE_PRIVACY_URL=https://acme.com/privacy\nVITE_TERMS_URL=https://acme.com/terms\n\n# ===== EMAIL =====\nVITE_EMAIL_FROM=noreply@acme.com\nVITE_EMAIL_REPLY_TO=support@acme.com\nVITE_SUPPORT_EMAIL=support@acme.com\nVITE_EMAIL_REGION=us-east-1\n\n# ===== BRANDING =====\nVITE_THEME_COLOR=#3b82f6\n\n# ===== SEO =====\nVITE_SEO_KEYWORDS=saas,project management,team collaboration\n\n# ===== FEATURES =====\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Environment-Specific Configuration\n\n### Development\n\n```bash title=\".env.development\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\nVITE_QUICKBACK_APP_URL=http://localhost:3000\nDISABLE_EMAIL_STATUS_CHECK=true\n```\n\n### Staging\n\n```bash title=\".env.staging\"\nVITE_QUICKBACK_API_URL=https://api-staging.example.com\nVITE_ACCOUNT_APP_URL=https://account-staging.example.com\nVITE_QUICKBACK_APP_URL=https://app-staging.example.com\n```\n\n### Production\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\nDISABLE_EMAIL_STATUS_CHECK=false\n```\n\n## Cloudflare Pages Setup\n\nWhen deploying to Cloudflare Pages, set environment variables in the dashboard:\n\n1. Go to **Settings** → **Environment Variables**\n2. Add each `VITE_*` variable\n3. Separate values for **Production** and **Preview** branches\n\n## Wrangler Configuration\n\nFor `wrangler dev` and `wrangler deploy`, add variables to `wrangler.toml`:\n\n```toml title=\"wrangler.toml\"\n[env.production.vars]\nVITE_QUICKBACK_API_URL = \"https://api.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\nVITE_APP_NAME = \"My App\"\n# ... other variables\n```\n\nOr use `.dev.vars` for local development (git-ignored):\n\n```bash title=\".dev.vars\"\nVITE_QUICKBACK_API_URL=http://localhost:8787\nVITE_ACCOUNT_APP_URL=http://localhost:5173\n```\n\n## Runtime Configuration\n\nSome values can be overridden at runtime using the config API:\n\n```ts\n\nsetAppConfig({\n name: 'My Custom App',\n branding: {\n primaryColor: '#ff6600',\n logoUrl: '/custom-logo.png',\n },\n urls: {\n base: 'https://account.custom.com',\n app: 'https://app.custom.com',\n },\n});\n```\n\n## Validation\n\nThe Account UI validates configuration on startup:\n\n- **Missing VITE_QUICKBACK_API_URL**: Throws error\n- **Invalid URLs**: Logs warning\n- **Missing optional fields**: Uses defaults\n\nCheck the browser console for configuration warnings.\n\n## Next Steps\n\n- **[Feature Flags](/stack/account-ui/features)** - Detailed feature configuration\n- **[Customization](/stack/account-ui/customization)** - Customize labels and messages\n- **[Worker Setup](/stack/account-ui/worker)** - Deploy to Cloudflare"
|
|
335
255
|
},
|
|
336
|
-
"
|
|
337
|
-
"title": "
|
|
338
|
-
"content": "
|
|
256
|
+
"stack/account-ui/features/admin": {
|
|
257
|
+
"title": "Admin Panel",
|
|
258
|
+
"content": "The admin panel provides a user management dashboard for administrators. It's part of the Account UI SPA — when enabled, the `/admin` route is included in the build.\n\n## Enabling Admin\n\nSet `auth.admin` to `true` in your account config:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n auth: {\n admin: true,\n },\n},\n```\n\nThis does two things:\n1. Includes admin route files in the Account SPA build (compile-time gating)\n2. Ensures the Better Auth `admin` plugin is enabled on the backend\n\nWhen `auth.admin` is `false` (the default), admin routes are excluded from the SPA bundle entirely — they don't exist in production.\n\n## What It Can Do\n\n- **View all users** — Paginated list with search\n- **Create users** — Manually create accounts with email/password\n- **Ban/unban users** — Suspend or reactivate user accounts\n- **Reset passwords** — Generate password reset for any user\n- **View sessions** — See active sessions for any user\n\n## Access Control\n\nThe admin panel is restricted to users with `role: \"admin\"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.\n\nTo grant admin access to a user, use the Better Auth admin API:\n\n```bash\ncurl -X POST https://api.example.com/admin/v1/set-role \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"userId\": \"user_123\", \"role\": \"admin\" }'\n```\n\n## Custom Admin Domain\n\nGive the admin panel its own subdomain with `adminDomain`:\n\n```typescript title=\"quickback/quickback.config.ts\"\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n auth: { password: true, admin: true },\n},\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n],\n```\n\nThe admin domain serves the same Account SPA at root (`/`). The SPA's client-side router handles showing the admin page at `admin.example.com/admin`. Authentication cookies are shared across subdomains automatically via [cross-subdomain cookie configuration](/compiler/config/domains#cross-subdomain-authentication).\n\n## CMS Access Control\n\nWhen both CMS and Account UI are enabled, the admin panel's profile page shows a \"Go to CMS\" button. You can restrict this to admin users only:\n\n```typescript\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n```\n\nWith `access: \"admin\"`, non-admin users can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to admins. See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.\n\n## Related\n\n- [Configuration](/compiler/config) — `auth.admin` and `adminDomain` options\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Access Control](/compiler/definitions/access) — Role-based permissions in your API"
|
|
339
259
|
},
|
|
340
|
-
"
|
|
341
|
-
"title": "
|
|
342
|
-
"content": "
|
|
260
|
+
"stack/account-ui/features/api-keys": {
|
|
261
|
+
"title": "API Key Management",
|
|
262
|
+
"content": "Account UI provides an API key management interface for users to create, view, and revoke API keys.\n\n## Creating API Keys\n\nUsers can create API keys with:\n\n- Custom name/description\n- Optional expiration date\n- Scoped to the current organization\n\n## Managing Keys\n\n- View all active API keys\n- See last-used timestamp\n- Revoke individual keys\n\n## Related\n\n- [API Keys Auth](/stack/auth/api-keys) — Server-side API key authentication\n- [Environment Variables](/stack/account-ui/environment-variables)"
|
|
263
|
+
},
|
|
264
|
+
"stack/account-ui/features/avatars": {
|
|
265
|
+
"title": "Avatars",
|
|
266
|
+
"content": "When file uploads are enabled, Account UI provides avatar upload functionality.\n\n## Enabling\n\nIn `quickback.config.ts`:\n\n```ts\naccount: {\n fileUploads: true,\n // ...\n}\n```\n\nThe compiler emits `VITE_ENABLE_FILE_UPLOADS=true` into the Account SPA's\nbuild env. For standalone Account UI deployments (built outside the\ncompiler), set `VITE_ENABLE_FILE_UPLOADS=true` in `.env` directly.\n\n## Upload Flow\n\n1. User clicks their profile picture\n2. Image picker opens (supports JPG, PNG, WebP)\n3. Image is cropped to square\n4. Uploaded to R2/S3 storage\n5. Profile updated with new avatar URL\n\n## Requirements\n\n- `account.fileUploads: true` (or `VITE_ENABLE_FILE_UPLOADS=true` for standalone)\n- R2 bucket or S3-compatible storage configured\n- Upload endpoints available in your API\n\n## Related\n\n- [R2 Storage](/stack/storage/r2) — File storage setup\n- [Environment Variables](/stack/account-ui/environment-variables)"
|
|
267
|
+
},
|
|
268
|
+
"stack/account-ui/features/cli-authorize": {
|
|
269
|
+
"title": "CLI Authorization",
|
|
270
|
+
"content": "Account UI includes a device authorization page that allows users to approve CLI login requests.\n\n## How It Works\n\n1. User runs `quickback login` in the CLI\n2. CLI displays a URL and user code\n3. User opens the URL in their browser\n4. Account UI shows the authorization page with the device code\n5. User confirms the code matches and approves\n6. CLI receives the authentication token\n\n## Configuration\n\nThe CLI authorization page is always available when the Account UI is deployed. No additional configuration is needed.\n\n## Related\n\n- [Device Auth](/stack/auth/device-auth) — Server-side device auth flow\n- [CLI Reference](/compiler/cloud-compiler/cli) — CLI commands"
|
|
271
|
+
},
|
|
272
|
+
"stack/account-ui/features": {
|
|
273
|
+
"title": "Feature Flags",
|
|
274
|
+
"content": "# Feature Flags\n\nControl which features are available in your Account UI deployment using feature flags. All features are configured via environment variables.\n\n## Authentication Features\n\n### User Signup\n\n```bash\nENABLE_SIGNUP=true # default: true\n```\n\nControls whether new users can register. Wired to the `ENABLE_SIGNUP` env var.\n\n**When enabled:**\n- Shows \"Sign Up\" link on login page\n- `/signup` route is accessible\n- New users can create accounts\n\n**When disabled:**\n- Signup route returns 404\n- Only existing users can log in\n- Useful for invite-only applications\n\n### Email Verification\n\n```bash\nENABLE_EMAIL_VERIFICATION=true # default: true\n```\n\nControls the email verification flow. Wired to the frontend via the `ENABLE_EMAIL_VERIFICATION` env var.\n\n**When enabled:**\n- Users must verify email before full access\n- Verification email sent on signup\n- \"Resend verification email\" option available\n- Unverified users see verification prompt\n\n**When disabled:**\n- Email addresses are trusted without verification\n- Users have immediate access after signup\n\n### Email Deliverability Check\n\n```bash\nDISABLE_EMAIL_STATUS_CHECK=false # default: false\n```\n\n**When `false` (checking enabled):**\n- System validates email addresses are deliverable\n- Rejects disposable/temporary email providers\n- Prevents typos in domain names\n\n**When `true` (checking disabled):**\n- Accepts all email formats\n- Useful for development/testing\n- Allows `@test.com`, `@localhost`, etc.\n\n### Passkey Login\n\n```bash\nENABLE_PASSKEY=true # default: true\n```\n\nControls passkey LOGIN only (not signup). When enabled, users can authenticate using passkeys.\n\n**When enabled:**\n- Users can register passkeys (fingerprint, Face ID, hardware keys)\n- Passwordless login option\n- \"Manage Passkeys\" page available\n\n**When disabled:**\n- No passkey registration\n- No passkey login option\n\n**Requirements:**\n- HTTPS (passkeys require secure context)\n- Modern browser with WebAuthn support\n\n### Email OTP\n\n```bash\nENABLE_EMAIL_OTP=true # default: true\n```\n\n**When enabled:**\n- Users can receive one-time passwords via email\n- Alternative to password login\n- `/email-otp` route available\n\n**When disabled:**\n- No email OTP option\n- Password or passkey required\n\n### Password Authentication\n\n```bash\nENABLE_PASSWORD=false # default: false\n```\n\n**When enabled:**\n- Email + password fields on login page\n- Password field on signup page\n- Traditional username/password authentication\n\n**When disabled:**\n- No password fields shown\n- Users authenticate via email OTP or passkey\n\n## Account Management Features\n\n### File Uploads\n\n```bash\nVITE_ENABLE_FILE_UPLOADS=false # default: false\n```\n\n**When enabled:**\n- Avatar/profile picture upload\n- Image cropping and editing\n- File upload to R2/S3\n\n**When disabled:**\n- No file upload functionality\n- Users can only use default avatars\n\n**Requirements:**\n- R2 bucket or S3 configured\n- Upload endpoints in your API\n\n## Organization Features\n\n### Organizations (Multi-Tenancy)\n\n```bash\nENABLE_ORGANIZATIONS=true # default: true\n```\n\n**When enabled:**\n- Users can create organizations\n- Organization management pages\n- Member invitations and roles\n- `/organizations/*` routes\n\n**When disabled:**\n- Single-user mode only\n- No organization features\n- Simpler user experience\n\n**Includes:**\n- Organization creation and deletion\n- Member management (owner, admin, member roles)\n- Invitation system\n- Organization settings\n\n## Admin Features\n\n### Admin Panel\n\n```bash\nENABLE_ADMIN=true # default: true\n```\n\n**When enabled:**\n- `/admin` route accessible to admin users\n- User management dashboard\n- Subscription management\n- Admin-only features:\n - Create users manually\n - Ban/unban users\n - Reset user passwords\n - View all sessions\n - Manage subscriptions\n\n**When disabled:**\n- No admin panel\n- Admin must use database directly\n\n**Requirements:**\n- User must have admin role in database\n\n## Feature Combinations\n\n### Minimal Configuration (Password-Only)\n\n```bash\nENABLE_PASSKEY=false\nENABLE_EMAIL_OTP=false\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=false\nENABLE_ADMIN=false\n```\n\nSimple email/password authentication for single-tenant apps.\n\n### Maximum Security\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=false\nENABLE_EMAIL_VERIFICATION=true\n```\n\nAll authentication methods with email verification and deliverability checks.\n\n### Multi-Tenant SaaS\n\n```bash\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nFull-featured SaaS with organizations, teams, and admin panel.\n\n### Invite-Only Platform\n\n```bash\nENABLE_SIGNUP=false\nENABLE_PASSKEY=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\n```\n\nNo public signup - users must be created by admin or invited to organizations.\n\n## Feature Detection\n\nCheck if a feature is enabled in your code:\n\n```ts\n\nif (isFeatureEnabled('organizations')) {\n // Show organizations menu\n}\n\nif (isFeatureEnabled('passkey')) {\n // Offer passkey setup\n}\n```\n\n## Dynamic Feature Configuration\n\nOverride features at runtime:\n\n```ts\n\nsetAppConfig({\n features: {\n organizations: false, // Disable organizations\n passkey: true, // Enable passkey\n },\n});\n```\n\n## Testing Features\n\nFor local development, create `.env.local`:\n\n```bash title=\".env.local\"\n# Test with all features enabled\nENABLE_SIGNUP=true\nENABLE_EMAIL_VERIFICATION=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\nENABLE_PASSWORD=true\nENABLE_ORGANIZATIONS=true\nENABLE_ADMIN=true\nVITE_ENABLE_FILE_UPLOADS=true\nDISABLE_EMAIL_STATUS_CHECK=true # Allow test emails\n```\n\n## Next Steps\n\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Complete variable reference\n- **[Customization](/stack/account-ui/customization)** - Customize UI text and labels\n- **[Worker Setup](/stack/account-ui/worker)** - Deploy your configuration"
|
|
275
|
+
},
|
|
276
|
+
"stack/account-ui/features/organizations": {
|
|
277
|
+
"title": "Organizations",
|
|
278
|
+
"content": "Account UI provides a complete organization management interface when `ENABLE_ORGANIZATIONS=true`.\n\n## Organization CRUD\n\n- Create new organizations\n- Update organization name and settings\n- Delete organizations (owner only)\n\n## Member Management\n\n- Invite members by email\n- Assign roles: **owner**, **admin**, **member**\n- Remove members\n- Transfer ownership\n\n## Invitations\n\n- Pending invitation list\n- Resend invitations\n- Cancel invitations\n\n> **Note:** These three roles (`owner`, `admin`, `member`) are Better Auth's built-in organization roles and map directly to Account UI's role picker. Use the same roles in your Quickback [Access](/compiler/definitions/access) rules — with [`auth.roleHierarchy`](/compiler/definitions/access#role-hierarchy) configured, you can write `roles: [\"member+\"]` to mean \"member and above.\"\n\n## Related\n\n- [Environment Variables](/stack/account-ui/environment-variables)\n- [Account UI Overview](/stack/account-ui)"
|
|
279
|
+
},
|
|
280
|
+
"stack/account-ui/features/passkeys": {
|
|
281
|
+
"title": "Passkeys",
|
|
282
|
+
"content": "When `ENABLE_PASSKEY=true`, Account UI provides passkey registration and management.\n\n## Passkey Registration\n\n- Setup wizard guides users through passkey creation\n- Supports fingerprint, Face ID, and hardware security keys\n- Multiple passkeys can be registered per account\n\n## Passkey Login\n\n- \"Sign in with passkey\" button on login page\n- Browser's native WebAuthn dialog\n- No password required\n\n## Managing Passkeys\n\n- View registered passkeys\n- Remove individual passkeys\n- Register additional passkeys\n\n## Requirements\n\n- HTTPS (WebAuthn requires secure context)\n- Modern browser with WebAuthn support\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/stack/account-ui/environment-variables)"
|
|
283
|
+
},
|
|
284
|
+
"stack/account-ui/features/passwordless": {
|
|
285
|
+
"title": "Passwordless Authentication",
|
|
286
|
+
"content": "Account UI supports passwordless authentication via email OTP and magic links.\n\n## Email OTP\n\nWhen `ENABLE_EMAIL_OTP=true`:\n\n- Users enter their email address\n- A one-time password is sent via email\n- User enters the OTP code to authenticate\n\n## Magic Links\n\nWhen `ENABLE_MAGIC_LINK=true`:\n\n- Users enter their email address\n- A login link is sent via email\n- Clicking the link authenticates the user\n\n## Combo Auth\n\nWhen both are enabled, Account UI uses the `@quickback-dev/better-auth-combo-auth` plugin to combine them into a single flow — the email contains both a clickable link and a code.\n\n## Related\n\n- [Auth Plugins](/stack/auth/plugins) — Plugin configuration\n- [Environment Variables](/stack/account-ui/environment-variables)"
|
|
287
|
+
},
|
|
288
|
+
"stack/account-ui/features/sessions": {
|
|
289
|
+
"title": "Session Management",
|
|
290
|
+
"content": "Account UI includes a session management page where users can view and revoke their active sessions.\n\n## Active Sessions\n\nUsers can see all devices where they're currently logged in, including:\n\n- Device type and browser\n- IP address and approximate location\n- Last active timestamp\n\n## Revoking Sessions\n\nUsers can revoke any session except their current one. This immediately invalidates the session token.\n\n## Related\n\n- [Environment Variables](/stack/account-ui/environment-variables)\n- [Account UI Overview](/stack/account-ui)"
|
|
291
|
+
},
|
|
292
|
+
"stack/account-ui/hooks": {
|
|
293
|
+
"title": "Auth Hooks",
|
|
294
|
+
"content": "# Auth Hooks\n\nQuickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.\n\nThe classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `400 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.\n\n## Folder layout\n\n```\nquickback/\n hooks/\n after-user-create.ts\n before-user-create.ts\n after-session-create.ts\n```\n\nEach file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.\n\n## Recognized events\n\n| Filename | Better Auth path | Entity | Return |\n|--------------------------------|-----------------------------------|----------|---------------------------------|\n| `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \\| { data?: Partial<User> }` |\n| `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |\n| `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |\n\nFilenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).\n\n## ctx shape\n\nEvery hook receives `(entity, ctx)`:\n\n```ts\ntype HookCtx = {\n /** Drizzle client bound to the auth DB binding (split-DB aware). */\n authDb: DrizzleClient;\n /**\n * Auth schema namespace — destructure to access the BA-managed tables\n * (`user`, `session`, `organization`, `member`, …) without writing an\n * import path. The hook source lives in `quickback/hooks/` pre-compile\n * and `src/lib/auth-hooks/` post-stage; relying on `authSchema`\n * removes the dual-path import problem.\n */\n authSchema: typeof import('../../auth/schema');\n /** Cloudflare bindings (Cloudflare runtime) or process.env (Bun/Node). */\n env: Bindings;\n /** Better Auth's own context object — request, hook metadata, etc. */\n baContext: any;\n};\n```\n\n`authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.\n\n## Writing hooks: use built-ins where possible\n\nHook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a \"module not found\" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.\n\nStick to runtime built-ins for ID generation, hashing, and similar primitives:\n\n| Need | Built-in |\n|--------------------|---------------------------------------------------------|\n| Random ID | `crypto.randomUUID()` |\n| SHA-256 / digest | `crypto.subtle.digest(...)` (Workers / Node 19+) |\n| Random bytes | `crypto.getRandomValues(new Uint8Array(n))` |\n| Time | `Date.now()`, `new Date().toISOString()` |\n\n`drizzle-orm` is already available in the schema-gen sandbox (the auth schema imports from it), so `eq`, `and`, `inArray`, etc. are safe to import.\n\n## Throw semantics\n\nWhat happens when a hook throws is the #1 thing that bites people:\n\n| Hook | Throw effect |\n|-----------------------|------------------------------------------------------------------------------|\n| `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |\n| `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |\n| `after-session-create`| Same as above — the session row exists; partial writes leak. |\n\nFor `after-*` hooks, design for **idempotency**: use the entity's `id` as a stable seed for any derived rows so re-running the hook (manually or via a background reconciler) is safe. Don't generate fresh `cuid()`s for derived rows you'd want to recover.\n\n## Examples\n\n### Auto-provision a personal workspace on signup\n\nThe QB-9 case. Without this, `organizations: true` projects break immediately for new users.\n\n```ts title=\"quickback/hooks/after-user-create.ts\"\n\nexport default async (user, { authDb, authSchema }) => {\n const { organization, member } = authSchema;\n\n // Idempotency: derive a stable org id from the user id so re-running this\n // hook (after a partial failure) doesn't create a second workspace.\n const orgId = `org_${user.id}`;\n const slug = `${(user.name ?? 'workspace').toLowerCase().replace(/\\s+/g, '-')}-${user.id.slice(0, 6)}`;\n\n // Skip if the workspace already exists (idempotent).\n const existing = await authDb\n .select({ id: organization.id })\n .from(organization)\n .where(eq(organization.id, orgId));\n if (existing.length > 0) return;\n\n await authDb.insert(organization).values({\n id: orgId,\n name: `${user.name ?? 'Personal'} Workspace`,\n slug,\n createdAt: new Date(),\n });\n\n await authDb.insert(member).values({\n id: crypto.randomUUID(),\n userId: user.id,\n organizationId: orgId,\n role: 'owner',\n createdAt: new Date(),\n });\n};\n```\n\n### Set the active organization on next session\n\nSetting `activeOrganizationId` from a hook means writing to `session.active_organization_id` via Drizzle directly — calling Better Auth's `setActiveOrganization` API server-side is awkward (see the CSRF caveat). The reliable pattern:\n\n```ts title=\"quickback/hooks/after-session-create.ts\"\n\nexport default async (newSession, { authDb, authSchema }) => {\n const { session, member } = authSchema;\n\n // Pick the user's first membership as their active org. Projects that\n // want a sticky last-active-org should track that separately.\n const memberships = await authDb\n .select({ organizationId: member.organizationId })\n .from(member)\n .where(eq(member.userId, newSession.userId))\n .limit(1);\n\n if (memberships.length === 0) return;\n\n await authDb\n .update(session)\n .set({ activeOrganizationId: memberships[0].organizationId })\n .where(eq(session.id, newSession.id));\n};\n```\n\n### Normalize and gate signup\n\n`before-*` hooks can return `{ data: Partial<User> }` to mutate the row before insert. Throw to abort.\n\n```ts title=\"quickback/hooks/before-user-create.ts\"\nexport default async (user: { email: string; name?: string }) => {\n // Block disposable inboxes.\n if (/@(?:mailinator|10minutemail)\\.com$/i.test(user.email)) {\n throw new Error('Disposable email addresses are not allowed.');\n }\n // Trim whitespace from display name.\n return { data: { name: user.name?.trim() } };\n};\n```\n\nThe compiler-generated wrapper merges your `data` onto the original entity, so you only return the fields you actually want to change.\n\n## CSRF caveat — server-side org create\n\n`POST /auth/v1/organization/create` (and Better Auth's `auth.api.createOrganization(...)` server helper) require an `Origin` header. A hook running inside `databaseHooks.user.create.after` is server-side — there is no incoming request, so no `Origin`. Calling those APIs from a hook may also validate `Origin` internally and reject.\n\n**The only safe path is direct Drizzle writes via `authDb`.** Treat the org/member tables as your source of truth and let the SPA call the BA API for user-initiated org creation.\n\n## Generated output\n\nCompile picks up `quickback/hooks/*.ts` and produces:\n\n```\nsrc/lib/auth.ts # imports the hook + adds a databaseHooks block\nsrc/lib/auth-hooks/<file> # your hook source, copied verbatim\n```\n\nInside the generated `auth.ts`:\n\n```ts\n\n// ...inside createAuth(env)...\nreturn betterAuth({\n // ...\n database: drizzleAdapter(db, { /* ... */ }),\n databaseHooks: {\n user: {\n create: {\n after: async (entity, _baCtx) => {\n const _qbCtx = { authDb: db, authSchema: schema, env, baContext: _baCtx };\n await __qbHook_afterUserCreate(entity, _qbCtx);\n },\n },\n },\n },\n});\n```\n\nNo hooks → no `databaseHooks` block emitted. The whole feature is opt-in by file presence.\n\n## See also\n\n- [With Quickback Compiler](/stack/account-ui/with-quickback) — how `account.auth.organizations` flows through the build\n- [Configuration → account block](/compiler/config) — `account.appUrl` and other account-level options\n- [Better Auth: Database Hooks](https://www.better-auth.com/docs/concepts/database#database-hooks)"
|
|
295
|
+
},
|
|
296
|
+
"stack/account-ui": {
|
|
297
|
+
"title": "Account UI",
|
|
298
|
+
"content": "# Quickback Account UI\n\nA complete authentication and account management frontend. It handles login, signup, password reset, profile management, device sessions, passkeys, organizations, and admin — so you don't have to build any of it.\n\n## What's Included\n\nAccount UI is a single React SPA that contains three distinct sections:\n\n### Account (every user)\n\nLogin, signup, profile editing, password management, device sessions, email changes, and account deletion. This is what every user interacts with.\n\nServed on its own domain (e.g., `auth.example.com`) or at `/account/` when embedded alongside the CMS.\n\n### Organization Management (multi-tenant)\n\nDashboard with org switching, org creation, member invitations, role management, and org settings. Only available when `auth.organizations` is enabled.\n\n### Admin Panel (admin users only)\n\nUser management dashboard — view all users, search, create accounts, ban/unban, reset passwords, and manage sessions. Only accessible to users with the `admin` role. Can be served on its own domain (e.g., `admin.example.com`) via the `adminDomain` config.\n\n## Quick Start (Compiler-Embedded)\n\nThe recommended approach: add `account` to your `quickback.config.ts` and compile. The compiler builds the SPA from source with your project-specific settings baked in.\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\" },\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\nThat's it. The compiler:\n1. Reads your auth feature flags and branding from the config\n2. Generates a `.env` file with the correct `VITE_*` variables\n3. Builds the SPA from source with Vite (inside Docker)\n4. Excludes routes for disabled features (compile-time tree shaking)\n5. Outputs the built assets alongside your API code\n\nNo manual `.env` configuration needed. No separate deployment.\n\nSee [Configuration](/compiler/config) for all `account` options and [Multi-Domain Architecture](/compiler/config/domains) for custom domain setup.\n\n### Skip SPA Rebuild\n\nAfter the first compile, skip rebuilding the Account SPA on subsequent compiles:\n\n```typescript\naccount: { build: false, /* ...other options */ }\n```\n\nUseful when iterating on API features — saves significant compile time. Set back to `true` (or omit) when you need to update the Account UI.\n\n### Custom Output Directory\n\n```typescript\naccount: { outputDir: \"my-custom-path/account\" }\n```\n\nChanges where compiled Account assets are placed, instead of the default `src/apps/account/`.\n\n## Compile-Time Feature Gating\n\nAuth feature flags control which pages are included in the bundle:\n\n| Flag | Pages Included |\n|------|---------------|\n| `auth.password` | Password login, inline password change on profile |\n| `auth.emailOTP` | Email OTP login flow, email-based password reset |\n| `auth.passkey` | Passkey setup and management |\n| `auth.organizations` | Dashboard, org creation, member management, invitations |\n| `auth.admin` | Admin panel (user management) |\n\nWhen a flag is `false`, the corresponding route files are **removed before the Vite build** — they never appear in the JavaScript bundle. This keeps production bundles minimal.\n\n## Standalone Usage\n\nAccount UI also works outside of Quickback:\n\n### Template (own the source)\n\nClone the repo and customize directly:\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\nConfigure via `.env` files and deploy as a standalone Cloudflare Worker. See [Standalone Usage](/stack/account-ui/standalone) for Better Auth backends or [With Quickback](/stack/account-ui/with-quickback) for Quickback-compiled backends.\n\n### Library (npm package)\n\nInstall as a dependency:\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n```tsx\n\nsetAppConfig({\n authRoute: 'quickback',\n name: 'My App',\n});\n```\n\nSee [Library Usage](/stack/account-ui/library-usage) for details.\n\n## Features\n\n- **Authentication** — Email/password, passkeys (WebAuthn), email OTP, magic links, email verification, password reset\n- **Account Management** — Profile editing, avatar upload, password changes, device/session management, account deletion\n- **Organizations** — Multi-tenant org management with owner/admin/member roles, invitations, and org settings\n- **Admin Panel** — User management dashboard with search, create, ban/unban, password reset, and session viewing\n- **API Keys** — Generate and manage API keys for programmatic access\n- **CLI Authorization** — Device authorization flow for `quickback login`\n\n## Next Steps\n\n- **[With Quickback](/stack/account-ui/with-quickback)** — Compiler-embedded and standalone setup\n- **[Standalone Usage](/stack/account-ui/standalone)** — Use with any Better Auth backend\n- **[Library Usage](/stack/account-ui/library-usage)** — Import as an npm package\n- **[Feature Flags](/stack/account-ui/features)** — Enable and disable features\n- **[Environment Variables](/stack/account-ui/environment-variables)** — Configuration reference\n- **[Customization](/stack/account-ui/customization)** — Branding, labels, and theming\n- **[Multi-Domain Architecture](/compiler/config/domains)** — Custom domains and hostname routing"
|
|
299
|
+
},
|
|
300
|
+
"stack/account-ui/library-usage": {
|
|
301
|
+
"title": "Library Usage",
|
|
302
|
+
"content": "# Library Usage\n\nInstead of cloning the template, you can install Account UI as an npm package. This gives you automatic updates via `npm update` while configuring the UI through `setAppConfig()`.\n\n## Installation\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n### Peer Dependencies\n\nAccount UI expects these packages in your app:\n\n```bash\nnpm install react react-dom react-router-dom @tanstack/react-query\n```\n\n## Basic Setup\n\n### 1. Import and Configure\n\n```tsx title=\"src/main.tsx\"\n\nsetAppConfig({\n authRoute: 'quickback', // or 'better-auth' for standalone Better Auth\n name: 'My App',\n companyName: 'My Company Inc.',\n tagline: 'Build faster, ship sooner',\n description: 'My app description',\n});\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n);\n```\n\n### 2. Set API URLs\n\nThe library reads API URLs from `globalThis` variables. Set these before importing the library:\n\n```tsx title=\"src/main.tsx\"\n// Single catch-all: API + Account + CMS URLs are all derived from this origin.\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com';\n(globalThis as any).__QUICKBACK_APP_URL__ = 'https://app.example.com';\n\n// Then import dynamically to ensure globals are set first\nconst { AuthApp, setAppConfig } = await import('quickback-better-auth-account-ui');\nawait import('quickback-better-auth-account-ui/styles.css');\n```\n\nIf your API lives on a different subdomain, set `__QUICKBACK_API_URL__` explicitly instead (or alongside) — it takes precedence over the catch-all:\n\n```tsx\n(globalThis as any).__QUICKBACK_URL__ = 'https://secure.example.com'; // catch-all\n(globalThis as any).__QUICKBACK_API_URL__ = 'https://api.example.com'; // explicit override\n```\n\nOr with Vite environment variables:\n\n```tsx title=\"src/main.tsx\"\n(globalThis as any).__QUICKBACK_URL__ = import.meta.env.VITE_QUICKBACK_URL;\n(globalThis as any).__QUICKBACK_API_URL__ = import.meta.env.VITE_QUICKBACK_API_URL;\n(globalThis as any).__QUICKBACK_APP_URL__ = import.meta.env.VITE_QUICKBACK_APP_URL;\n\nPromise.all([\n import('quickback-better-auth-account-ui'),\n import('quickback-better-auth-account-ui/styles.css'),\n]).then(([{ AuthApp, setAppConfig }]) => {\n setAppConfig({\n authRoute: 'quickback',\n name: import.meta.env.VITE_APP_NAME || 'My App',\n companyName: import.meta.env.VITE_COMPANY_NAME || 'My Company',\n tagline: import.meta.env.VITE_APP_TAGLINE || 'Welcome',\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n \n </React.StrictMode>\n );\n});\n```\n\n## Cloudflare Worker\n\nThe library exports a Cloudflare Worker entry point for SPA routing and static asset serving:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nOr extend it with custom logic:\n\n```ts title=\"src/worker.ts\"\n\nexport default createAuthWorker();\n```\n\n## Configuration via `setAppConfig()`\n\nIn library mode, all configuration happens through `setAppConfig()` instead of environment variables.\n\n### Auth Route Mode\n\n```ts\nsetAppConfig({\n authRoute: 'quickback', // Quickback API: /auth/v1, /api/v1, /storage/v1\n // or\n authRoute: 'better-auth', // Better Auth default: /api/auth\n});\n```\n\n### Branding\n\n```ts\nsetAppConfig({\n name: 'Acme SaaS',\n companyName: 'Acme Corporation',\n tagline: 'Build faster, ship sooner',\n description: 'The complete platform for modern web applications',\n branding: {\n primaryColor: '#3b82f6',\n logoUrl: '/logo.png',\n faviconUrl: '/favicon.ico',\n },\n});\n```\n\n### Labels and Messages\n\n```ts\nsetAppConfig({\n labels: {\n organizations: 'Workspaces',\n terms: 'Terms and Conditions',\n privacy: 'Privacy Notice',\n },\n messages: {\n noOrganizations: \"You haven't joined any workspaces yet.\",\n createOrganization: 'Create Workspace',\n },\n});\n```\n\n### Routes\n\n```ts\nsetAppConfig({\n routes: {\n public: {\n login: '/sign-in',\n signup: '/sign-up',\n },\n organizations: {\n list: '/workspaces',\n create: '/workspaces/new',\n },\n },\n});\n```\n\n### Password and Session\n\n```ts\nsetAppConfig({\n auth: {\n passwordRequirements: {\n minLength: 12,\n requireSymbols: true,\n },\n sessionDuration: 7 * 24 * 60 * 60, // 7 days\n },\n});\n```\n\nSee [Customization](/stack/account-ui/customization) for the full reference of all configurable options.\n\n## Exports\n\nThe library provides the following exports:\n\n### Main Entry (`quickback-better-auth-account-ui`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `AuthApp` | Component | The main React application component |\n| `authClient` | Object | Pre-configured Better Auth client |\n| `appConfig` | Object | Current app configuration |\n| `setAppConfig` | Function | Set app configuration overrides |\n| `createAppConfig` | Function | Create a new config object |\n| `getApiBase` | Function | Get the current API base URL |\n| `setApiBase` | Function | Override the API base URL |\n| `getAuthApiUrl` | Function | Get the auth API URL |\n| `getDataApiUrl` | Function | Get the data API URL |\n| `getStorageApiUrl` | Function | Get the storage API URL |\n\n### Styles (`quickback-better-auth-account-ui/styles.css`)\n\nThe compiled CSS for the Account UI. Must be imported for the UI to render correctly.\n\n### Worker (`quickback-better-auth-account-ui/worker`)\n\n| Export | Type | Description |\n|--------|------|-------------|\n| `default` | Worker | Cloudflare Worker with SPA routing |\n| `createAuthWorker` | Function | Factory for creating a worker instance |\n\n## Custom Styles\n\nOverride styles by importing your CSS after the library styles:\n\n```ts\n\n```\n\n```css title=\"my-overrides.css\"\n:root {\n --primary: 59 130 246;\n --primary-foreground: 255 255 255;\n}\n```\n\n## Updating\n\nUpdate to the latest version:\n\n```bash\nnpm update quickback-better-auth-account-ui\n```\n\nThe library follows semantic versioning. Check the [changelog](https://github.com/Kardoe-com/quickback-better-auth-account-ui/releases) for breaking changes.\n\n## Next Steps\n\n- **[Customization](/stack/account-ui/customization)** — Full configuration reference\n- **[Feature Flags](/stack/account-ui/features)** — Enable and disable features\n- **[Worker Setup](/stack/account-ui/worker)** — Deploy to Cloudflare Workers\n- **[With Quickback](/stack/account-ui/with-quickback)** — Quickback-specific configuration"
|
|
303
|
+
},
|
|
304
|
+
"stack/account-ui/standalone": {
|
|
305
|
+
"title": "Standalone Usage",
|
|
306
|
+
"content": "Account UI can be used with **any Better Auth-powered backend**, not just Quickback-compiled projects. This makes it a drop-in authentication frontend for any app using Better Auth.\n\n## Requirements\n\n- A backend running [Better Auth](https://better-auth.com) with API endpoints\n- Node.js 18+ and npm/pnpm/bun\n- A Cloudflare account (for deployment)\n\n## Setup\n\n### 1. Clone or Install the Account UI\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### 2. Configure the Auth Route Mode\n\nThe key difference from Quickback mode is the `VITE_AUTH_ROUTE` variable. Set it to `better-auth` to use Better Auth's default API paths:\n\n```bash title=\".env\"\n# Auth route mode — use 'better-auth' for standalone\nVITE_AUTH_ROUTE=better-auth\n\n# Your Better Auth backend URL (single catch-all — see below)\nVITE_QUICKBACK_URL=https://secure.example.com\n\n# Where this Account UI is hosted\nVITE_ACCOUNT_APP_URL=https://account.example.com\n```\n\n`VITE_QUICKBACK_URL` is the recommended one-variable setup. If your API lives on a separate subdomain, set `VITE_QUICKBACK_API_URL` explicitly — it takes precedence.\n\nThis configures the auth client to use `/api/auth` as the base path (Better Auth's default), instead of Quickback's `/auth/v1`.\n\n### 3. Configure Your App\n\n```bash title=\".env\"\n# App identity\nVITE_APP_NAME=My App\nVITE_APP_TAGLINE=Welcome to My App\n\n# Redirect after login\nVITE_QUICKBACK_APP_URL=https://app.example.com\n\n# Feature flags\nENABLE_SIGNUP=true\nENABLE_ORGANIZATIONS=true\nENABLE_PASSKEY=true\nENABLE_EMAIL_OTP=true\n```\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the complete reference.\n\n### 4. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Auth Route Modes\n\nAccount UI supports three routing modes, controlled by `VITE_AUTH_ROUTE`:\n\n| Mode | Value | Auth Path | Data Path | Storage Path |\n|------|-------|-----------|-----------|--------------|\n| Better Auth | `better-auth` | `/api/auth` | — | — |\n| Quickback | `quickback` | `/auth/v1` | `/api/v1` | `/storage/v1` |\n| Custom | `custom` | Custom | Custom | Custom |\n\n### Better Auth Mode (Default)\n\nRoutes all auth requests to `/api/auth/*` — the standard Better Auth convention:\n\n```bash\nVITE_AUTH_ROUTE=better-auth\n```\n\n### Custom Mode\n\nFor non-standard setups, use custom mode with explicit paths:\n\n```bash\nVITE_AUTH_ROUTE=custom\nVITE_AUTH_BASE_PATH=/my-auth\nVITE_DATA_BASE_PATH=/my-api\nVITE_STORAGE_BASE_PATH=/my-storage\n```\n\n## Backend Requirements\n\nYour Better Auth backend must have the following plugins enabled for full Account UI functionality:\n\n| Feature | Required Plugin | Required For |\n|---------|----------------|--------------|\n| Organizations | `organization` | Multi-tenant org management |\n| Admin panel | `admin` | User management dashboard |\n| API keys | `apiKey` | API key generation UI |\n| Passkeys | `@better-auth/passkey` | WebAuthn authentication |\n| Email OTP | `emailOTP` | One-time password login |\n| CLI login | `deviceAuthorization` | `quickback login` flow |\n\nOnly enable the features that match your backend's plugin configuration. Disable features for plugins you haven't installed:\n\n```bash\n# If your backend doesn't have the organization plugin:\nENABLE_ORGANIZATIONS=false\n\n# If you haven't set up passkeys:\nENABLE_PASSKEYS=false\n```\n\n## CORS Configuration\n\nYour Better Auth backend must allow requests from the Account UI's domain. Configure CORS to include:\n\n```typescript\n// In your Better Auth config\ntrustedOrigins: [\n \"https://account.example.com\", // Account UI domain\n],\n```\n\n## Differences from Quickback Mode\n\n| Aspect | Standalone | With Quickback |\n|--------|-----------|----------------|\n| Auth routes | `/api/auth/*` | `/auth/v1/*` |\n| Data API | Not used | `/api/v1/*` |\n| Storage API | Not used | `/storage/v1/*` |\n| File uploads | Manual setup | Auto-configured |\n| Backend | Any Better Auth app | Quickback-compiled |\n\n## Next Steps\n\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete configuration reference\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming\n- [Worker Setup](/stack/account-ui/worker) — Cloudflare Workers deployment\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features"
|
|
343
307
|
},
|
|
344
|
-
"
|
|
345
|
-
"title": "
|
|
346
|
-
"content": "
|
|
308
|
+
"stack/account-ui/with-quickback": {
|
|
309
|
+
"title": "With Quickback",
|
|
310
|
+
"content": "When using Account UI with a Quickback-compiled backend, the recommended approach is to let the compiler build and embed the SPA directly into your Worker.\n\n## Compiler-Embedded (Recommended)\n\nAdd `account` to your `quickback.config.ts`:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default {\n name: \"my-app\",\n template: \"hono\",\n account: {\n domain: \"auth.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n passkey: true,\n organizations: true,\n admin: true,\n },\n },\n // ...providers\n};\n```\n\nThen compile and deploy:\n\n```bash\nquickback compile\nnpx wrangler deploy\n```\n\n### What Happens During Compilation\n\n1. The compiler reads your `account` config and generates a `.env` file with the correct Vite environment variables (`VITE_QUICKBACK_URL`, `VITE_QUICKBACK_API_URL`, `VITE_ENABLE_PASSWORD`, branding, etc.)\n2. The Account SPA source is copied to a temp directory, with disabled feature routes excluded\n3. Pre-installed dependencies are symlinked (no `npm install` during build)\n4. Vite builds the SPA with your settings baked in\n5. Built assets (content-hashed filenames) are placed in the output directory\n\nWhen CMS is also enabled, Account assets go to `src/apps/account/` and are served at `/account/`. When Account is the only SPA, assets go to `src/apps/` and are served at root.\n\n### Custom Domains\n\nWith a custom domain, the Account SPA is served at root (`/`) on that domain:\n\n```typescript\naccount: { domain: \"auth.example.com\" }\n```\n\nAdd an admin domain to serve the admin panel on its own subdomain:\n\n```typescript\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n}\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname routing and cross-subdomain cookies.\n\n### Auth Feature Flags\n\nFeature flags control which pages are included in the build:\n\n```typescript\nauth: {\n password: true, // Email/password login + inline password change\n emailOTP: false, // Email OTP login flow\n passkey: true, // WebAuthn passkey setup + management\n organizations: true, // Dashboard, org management, invitations\n admin: true, // Admin panel (user management)\n}\n```\n\nDisabled features are excluded at compile time — their route files are removed before the Vite build. See [Configuration](/compiler/config) for all options.\n\n## Manual Deployment\n\nIf you need Account UI as a separate Worker (not embedded in the API Worker), you can deploy it standalone.\n\n### 1. Clone the Template\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### 2. Configure for Quickback\n\nSet the auth route mode to `quickback` to match Quickback's API paths:\n\n```bash title=\".env\"\nVITE_AUTH_ROUTE=quickback\n# One variable points at the Quickback origin — API, Account, and CMS are all derived from it.\nVITE_QUICKBACK_URL=https://secure.example.com\nVITE_ACCOUNT_APP_URL=https://account.example.com\nVITE_QUICKBACK_APP_URL=https://app.example.com\n```\n\nIn Quickback mode, Account UI routes requests to three API paths:\n\n| Path | Purpose | Examples |\n|------|---------|---------|\n| `/auth/v1/*` | Authentication | Login, signup, sessions, passkeys |\n| `/api/v1/*` | Data API | Organizations, API keys |\n| `/storage/v1/*` | File storage | Avatar uploads, file management |\n\n### 3. Configure Features\n\nMatch your `quickback.config.ts` plugins:\n\n```bash title=\".env\"\nVITE_APP_NAME=My App\nVITE_APP_TAGLINE=Build faster, ship sooner\nENABLE_SIGNUP=true\nENABLE_ORGANIZATIONS=true\nENABLE_PASSKEY=true\nENABLE_ADMIN=true\n```\n\n### 4. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Library Mode\n\nInstall as a dependency instead of cloning:\n\n```bash\nnpm install quickback-better-auth-account-ui\n```\n\n```tsx\n\nsetAppConfig({\n authRoute: 'quickback',\n name: 'My App',\n companyName: 'My Company',\n});\n```\n\nSee [Library Usage](/stack/account-ui/library-usage) for the complete guide.\n\n## Next Steps\n\n- [Configuration](/compiler/config) — CMS and Account config reference\n- [Multi-Domain Architecture](/compiler/config/domains) — Custom domains and hostname routing\n- [Environment Variables](/stack/account-ui/environment-variables) — Complete variable reference\n- [Feature Flags](/stack/account-ui/features) — Enable and disable features\n- [Auth Hooks](/stack/account-ui/hooks) — Run project code on signup, login, and session events\n- [Customization](/stack/account-ui/customization) — Branding, labels, and theming"
|
|
311
|
+
},
|
|
312
|
+
"stack/account-ui/worker": {
|
|
313
|
+
"title": "Worker Setup",
|
|
314
|
+
"content": "# Worker Setup\n\nDeploy the Account UI as a Cloudflare Worker with static asset serving.\n\n## Quick Start\n\n### Using the Template\n\n```bash\nnpx degit Kardoe-com/quickback-better-auth-account-ui my-account-app\ncd my-account-app\nnpm install\n```\n\n### Using the Library\n\nIf you're consuming Account UI as an npm package, re-export the worker from the library:\n\n```ts title=\"src/worker.ts\"\nexport { default } from 'quickback-better-auth-account-ui/worker';\n```\n\nThen continue with the Wrangler configuration below.\n\n### 2. Configure Wrangler\n\nThe template includes a `wrangler.toml` pre-configured for Cloudflare Workers:\n\n```toml title=\"wrangler.toml\"\nname = \"my-account-app\"\ncompatibility_date = \"2025-01-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n# Custom domain (uncomment and set your domain)\n# routes = [\n# { pattern = \"account.example.com\", custom_domain = true }\n# ]\n\n# Worker entry point\nmain = \"src/worker.ts\"\n\n# Static assets\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\"\n```\n\n### 3. Build and Deploy\n\n```bash\nnpm run build\nnpx wrangler deploy\n```\n\n## Worker Entry Point\n\nThe worker is at `src/worker.ts`. It serves static assets and handles SPA routing:\n\n- Static asset serving via the `ASSETS` binding\n- SPA routing (all routes serve `index.html`)\n- Health check endpoint (`/health`)\n\n### Custom Worker Logic\n\nEdit `src/worker.ts` directly to add custom logic:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise\n\n### Multiple Environments\n\n```toml title=\"wrangler.toml\"\n# Development\n[env.dev]\nname = \"my-account-app-dev\"\nroute = \"account-dev.example.com/*\"\n\n[env.dev.vars]\nVITE_QUICKBACK_URL = \"https://secure-dev.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-dev.example.com\"\n\n# Staging\n[env.staging]\nname = \"my-account-app-staging\"\nroute = \"account-staging.example.com/*\"\n\n[env.staging.vars]\nVITE_QUICKBACK_URL = \"https://secure-staging.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account-staging.example.com\"\n\n# Production\n[env.production]\nname = \"my-account-app\"\nroute = \"account.example.com/*\"\n\n[env.production.vars]\nVITE_QUICKBACK_URL = \"https://secure.example.com\"\nVITE_ACCOUNT_APP_URL = \"https://account.example.com\"\n```\n\nDeploy to specific environment:\n\n```bash\nwrangler deploy --env staging\nwrangler deploy --env production\n```\n\n## Cloudflare Pages Alternative\n\nYou can also deploy to Cloudflare Pages instead of Workers:\n\n### 1. Configure Build\n\n```toml title=\"wrangler.toml\"\n# Remove [assets] section - Pages handles this\n\nname = \"my-account-app\"\npages_build_output_dir = \"dist/client\"\n```\n\n### 2. Deploy to Pages\n\n```bash\n# First time setup\nwrangler pages project create my-account-app\n\n# Deploy\nwrangler pages deploy dist/client\n```\n\n### 3. Configure Environment Variables\n\nSet environment variables in Cloudflare Pages dashboard:\n1. Go to your Pages project\n2. **Settings** → **Environment Variables**\n3. Add `VITE_*` variables\n4. Redeploy\n\n## Local Development\n\n### Option 1: Vite Dev Server\n\nThe fastest way to develop locally:\n\n```bash\nnpx vite dev\n```\n\nThis starts the Vite dev server with hot module replacement on `localhost:5173`.\n\n### Option 2: Wrangler Dev\n\nTest the worker locally with `wrangler dev`:\n\n```bash\nnpm run build && wrangler dev\n```\n\nThis runs the worker on `localhost:8787`.\n\n## Health Check\n\nThe worker includes a built-in health check endpoint:\n\n```bash\ncurl https://account.example.com/health\n```\n\nResponse:\n\n```json\n{\n \"status\": \"ok\",\n \"app\": \"auth-ui\"\n}\n```\n\nUse this for:\n- Uptime monitoring\n- Load balancer health checks\n- Deployment verification\n\n## Security Headers\n\nAdd security headers by editing `src/worker.ts`:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n // ... routing logic ...\n\n // Add security headers to response\n const response = await env.ASSETS.fetch(request);\n\n const headers = new Headers(response.headers);\n headers.set('X-Frame-Options', 'DENY');\n headers.set('X-Content-Type-Options', 'nosniff');\n headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n headers.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n },\n};\n```\n\n## Custom 404 Page\n\nServe a custom 404 page for unmatched routes:\n\n```ts title=\"src/worker.ts\"\nexport default {\n async fetch(request: Request, env: Env): Promise<Response> {\n const url = new URL(request.url);\n\n // Try to serve static asset\n const assetResponse = await env.ASSETS.fetch(request);\n\n if (assetResponse.status !== 404) {\n return assetResponse;\n }\n\n // Serve index.html for SPA routes\n if (!url.pathname.startsWith('/api/')) {\n const indexRequest = new Request(`${url.origin}/index.html`, request);\n return env.ASSETS.fetch(indexRequest);\n }\n\n // Custom 404 for API routes\n return new Response('Not Found', { status: 404 });\n },\n};\n```\n\n## Deployment Checklist\n\nBefore deploying to production:\n\n- [ ] Set all required environment variables (`VITE_QUICKBACK_URL` or `VITE_QUICKBACK_API_URL`, etc.)\n- [ ] Configure custom domain in Cloudflare\n- [ ] Add SSL certificate (automatic with Cloudflare)\n- [ ] Test all authentication flows\n- [ ] Configure DNS records\n- [ ] Set up monitoring/health checks\n- [ ] Test email sending\n- [ ] Verify passkey functionality (requires HTTPS)\n- [ ] Check CORS configuration on API\n- [ ] Review security headers\n- [ ] Test organization invitations\n- [ ] Verify redirection to main app works\n\n## Troubleshooting\n\n### Assets Not Loading\n\n**Problem**: 404 errors for static assets (JS, CSS)\n\n**Solution**: Check `directory` path in `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"dist/client\" # Must point to Vite's client build output\n```\n\n### Environment Variables Not Working\n\n**Problem**: Config values are undefined\n\n**Solution**: Remember that `VITE_*` variables are build-time. Either:\n1. Set them in `.env.production` before building\n2. Use `setAppConfig()` in `src/main.tsx` for runtime overrides\n3. Edit `src/config/app.ts` defaults directly\n\n### SPA Routing Issues\n\n**Problem**: Refreshing on `/profile` returns 404\n\n**Solution**: Ensure your worker serves `index.html` for all non-asset routes:\n\n```ts\nif (assetResponse.status === 404 && !url.pathname.startsWith('/api/')) {\n return env.ASSETS.fetch(new Request(`${url.origin}/index.html`, request));\n}\n```\n\n## Next Steps\n\n- **[Environment Variables](/stack/account-ui/environment-variables)** - Configure your deployment\n- **[Feature Flags](/stack/account-ui/features)** - Enable features\n- **[Customization](/stack/account-ui/customization)** - Brand your UI"
|
|
347
315
|
},
|
|
348
316
|
"stack/auth/api-keys": {
|
|
349
317
|
"title": "API Keys",
|
|
@@ -361,10 +329,22 @@ export const DOCS = {
|
|
|
361
329
|
"title": "JWT Optimization",
|
|
362
330
|
"content": "Quickback automatically optimizes authenticated API requests using JWT tokens. After the first request (which uses session cookies), subsequent requests skip the database entirely by sending a signed JWT that encodes the full auth context.\n\n## How It Works\n\n### Request Flow\n\n```\nFirst request (no JWT cached):\n Browser → Cookie auth → 2 DB queries → Response + set-auth-token header\n Browser caches JWT in localStorage\n\nSubsequent requests (JWT cached):\n Browser → Bearer JWT → Signature check only → Response (0 DB queries)\n```\n\n### What's in the JWT\n\nThe JWT encodes everything needed for auth middleware:\n\n| Claim | Description |\n|-------|-------------|\n| `sub` | User ID |\n| `orgId` | Active organization ID |\n| `role` | Organization membership role (`owner`, `admin`, `member`) |\n| `userRole` | Global user role (when admin panel is enabled) |\n| `email` | User email |\n| `name` | User display name |\n| `iat` | Issued-at timestamp |\n| `exp` | Expiry (15 minutes from issue) |\n\n### Signing\n\nJWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET`. No additional configuration is needed — this uses the same secret you already set for Better Auth.\n\n---\n\n## Server-Side Validation\n\n**Every authenticated API request is validated server-side before it reaches your handler.** There is no \"trust the client\" shortcut — the middleware runs full signature verification on each request.\n\nValidation steps (in generated `src/middleware/auth.ts`):\n\n1. Extract the `Authorization: Bearer <token>` header\n2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`\n3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)\n4. Check `exp` against the current time\n5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query\n6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header\n\nThe Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.\n\n---\n\n## Token Lifecycle\n\n### Automatic Minting\n\nWhen a request arrives without a JWT (or with an expired one), the auth middleware:\n\n1. Authenticates via session cookie (existing Better Auth flow)\n2. Signs a JWT with the full auth context\n3. Returns it in the `set-auth-token` response header\n\nThe Quickback API client (`quickback-client.ts`) automatically captures this header and stores the JWT in `localStorage`.\n\n### Re-minting on Org Switch\n\nWhen a user switches organizations, the JWT must be re-minted because `orgId` and `role` change. The auth UI handles this automatically:\n\n```typescript\n// This happens automatically in the org switcher\nawait authClient.organization.setActive({ organizationSlug: slug });\n\n// Fetch fresh JWT with new org context\nconst res = await fetch('/api/v1/token', {\n method: 'POST',\n credentials: 'include',\n});\nconst { token } = await res.json();\nlocalStorage.setItem('bearer_token', token);\n```\n\n### Invalidation on Role Changes\n\nWhen an admin changes a user's role or removes them from an organization, the server broadcasts an `auth:token-invalidated` event via WebSocket. The client automatically clears the cached JWT, forcing the next request to fall back to session auth and mint a fresh token.\n\n```\nAdmin changes user role\n → databaseHooks fires on member update\n → Broadcasts auth:token-invalidated via realtime\n → Client clears localStorage JWT\n → Next request uses session cookie → gets fresh JWT\n```\n\n### Expiry\n\nJWTs expire after 15 minutes. This is a safety net — in practice, JWTs are re-minted well before expiry through the `set-auth-token` response header on session-fallback requests.\n\nWhen a JWT expires or is invalid:\n1. The middleware silently falls back to session cookie auth\n2. A fresh JWT is minted and returned in the response header\n3. The client stores the new JWT for subsequent requests\n\n---\n\n## Token Endpoint\n\n`POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.\n\n**Request:**\n```bash\ncurl -X POST https://your-api.example.com/api/v1/token \\\n -H \"Content-Type: application/json\" \\\n --cookie \"better-auth.session_token=...\"\n```\n\n**Response:**\n```json\n{\n \"token\": \"eyJhbGciOiJIUzI1NiJ9...\"\n}\n```\n\nUse this endpoint after operations that change auth context (like switching organizations) to get a JWT that reflects the new state.\n\n---\n\n## Client Integration\n\n### Quickback API Client\n\nThe `quickback-client.ts` API client handles JWT auth automatically:\n\n- **Sends** the cached JWT as `Authorization: Bearer <token>` on every request\n- **Captures** refreshed JWTs from `set-auth-token` response headers\n- **Clears** the JWT on `401` responses (falls back to session cookie)\n\nNo additional client configuration is needed.\n\n### Custom API Calls\n\nIf you make direct `fetch()` calls to your API (outside the Quickback client), include the JWT:\n\n```typescript\nconst jwt = localStorage.getItem('bearer_token');\n\nconst res = await fetch('https://your-api.example.com/api/v1/things', {\n headers: {\n 'Authorization': `Bearer ${jwt}`,\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Fallback to session cookie if no JWT\n});\n\n// Capture refreshed token\nconst newToken = res.headers.get('set-auth-token');\nif (newToken) {\n localStorage.setItem('bearer_token', newToken);\n}\n```\n\n### Sign Out\n\nClear the JWT on sign-out to prevent stale tokens:\n\n```typescript\nlocalStorage.removeItem('bearer_token');\nawait authClient.signOut();\n```\n\n---\n\n## Security\n\n### Threat Model\n\n| Threat | Mitigation |\n|--------|------------|\n| Token theft (XSS) | 15-minute expiry limits exposure window. `httpOnly` cookies protect the session. |\n| Token replay | Short expiry + `set-auth-token` rotation on session fallback |\n| Stale permissions | WebSocket `auth:token-invalidated` broadcast on role changes |\n| Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |\n| Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |\n\n### Key Points\n\n- JWTs are a **performance optimization**, not a replacement for session auth\n- Session cookies remain the source of truth — JWTs are derived from them\n- If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth\n- No additional secrets or configuration needed — uses your existing `BETTER_AUTH_SECRET`\n- The JWT contains no sensitive data beyond what's already in the auth context\n\n---\n\n## Files Worker\n\nThe files worker (for Cloudflare R2 file uploads) also supports JWT authentication. When a request includes a JWT `Authorization` header, the worker verifies it directly instead of calling back to the auth API — eliminating a network round-trip for file operations.\n\n---\n\n## Relation to Better Auth's JWT Plugin\n\nQuickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.\n\n### What Quickback ships by default\n\n- Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`\n- Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries\n- Signed with `BETTER_AUTH_SECRET`\n- Used by the generated auth middleware as a fast-path ahead of `getSession()`\n\n### What Better Auth's JWT plugin gives you (opt-in)\n\nEnable it with `plugins: [\"jwt\"]` in your auth config:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\nYou get:\n- JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services\n- BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)\n- Standard OIDC-style claims via BA's `definePayload` hook\n\n### Why Quickback doesn't use BA's plugin internally\n\nBetter Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.\n\n### When to enable BA's JWT plugin anyway\n\nTurn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.\n\nEnabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.\n\n---\n\n## Related\n\n- [Auth Overview](/stack/auth) — Setup and configuration\n- [Auth Security](/stack/auth/security) — Cookie security, rate limiting, CORS\n- [API Keys](/stack/auth/api-keys) — Programmatic API access"
|
|
363
331
|
},
|
|
332
|
+
"stack/auth/plugins/aws-ses": {
|
|
333
|
+
"title": "AWS SES Plugin",
|
|
334
|
+
"content": "`@quickback-dev/better-auth-aws-ses` is a Better Auth plugin that sends transactional emails via AWS SES. It handles AWS Signature V4 signing, HTML/text email templates, and rate limiting — designed to work in Cloudflare Workers (no Node.js `aws-sdk` dependency).\n\n> **Cloudflare Email is the default.** As of the Cloudflare Email Sending public beta, the zero-config `send_email` binding is Quickback's default transport for Cloudflare deploys — no API keys, no SES setup. See [Email Configuration](/compiler/config#email-configuration). Use AWS SES when you need it (non-Cloudflare runtimes, existing SES infra, or specific deliverability/compliance requirements).\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-aws-ses\n```\n\nThis plugin is wired up only when you explicitly opt in via `email.provider: 'aws-ses'` in your Quickback config. Without that, `email.provider` defaults to `'cloudflare'` and the Cloudflare Email helper is used instead.\n\n## Email Types\n\nThe plugin handles 8 email types:\n\n| Endpoint | When Sent |\n|----------|-----------|\n| `/ses/send-verification` | Signup email verification |\n| `/ses/send-password-reset` | Password reset request |\n| `/ses/send-magic-link` | Passwordless sign-in link |\n| `/ses/send-otp` | One-time password code |\n| `/ses/send-welcome` | Post-signup welcome email |\n| `/ses/send-organization-invitation` | Team/org invite with role |\n| Combo auth | Magic link + OTP in a single email |\n| Delete account | Account deletion confirmation |\n\n### Combo Auth Mode\n\nWhen `useComboAuthEmail: true` is set, the plugin sends a single email that includes both a magic link button and an OTP code. Users can choose either method to authenticate.\n\n## AWS Signature V4\n\nThe plugin signs requests to SES using AWS Signature V4 with the Web Crypto API (`crypto.subtle`), making it compatible with Cloudflare Workers without any AWS SDK dependency.\n\n## Templates\n\nEach email type has both HTML and plain text templates. Templates include:\n\n- Responsive HTML layout with MSO (Microsoft Outlook) support\n- Security warning banners for sensitive operations\n- Fallback plain text versions for all email clients\n- XSS prevention via HTML escaping and URL sanitization\n\n## Configuration\n\n### Server Plugin\n\n```typescript\n\nconst auth = betterAuth({\n plugins: [\n awsSESPlugin({\n region: env.AWS_SES_REGION,\n accessKeyId: env.AWS_ACCESS_KEY_ID,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n fromEmail: env.EMAIL_FROM,\n fromName: env.EMAIL_FROM_NAME || \"My App\",\n replyTo: env.EMAIL_REPLY_TO,\n appName: env.APP_NAME || \"My App\",\n appUrl: env.APP_URL,\n useComboAuthEmail: true, // Optional: combine magic link + OTP\n }),\n ],\n});\n```\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [awsSESClientPlugin()],\n});\n```\n\n## Required Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `AWS_ACCESS_KEY_ID` | AWS access key (use Wrangler secrets) |\n| `AWS_SECRET_ACCESS_KEY` | AWS secret key (use Wrangler secrets) |\n| `AWS_SES_REGION` | SES region (e.g., `us-east-2`) |\n| `EMAIL_FROM` | Sender email address (must be SES-verified) |\n\n## Optional Variables\n\n| Variable | Description |\n|----------|-------------|\n| `EMAIL_FROM_NAME` | Sender display name |\n| `EMAIL_REPLY_TO` | Reply-to address (defaults to `EMAIL_FROM`) |\n| `APP_NAME` | Application name shown in email templates |\n| `APP_URL` | Application URL for links in emails |\n| `BETTER_AUTH_URL` | Auth API URL (for verification/reset links) |\n\n## Rate Limiting\n\nThe plugin includes basic in-memory rate limiting per recipient:\n\n- Configurable hourly and daily limits\n- Per-recipient tracking\n- For production, consider using an external store (Redis, KV)\n\n```typescript\nawsSESPlugin({\n // ...\n rateLimit: {\n maxEmailsPerHour: 10,\n maxEmailsPerDay: 50,\n },\n})\n```\n\n## Error Handling\n\n- Email failures return `false` (don't throw) — signup/login flows continue even if email delivery fails\n- Invalid or placeholder AWS credentials are detected at startup\n- Detailed console logging for debugging delivery issues\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP authentication\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
335
|
+
},
|
|
336
|
+
"stack/auth/plugins/combo-auth": {
|
|
337
|
+
"title": "Combo Auth Plugin",
|
|
338
|
+
"content": "`@quickback-dev/better-auth-combo-auth` provides a combined authentication flow that sends both a magic link and an OTP code in a single email. Users can click the link (one-click) or enter the 6-digit OTP code — whichever is more convenient.\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-combo-auth\n```\n\n## Server Setup\n\nAdd the plugin to your Better Auth configuration:\n\n```typescript\n\nexport const auth = betterAuth({\n plugins: [\n comboAuth({\n sendComboAuth: async ({ email, otp, url }) => {\n // Send email with both the magic link (url) and OTP code (otp)\n await sendEmail({\n to: email,\n subject: \"Sign in to My App\",\n html: `\n <p>Click the link below to sign in:</p>\n <a href=\"${url}\">Sign in to My App</a>\n <p>Or enter this code: <strong>${otp}</strong></p>\n `,\n });\n },\n }),\n ],\n});\n```\n\n## Client Usage\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [comboAuthClient()],\n});\n\n// Request authentication — sends email with link + OTP\nawait authClient.signIn.comboAuth({\n email: \"user@example.com\",\n});\n\n// Verify with OTP code (if user enters it manually)\nawait authClient.signIn.comboAuth({\n email: \"user@example.com\",\n otp: \"123456\",\n});\n```\n\n## How It Works\n\n1. User enters their email and requests sign-in\n2. A single email is sent containing both a magic link and a 6-digit OTP\n3. **Option A:** User clicks the magic link — authenticated immediately\n4. **Option B:** User enters the OTP code — authenticated after verification\n\nThis provides the best of both worlds: convenience of magic links with the reliability of OTP codes (useful when magic links don't work well, e.g., opening email on a different device).\n\n## See Also\n\n- [Auth Plugins](/stack/auth/plugins) — All authentication plugin options\n- [Upgrade Anonymous](/stack/auth/plugins/upgrade-anonymous) — Convert anonymous sessions to full accounts\n- [AWS SES](/stack/auth/plugins/aws-ses) — Email delivery for auth flows"
|
|
339
|
+
},
|
|
364
340
|
"stack/auth/plugins": {
|
|
365
341
|
"title": "Auth Plugins",
|
|
366
342
|
"content": "Quickback ships with a curated set of Better Auth plugins and helper wiring so your auth stack is production-ready by default. Enable these in `quickback.config.ts` under `providers.auth`.\n\n## Available Plugins\n\n### Email OTP (with AWS SES)\n\nQuickback wires the Better Auth Email OTP flow to AWS SES. When `emailOtp` is enabled, the compiler emits the SES plugin and combo-auth email flow (magic link + OTP).\n\n**Enable in config:**\n\n```ts\n\nexport default defineConfig({\n name: \"quickback-api\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n AWS_SES_REGION: \"us-east-2\",\n EMAIL_FROM: \"noreply@yourdomain.com\",\n EMAIL_FROM_NAME: \"Your App | Account Services\",\n APP_NAME: \"Your App\",\n APP_URL: \"https://account.yourdomain.com\",\n BETTER_AUTH_URL: \"https://api.yourdomain.com\",\n },\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"emailOtp\"],\n }),\n },\n});\n```\n\n**Endpoints:**\n- `POST /auth/v1/email-otp/send-verification-otp`\n- `POST /auth/v1/email-otp/verify-otp`\n\n**Email readiness check:**\n\nUse this to show UI warnings when SES isn't configured.\n\n- `GET /api/v1/system/email-status`\n- Response: `{ \"emailConfigured\": true|false }`\n\n### Upgrade Anonymous\n\nAdds a first-class endpoint to convert an anonymous user into a full user. This flips `isAnonymous` to `false` and refreshes the session cache immediately.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n}),\n```\n\n**Endpoint:**\n- `POST /auth/v1/upgrade-anonymous`\n\n**Note:** If you send `Content-Type: application/json`, include a body (an empty `{}` is fine). This avoids request parsing errors in some clients.\n\n### AWS SES Plugin\n\nThis is a Quickback-provided Better Auth plugin for Email OTP and other transactional emails. It handles SES signing and delivery over the Web Crypto API so it runs in Cloudflare Workers without the AWS SDK. It is wired up only when you opt in via `email.provider: 'aws-ses'` — the default transport is Cloudflare Email Sending (`send_email` binding).\n\nRequired vars (only when `email.provider: 'aws-ses'` is set; use Wrangler secrets for credentials):\n- `AWS_ACCESS_KEY_ID` (secret)\n- `AWS_SECRET_ACCESS_KEY` (secret)\n- `AWS_SES_REGION`\n- `EMAIL_FROM`\n\nOptional vars:\n- `EMAIL_FROM_NAME`\n- `EMAIL_REPLY_TO` - Reply-to address for emails (defaults to `EMAIL_FROM`)\n- `APP_NAME`\n- `APP_URL`\n- `BETTER_AUTH_URL`\n\n### Magic Links\n\nMagic links provide passwordless authentication by sending a unique login link to the user's email. When clicked, the link authenticates the user without requiring a password.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"magicLink\"],\n}),\n```\n\n**Endpoints:**\n- `POST /auth/v1/magic-link/send` - Send magic link email\n- `GET /auth/v1/magic-link/verify` - Verify magic link token\n\n**Email customization:**\n\nMagic link emails use the same AWS SES configuration as Email OTP. Customize the email template via environment variables:\n\n- `APP_NAME` - Application name in email subject\n- `APP_URL` - Base URL for magic link redirect\n- `EMAIL_FROM` - Sender email address\n- `EMAIL_FROM_NAME` - Sender display name\n\n**Frontend integration:**\n\n```ts\n// Request magic link\nawait fetch('/auth/v1/magic-link/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: 'user@yourdomain.com' })\n});\n\n// User clicks link in email, which redirects to your app\n// The token is verified automatically via the callback URL\n```\n\n### Passkeys\n\nPasskeys provide passwordless authentication using WebAuthn/FIDO2. Users authenticate with biometrics (fingerprint, face) or device PIN instead of passwords.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"passkey\"],\n}),\n```\n\n**Required environment variable:**\n- `ACCOUNT_URL` - Your account/frontend URL (used as the relying party origin for WebAuthn)\n\n**Endpoints:**\n- `POST /auth/v1/passkey/register/options` - Get registration challenge\n- `POST /auth/v1/passkey/register/verify` - Complete registration\n- `POST /auth/v1/passkey/authenticate/options` - Get authentication challenge\n- `POST /auth/v1/passkey/authenticate/verify` - Complete authentication\n- `GET /auth/v1/passkey/list-user-passkeys` - List user's registered passkeys\n- `POST /auth/v1/passkey/delete-passkey` - Delete a registered passkey\n\n**Browser support:**\n\nPasskeys are supported in all modern browsers:\n- Chrome 67+\n- Safari 14+\n- Firefox 60+\n- Edge 79+\n\n**Registration flow:**\n\n```ts\n// 1. Get registration options\nconst optionsRes = await fetch('/auth/v1/passkey/register/options', {\n method: 'POST',\n credentials: 'include'\n});\nconst options = await optionsRes.json();\n\n// 2. Create credential using WebAuthn API\nconst credential = await navigator.credentials.create({\n publicKey: options\n});\n\n// 3. Send credential to server\nawait fetch('/auth/v1/passkey/register/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n**Authentication flow:**\n\n```ts\n// 1. Get authentication options\nconst optionsRes = await fetch('/auth/v1/passkey/authenticate/options', {\n method: 'POST'\n});\nconst options = await optionsRes.json();\n\n// 2. Get credential using WebAuthn API\nconst credential = await navigator.credentials.get({\n publicKey: options\n});\n\n// 3. Verify credential\nawait fetch('/auth/v1/passkey/authenticate/verify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(credential)\n});\n```\n\n### JWT Plugin\n\nBetter Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.\n\n**Enable in config:**\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: [\"jwt\"],\n}),\n```\n\n**Endpoints:**\n- `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens\n- `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session\n\n**When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.\n\n## Where This Runs\n\nAll Better Auth plugin routes are served under your auth base path:\n\n```\n/auth/v1/*\n```"
|
|
367
343
|
},
|
|
344
|
+
"stack/auth/plugins/upgrade-anonymous": {
|
|
345
|
+
"title": "Upgrade Anonymous Plugin",
|
|
346
|
+
"content": "`@quickback-dev/better-auth-upgrade-anonymous` provides a single endpoint to convert anonymous users into full authenticated users. It flips the `isAnonymous` flag, optionally updates email and name, and refreshes the session — no re-authentication required.\n\n## Installation\n\n```bash\nnpm install @quickback-dev/better-auth-upgrade-anonymous\n```\n\n## Configuration\n\nEnable both the `anonymous` and `upgradeAnonymous` plugins:\n\n```typescript\nauth: defineAuth(\"better-auth\", {\n plugins: [\"anonymous\", \"upgradeAnonymous\"],\n})\n```\n\nThe plugin accepts optional configuration:\n\n```typescript\n\nupgradeAnonymous({\n emailConfigured: true, // Whether email delivery is available\n requireEmailVerification: true, // Whether to require email verification\n})\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `emailConfigured` | `false` | When `true` and an email is provided, `emailVerified` is set based on `requireEmailVerification` |\n| `requireEmailVerification` | `true` | When `true`, provided emails are marked unverified (requiring OTP). When `false`, emails are marked verified immediately |\n\n## Endpoint\n\n```\nPOST /auth/v1/upgrade-anonymous\n```\n\n### Flow\n\n1. Validates the user's session (returns `401` if not authenticated)\n2. Checks if the user is already upgraded (returns success immediately if so)\n3. If an email is provided, checks for duplicates (returns `400` if email is taken)\n4. Updates `isAnonymous` to `false`, plus optional `email`, `name`, and `emailVerified` fields\n5. Refreshes the session cookie with the updated user object\n6. Returns the updated user, session, and `verificationRequired` flag\n\n### Request\n\nThe body is optional. When provided, it accepts:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `email` | `string` (email) | Optional. Real email to replace the anonymous placeholder |\n| `name` | `string` | Optional. User's display name |\n\n```bash\n# Minimal — just upgrade, no email/name\ncurl -X POST https://api.example.com/auth/v1/upgrade-anonymous \\\n -H \"Cookie: better-auth.session_token=...\"\n\n# With email and name\ncurl -X POST https://api.example.com/auth/v1/upgrade-anonymous \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"jane@example.com\", \"name\": \"Jane\"}'\n```\n\n### Response\n\n```json\n{\n \"success\": true,\n \"verificationRequired\": true,\n \"user\": {\n \"id\": \"usr_abc123\",\n \"email\": \"jane@example.com\",\n \"isAnonymous\": false\n },\n \"session\": {\n \"id\": \"sess_xyz\",\n \"userId\": \"usr_abc123\"\n }\n}\n```\n\nThe `verificationRequired` field is `true` when all three conditions are met:\n- An email was provided in the request body\n- `emailConfigured` is `true` in plugin config\n- `requireEmailVerification` is `true` in plugin config\n\nWhen `verificationRequired` is `true`, the frontend should send a verification OTP and redirect the user to verify their email.\n\n## How It Works\n\nThe plugin is designed to be flexible:\n\n- **Minimal by default** — With no body, only changes `isAnonymous` from `true` to `false`\n- **Optional email/name** — Can update email and name in the same request\n- **Duplicate protection** — Rejects emails already associated with another account\n- **Verification-aware** — Returns `verificationRequired` so the frontend knows whether to trigger OTP\n- **Session preserved** — Same session ID, no re-authentication needed\n- **Idempotent** — Calling on an already-upgraded user returns success immediately\n\n## Typical Flows\n\n### Passkey Signup (no email)\n\n1. User creates anonymous session\n2. User registers a passkey\n3. App calls `POST /auth/v1/upgrade-anonymous` with no body\n4. User is now a full user with passkey auth — no email on file\n\n### Passkey Signup (with email)\n\n1. User creates anonymous session\n2. User registers a passkey\n3. User optionally enters email/name on the email collection step\n4. App calls `POST /auth/v1/upgrade-anonymous` with `{ email, name }`\n5. If `verificationRequired`: app sends OTP, user verifies, then redirects to dashboard\n6. Otherwise: user goes straight to dashboard\n\n### Email Signup\n\n1. User starts as anonymous (created via Better Auth's `anonymous` plugin)\n2. User provides email/password through your UI (via combo auth or signup)\n3. Your app calls `POST /auth/v1/upgrade-anonymous`\n4. User is now a full user with the same ID and all their data intact\n\n### Client Plugin\n\n```typescript\n\nconst authClient = createAuthClient({\n plugins: [upgradeAnonymousClient()],\n});\n\n// Upgrade the current anonymous user\nawait authClient.upgradeAnonymous();\n```\n\n## See Also\n\n- [Combo Auth Plugin](/stack/auth/plugins/combo-auth) — Combined magic link + OTP for collecting credentials\n- [Auth Configuration](/compiler/config/providers) — Configuring auth plugins"
|
|
347
|
+
},
|
|
368
348
|
"stack/auth/security": {
|
|
369
349
|
"title": "Authentication Security",
|
|
370
350
|
"content": "Quickback enforces secure authentication defaults out of the box. This page explains how cookie security, rate limiting, and cross-domain authentication work, plus how to configure them for your use case.\n\n## Cookie Security\n\nQuickback sets secure cookie defaults to protect against CSRF, XSS, and man-in-the-middle attacks.\n\n### Default Attributes\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax', // CSRF protection\n secure: true, // HTTPS only\n httpOnly: true, // No JavaScript access\n }\n }\n})\n```\n\n**What each attribute does:**\n\n| Attribute | Value | Purpose |\n|-----------|-------|---------|\n| `sameSite` | `lax` | Blocks cookies on cross-site POST requests (CSRF protection) |\n| `secure` | `true` | Cookies only sent over HTTPS (prevents interception) |\n| `httpOnly` | `true` | JavaScript cannot access cookies via `document.cookie` (XSS mitigation) |\n\n### SameSite Options\n\n- **`lax` (recommended)**: Blocks cross-site POST requests but allows top-level navigation. Best balance of security and usability.\n- **`strict`**: Blocks cookies on all cross-site requests. More secure but may break legitimate flows (e.g., returning from payment provider).\n- **`none`**: Allows all cross-site requests. Required for cross-domain authentication (requires `secure: true`).\n\n### Development Override\n\nFor local development over HTTP, you can relax the `secure` flag:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Warning**: Never use `secure: false` in production.\n\n---\n\n## Rate Limiting\n\nQuickback includes per-IP rate limiting by default to protect against brute-force attacks and abuse.\n\n### How It Works\n\n**Rate limits are applied per IP address**, not globally:\n\n```\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.1 │\n│ Endpoint: /sign-in/email │\n│ Limit: 10 requests per 60 seconds │\n│ │\n│ Request 1-10: ✅ Allowed │\n│ Request 11: ❌ 429 Too Many Requests │\n│ After 60s: Counter resets to 0 │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.2 (different IP) │\n│ Endpoint: /sign-in/email │\n│ Independent counter: Not affected by 1.1 │\n│ Starts at 0 │\n└─────────────────────────────────────────────────┘\n```\n\n### Default Configuration\n\n```ts\nauth: defineAuth(\"better-auth\", {\n rateLimit: {\n enabled: true,\n window: 60, // 60 second window\n max: 100, // 100 requests per IP per window\n customRules: {\n \"/sign-in/email\": { window: 60, max: 10 },\n \"/sign-in/social\": { window: 60, max: 10 },\n \"/device/init\": { window: 60, max: 5 },\n \"/device/poll\": { window: 60, max: 30 },\n \"/device/token\": { window: 60, max: 10 },\n }\n }\n})\n```\n\n### Custom Rules by Endpoint\n\nSet different limits based on endpoint sensitivity:\n\n| Endpoint Type | Recommended Limit | Reasoning |\n|---------------|-------------------|-----------|\n| Sign-in | 10/min per IP | Prevent credential stuffing |\n| Device codes | 5/min per IP | Prevent device code enumeration |\n| Token exchange | 10/min per IP | Prevent token brute-force |\n| Polling | 30/min per IP | Allow reasonable polling (every 2s) |\n| General API | 100/min per IP | Balance abuse prevention and usability |\n\n### Why Per-IP?\n\n✅ **Per-IP** (what Quickback uses):\n- Prevents single attacker from brute-forcing\n- Doesn't penalize legitimate users when one IP is malicious\n- Standard for auth endpoints\n\n❌ **Global total** (not used):\n- Would allow distributed attacks to succeed\n- One attacker with many IPs could exhaust the limit for everyone\n- Not effective for security\n\n### Disabling Rate Limiting\n\nNot recommended, but you can disable for testing:\n\n```ts\nrateLimit: {\n enabled: process.env.NODE_ENV === 'production',\n window: 60,\n max: 1000, // Higher limit for development\n}\n```\n\n---\n\n## Cross-Domain Authentication\n\nFor applications spanning multiple subdomains (e.g., `account.example.com`, `api.example.com`, `dashboard.example.com`), Quickback provides dual-layer security.\n\n### The Problem\n\nBrowsers restrict cookies to exact domains by default. If your auth API is at `api.example.com`, cookies won't be sent to `dashboard.example.com`.\n\n### The Solution: Dual-Layer Protection\n\nQuickback uses two complementary security layers:\n\n#### 1. Cookie Domain (Browser-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: 'example.com' // All *.example.com can access cookies\n }\n }\n})\n```\n\n**Behavior**: Allows ALL subdomains to access the cookie (browser limitation per RFC 6265)\n- Cannot selectively allow only specific subdomains\n- All-or-nothing: either exact domain only, or all subdomains\n\n#### 2. Trusted Origins (Application-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n 'https://account.example.com',\n 'https://api.example.com',\n 'https://dashboard.example.com'\n ]\n})\n```\n\n**Behavior**: Better Auth validates request origins before processing auth operations\n- Granular whitelist of allowed origins\n- Blocks requests from untrusted subdomains even if they have the cookie\n- Prevents CSRF and unauthorized auth operations\n\n### Security Model\n\n```\n┌─────────────────────────────────────────────────┐\n│ Subdomain: evil.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✗ │\n│ Result: REQUEST BLOCKED by Better Auth │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ Subdomain: account.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✓ │\n│ Result: REQUEST ALLOWED │\n└─────────────────────────────────────────────────┘\n```\n\n### Full Cross-Domain Configuration\n\n```ts\n\nexport default defineConfig({\n name: \"my-saas\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ACCOUNT_URL: \"https://account.example.com\",\n BETTER_AUTH_URL: \"https://api.example.com\",\n }\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"organization\"],\n\n // Trusted origins (granular whitelist)\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\",\n \"https://dashboard.example.com\",\n \"http://localhost:3000\", // Development\n ],\n\n // Cookie configuration\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n secure: true,\n sameSite: \"none\", // Required for cross-domain\n httpOnly: true,\n }\n }\n })\n }\n})\n```\n\n**Important**: When using `sameSite: \"none\"`, you must also set `secure: true`. This is required by browsers.\n\n---\n\n## Environment Variables\n\nSet these in your Cloudflare Workers environment or `.env` file:\n\n### Required\n\n```bash\n# Better Auth secret (minimum 32 characters)\nBETTER_AUTH_SECRET=your-secret-key-min-32-chars\n\n# Base URL for Better Auth endpoints\nBETTER_AUTH_URL=https://api.example.com\n```\n\n### Optional (Cross-Domain)\n\n```bash\n# Enable cross-subdomain cookies\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\n\n# Trusted origins (comma-separated)\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\n\n# CORS allowed origins (typically matches trustedOrigins)\nALLOWED_ORIGINS=https://account.example.com,https://api.example.com\n```\n\n### Setting Secrets with Wrangler\n\nFor sensitive values like `BETTER_AUTH_SECRET`:\n\n```bash\nwrangler secret put BETTER_AUTH_SECRET\n# Paste your secret when prompted\n```\n\nFor non-secret vars, add to `wrangler.toml`:\n\n```toml\n[vars]\nBETTER_AUTH_URL = \"https://api.example.com\"\nCROSS_SUBDOMAIN_COOKIES = \"false\"\n```\n\n---\n\n## Security Best Practices\n\n### Single Domain (Recommended)\n\nFor most applications, use exact domain cookies:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\"https://app.example.com\"],\n advanced: {\n crossSubDomainCookies: {\n enabled: false // Default: exact domain only\n },\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Benefits**:\n- Maximum security (smallest cookie scope)\n- No cross-subdomain attack surface\n- Simpler configuration\n\n### Multi-Subdomain (When Needed)\n\nOnly enable cross-subdomain cookies if you need SSO across multiple subdomains:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://dashboard.example.com\",\n ],\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n sameSite: 'none', // Required for cross-domain\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Security requirements**:\n- Trust all subdomains equally (any compromised subdomain can steal cookies)\n- Use separate root domains for untrusted services\n- Always set `trustedOrigins` for granular control\n\n### CORS vs Trusted Origins\n\nThese serve different purposes and should typically match:\n\n| Setting | Purpose |\n|---------|---------|\n| `ALLOWED_ORIGINS` (CORS) | Controls which origins can make credentialed requests |\n| `trustedOrigins` (Better Auth) | Validates origins for auth operations + prevents open redirects |\n\n**Example**:\n\n```ts\ndatabase: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ALLOWED_ORIGINS: \"https://account.example.com,https://api.example.com\"\n }\n}),\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\"\n ]\n})\n```\n\n### Checklist\n\nBefore deploying to production:\n\n- [ ] `BETTER_AUTH_SECRET` is set (minimum 32 random characters)\n- [ ] `secure: true` is enabled (HTTPS only)\n- [ ] `httpOnly: true` is enabled (XSS protection)\n- [ ] `sameSite: 'lax'` or `'strict'` unless cross-domain required\n- [ ] `trustedOrigins` includes only your domains\n- [ ] `ALLOWED_ORIGINS` matches `trustedOrigins`\n- [ ] Rate limiting is enabled (`rateLimit.enabled: true`)\n- [ ] Custom rate limits set for sensitive endpoints\n\n---\n\n## Deployment Considerations\n\n### Behind Proxy/Load Balancer\n\nIf your app is behind a proxy, ensure IP address headers are trusted:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n autoDetectIpAddress: true, // Uses X-Forwarded-For or CF-Connecting-IP\n})\n```\n\n**Cloudflare Workers**: IP automatically available via `CF-Connecting-IP` header\n\n**Other proxies**: Configure to trust `X-Forwarded-For` or `X-Real-IP`\n\n### Multiple Environments\n\nUse environment variables to configure different settings per environment:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',') || [],\n advanced: {\n crossSubDomainCookies: {\n enabled: process.env.CROSS_SUBDOMAIN_COOKIES === 'true',\n domain: process.env.COOKIE_DOMAIN,\n },\n defaultCookieAttributes: {\n sameSite: process.env.COOKIE_SAMESITE || 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Development** (`.dev.vars`):\n```bash\nTRUSTED_ORIGINS=http://localhost:3000,http://localhost:5173\nCROSS_SUBDOMAIN_COOKIES=false\nCOOKIE_SAMESITE=lax\n```\n\n**Production** (Wrangler secrets):\n```bash\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\nCOOKIE_SAMESITE=none\n```\n\n---\n\n## Further Reading\n\n- [Better Auth: Cookies Documentation](https://www.better-auth.com/docs/concepts/cookies)\n- [Better Auth: Security Guide](https://www.better-auth.com/docs/reference/security)\n- [OWASP: Cross-Site Request Forgery Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n- [MDN: SameSite Cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)"
|
|
@@ -373,25 +353,57 @@ export const DOCS = {
|
|
|
373
353
|
"title": "Using Auth",
|
|
374
354
|
"content": "This page covers how to use Better Auth in your Quickback Stack application — sign-in flows, session management, and working with organization context.\n\n## Sign-In Flows\n\nBetter Auth supports multiple sign-in methods:\n\n- **Email/Password** — Traditional credential-based authentication\n- **Email OTP** — One-time passwords sent via email\n- **Magic Links** — Passwordless email links\n- **Passkeys** — WebAuthn biometric/hardware key authentication\n\n## Session Handling\n\nSessions are stored in Cloudflare KV for fast edge-based lookups.\n\n```typescript\n// Access the current session in a Hono route\napp.get('/api/me', async (c) => {\n const session = c.get('session');\n const user = c.get('user');\n return c.json({ user, session });\n});\n```\n\n## Organization Context\n\nWhen organizations are enabled, the current organization is available in the request context:\n\n```typescript\nconst orgId = c.get('session')?.activeOrganizationId;\n```\n\n## Related\n\n- [Auth Overview](/stack/auth) — Setup and configuration\n- [Auth Plugins](/stack/auth/plugins) — Available plugins\n- [Auth Security](/stack/auth/security) — Security best practices"
|
|
375
355
|
},
|
|
376
|
-
"stack/
|
|
377
|
-
"title": "
|
|
378
|
-
"content": "
|
|
356
|
+
"stack/cms/actions": {
|
|
357
|
+
"title": "Actions",
|
|
358
|
+
"content": "# Actions\n\nActions are custom operations defined in your feature files (e.g., `approve`, `void`, `post`, `applyPayment`). The CMS renders them as clickable buttons with auto-generated input forms — no UI code required.\n\n## Where Actions Appear\n\nActions show up in two places:\n\n### Row Action Menu (Table Mode)\n\nIn Table mode, the three-dot menu on each row includes a section for custom actions. Actions are separated from standard operations (view, edit, delete) by a divider.\n\n### Action Bar (Detail View)\n\nIn the record detail view, an \"Actions\" card displays all available actions as buttons. Each button shows the action name, and hovering reveals the description as a tooltip.\n\n## Action Dialog\n\nClicking an action opens a modal dialog with:\n\n1. **Header** — Action name with an icon (lightning bolt for standard, warning triangle for destructive, download for file responses)\n2. **Description** — The action's description text\n3. **Side effects warning** — If the action has `sideEffects: \"sync\"`, an amber warning banner appears: \"This action has synchronous side effects (e.g., GL entries).\"\n4. **Confirmation step** — If the action has `cms.confirm`, a confirmation message appears before the input form\n5. **Input fields** — Auto-generated from the action's `inputFields` schema\n6. **Execute button** — Submits the action. Shows \"Executing...\" while in progress.\n7. **Cancel button** — Closes the dialog without executing\n\n### Input Field Types\n\nThe dialog generates the appropriate input control for each field:\n\n| Zod Type | Input Control | Notes |\n|----------|--------------|-------|\n| `string` | Text input | Free-text entry |\n| `number` | Number input | Step 0.01, supports decimals |\n| `boolean` | Checkbox | With label text |\n| `array<string>` | Text input | Comma-separated values, split on save |\n\nRequired fields are marked with a red asterisk. Default values from the schema are pre-filled.\n\n### Example\n\nGiven this action definition:\n\n```typescript\nactions: {\n applyPayment: {\n description: \"Apply a payment to this invoice\",\n input: 'z.object({ amount: z.number(), reference: z.string().optional() })',\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'posted' } },\n },\n sideEffects: \"sync\",\n cms: {\n label: \"Apply Payment\",\n icon: \"dollar-sign\",\n confirm: \"This will create GL entries. Continue?\",\n category: \"payments\",\n successMessage: \"Payment applied successfully\",\n order: 1,\n },\n },\n}\n```\n\nThe CMS renders a dialog with:\n\n- A number input for `amount` (required)\n- A text input for `reference` (optional)\n- A sync side effects warning\n- A confirmation step with the custom message\n- Only visible to admins and owners\n- Only visible on records where `status === \"posted\"`\n\n## Access Filtering\n\nActions are filtered based on two criteria:\n\n### Role Check\n\nThe action's `access.roles` array is compared against the current user's role. If the user's role is not in the list, the action is hidden.\n\n### Record Condition\n\nThe action's `access.record` conditions are evaluated against the current record's data. Supported conditions:\n\n| Operator | Example | Meaning |\n|----------|---------|---------|\n| `equals` | `{ status: { equals: 'pending' } }` | Field must equal value |\n| `notEquals` | `{ status: { notEquals: 'void' } }` | Field must not equal value |\n| `in` | `{ status: { in: ['pending', 'draft'] } }` | Field must be one of values |\n\nAll conditions must pass for the action to be visible. This means \"approve\" actions naturally disappear after a record is approved, and \"void\" actions only appear on voidable records.\n\n## CMS Metadata\n\nActions can include an optional `cms` property for enhanced CMS rendering. Actions without `cms` render with default behavior.\n\n| Property | Type | Default | Purpose |\n|----------|------|---------|---------|\n| `label` | `string` | camelCase split | Display name override |\n| `icon` | `string` | `\"zap\"` | Lucide icon name |\n| `confirm` | `string \\| boolean` | `false` | `true` = generic confirm, string = custom message |\n| `destructive` | `boolean` | `false` | Red styling + requires confirmation |\n| `category` | `string` | none | Group actions under a header |\n| `hidden` | `boolean` | `false` | Hide from CMS entirely (API-only actions) |\n| `successMessage` | `string` | none | Toast message after success |\n| `onSuccess` | `\"refresh\" \\| \"redirect:list\" \\| \"close\"` | `\"refresh\"` | Behavior after successful execution |\n| `order` | `number` | `0` | Sort priority (lower = first) |\n\n### Example with CMS metadata\n\n```typescript\n// features/invoices/actions/post.ts\n\nexport default defineAction({\n description: \"Post this invoice to accounts receivable\",\n input: z.object({}),\n access: { roles: [\"owner\", \"admin\"], record: { status: { equals: \"draft\" } } },\n sideEffects: \"sync\",\n cms: {\n label: \"Post Invoice\",\n icon: \"send\",\n confirm: \"This will post the invoice to AR and create GL entries. Continue?\",\n category: \"lifecycle\",\n successMessage: \"Invoice posted successfully\",\n onSuccess: \"refresh\",\n order: 1,\n },\n async execute({ db, record }) {\n // ... post invoice\n return { ok: true };\n },\n});\n```\n\n### Hiding API-only actions\n\n```typescript\n// features/invoices/actions/internal-recalc.ts\n\nexport default defineAction({\n description: \"Recalculate internal totals\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n cms: { hidden: true }, // Never shown in CMS\n async execute({ db, record }) {\n // ... recalc totals\n return { ok: true };\n },\n});\n```\n\n## Destructive Actions\n\nActions are styled as destructive when either:\n\n- The action's `cms.destructive` is `true`\n- The action is named `void` or `delete` (legacy fallback)\n\nDestructive actions receive:\n\n- **Red text** in the row action menu\n- **Warning triangle icon** (unless overridden by `cms.icon`)\n- **Red execute button** in the dialog (using `bg-destructive` styling)\n- **Automatic confirmation step** (unless `cms.confirm` is explicitly `false`)\n\nThis provides a visual cue that the action has permanent consequences.\n\n## Standalone Actions\n\nActions with `path:` set are standalone — not tied to a specific record. They appear in a separate section and don't receive a `recordId` when executed. The CMS passes `null` as the record ID for standalone actions.\n\n## File Response Actions\n\nActions with `responseType: \"file\"` show a download icon instead of the lightning bolt. When executed, the response is treated as a file download rather than a JSON result.\n\n## Execution Flow\n\n1. User clicks action in row menu or action bar\n2. Dialog opens with description, inputs, and warnings\n3. If `cms.confirm` is set, user sees confirmation step first\n4. User fills in required fields\n5. User clicks \"Execute\" (or \"Confirm\" after confirmation step)\n6. CMS calls `client.executeAction(table, actionName, recordId, input)`\n7. On success: `cms.successMessage` shown as toast (if set), then `cms.onSuccess` behavior\n8. On error: error message displayed in dialog\n\n## Next Steps\n\n- **[Security](/stack/cms/security)** — Access conditions and role-based access\n- **[Table Views](/stack/cms/table-views)** — Where actions appear in the UI\n- **[Schema Format Reference](/stack/cms/schema-format)** — ActionMeta type definition"
|
|
379
359
|
},
|
|
380
|
-
"stack/
|
|
381
|
-
"title": "
|
|
382
|
-
"content": "The Quickback Stack supports multiple database providers. Choose the one that fits your deployment target.\n\n## Providers\n\n| Provider | Best For | Features |\n|----------|----------|----------|\n| [Cloudflare D1](/stack/database/d1) | Edge-first apps | SQLite at the edge, zero-latency reads |\n| [Neon](/stack/database/neon) | Postgres apps | Serverless Postgres, branching, autoscaling |\n\n## Getting Started\n\n- **[D1 Setup](/stack/database/d1)** — Bindings, wrangler config, migrations\n- **[Using D1](/stack/database/using-d1)** — Drizzle queries, dual-DB mode, schema patterns\n- **[Neon](/stack/database/neon)** — Serverless Postgres setup and usage"
|
|
360
|
+
"stack/cms/components": {
|
|
361
|
+
"title": "Components Reference",
|
|
362
|
+
"content": "# Components Reference\n\nThe CMS is built from composable React components organized by function. Every component reads metadata from the schema registry and adapts its behavior based on the current role.\n\n## Layout\n\n### Sidebar\n\nThe main navigation sidebar. Reads the schema registry to build a collapsible feature-grouped table list.\n\n```typescript\ninterface SidebarProps {\n // No props — reads schema registry directly\n}\n```\n\n| Behavior | Description |\n|----------|-------------|\n| Feature grouping | Tables grouped by feature with collapsible sections |\n| Feature icons | Each feature gets a contextual icon (e.g., Calculator for accounting) |\n| Active state | Current table highlighted with primary color |\n| Internal filter | Tables with `internal: true` are hidden |\n| Footer stats | Shows total feature and table counts |\n\n### Header\n\nTop bar with tagline and role switcher.\n\n```typescript\ninterface HeaderProps {\n // No props — renders tagline and RoleSwitcher\n}\n```\n\n### RoleSwitcher\n\nDropdown to switch between `owner`, `admin`, and `member` roles. Available in demo mode. In live mode, the role is read from the authenticated session.\n\n```typescript\n// Uses RoleContext internally\n// Provides: role, setRole, session\n```\n\n## Table\n\n### DataTable\n\nStandard browse table with clickable rows and sortable columns.\n\n```typescript\ninterface DataTableProps {\n data: Record[];\n columns: ColumnDef[];\n onRowClick?: (row: Record) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `data` | Array of records to display |\n| `columns` | Column definitions (built by `ColumnFactory`) |\n| `onRowClick` | Handler when a row is clicked (navigates to detail view) |\n\n### SpreadsheetTable\n\nExcel/Google Sheets-like editable table with cell selection and keyboard navigation.\n\n```typescript\ninterface SpreadsheetTableProps {\n data: Record[];\n columns: ColumnDef[];\n onCellEdit: (recordId: string, field: string, value: unknown) => Promise<void>;\n editableFields: Set<string>;\n onFKSearch: (targetTable: string, query: string) => Promise<FKOption[]>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `data` | Array of records to display |\n| `columns` | Column definitions |\n| `onCellEdit` | Called when a cell value is saved (auto-saves on blur/Enter) |\n| `editableFields` | Set of field names that can be edited (from guards) |\n| `onFKSearch` | Async function for FK typeahead search |\n\n### Toolbar\n\nSearch bar, view selector, view mode toggle, and refresh button.\n\n```typescript\ninterface ToolbarProps {\n table: TableMeta;\n search: string;\n onSearchChange: (search: string) => void;\n onRefresh: () => void;\n selectedView?: string;\n onViewChange: (view: string | undefined) => void;\n viewMode: \"table\" | \"dataTable\";\n onViewModeChange: (mode: \"table\" | \"dataTable\") => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used to build view dropdown) |\n| `search` | Current search query |\n| `onSearchChange` | Handler for search input changes |\n| `onRefresh` | Refreshes the table data |\n| `selectedView` | Currently selected view name (undefined = all fields) |\n| `onViewChange` | Handler for view selection changes |\n| `viewMode` | Current view mode |\n| `onViewModeChange` | Handler for toggling between Table and Data Table |\n\n### Pagination\n\nPage navigation controls with range indicator.\n\n```typescript\ninterface PaginationProps {\n page: number;\n pageSize: number;\n total: number;\n onPageChange: (page: number) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `page` | Current page number (1-indexed) |\n| `pageSize` | Records per page |\n| `total` | Total record count |\n| `onPageChange` | Handler for page changes |\n\n### RowActions\n\nThree-dot dropdown menu on each table row with view, edit, delete, and custom actions.\n\n```typescript\ninterface RowActionsProps {\n table: TableMeta;\n record: Record;\n onDelete?: (id: string) => void;\n onAction?: (action: ActionMeta, record: Record) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used for CRUD access checks and action filtering) |\n| `record` | The row's record data |\n| `onDelete` | Handler for delete action |\n| `onAction` | Handler for custom action selection |\n\n### ColumnFactory\n\nUtility function (not a component) that builds column definitions from table metadata.\n\n```typescript\nfunction buildColumns(\n table: TableMeta,\n role: Role,\n options?: { viewFields?: string[] }\n): ColumnDef[];\n```\n\nGenerates columns with appropriate formatters for each field type: dates, money, booleans, enums, FK references, masked values, and plain text. Respects view field projections when provided.\n\n## Record\n\n### RecordDetail\n\nGrouped field display for a single record. Auto-groups fields by category (Identity, Contact, Financial, References, Settings, Dates, Audit).\n\n```typescript\ninterface RecordDetailProps {\n table: TableMeta;\n record: Record;\n role: Role;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (columns, masking, validation) |\n| `record` | The record data to display |\n| `role` | Current user role (affects masking) |\n\n### FieldDisplay\n\nRenders a single field value with appropriate formatting: masking, booleans, enums, FK links, dates, money, percentages, and numbers.\n\n```typescript\ninterface FieldDisplayProps {\n column: ColumnMeta;\n value: unknown;\n role: Role;\n masking?: Record<string, MaskingRule>;\n validation?: Record<string, ValidationRule>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `column` | Column metadata (type, mode, name) |\n| `value` | The raw value to display |\n| `role` | Current role (for masking checks) |\n| `masking` | Masking rules for the table |\n| `validation` | Validation rules (used for enum detection) |\n\n### ActionBar\n\nCard displaying available actions as buttons for the current record.\n\n```typescript\ninterface ActionBarProps {\n table: TableMeta;\n record: Record;\n onAction: (action: ActionMeta) => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata |\n| `record` | Current record (used for access condition evaluation) |\n| `onAction` | Handler when an action button is clicked |\n\n### RelatedRecords\n\nCard showing incoming FK relationships with record counts. Lists tables that reference the current record.\n\n```typescript\ninterface RelatedRecordsProps {\n table: TableMeta;\n recordId: string;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (used to discover incoming FK relationships) |\n| `recordId` | Current record ID (used to count related records) |\n\n## Form\n\n### AutoForm\n\nAuto-generated create/edit form built from the table's guard configuration.\n\n```typescript\ninterface AutoFormProps {\n table: TableMeta;\n mode: \"create\" | \"edit\";\n initialData?: Record;\n onSubmit: (data: Record) => Promise<void>;\n onCancel: () => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `table` | Table metadata (guards, columns, validation) |\n| `mode` | `\"create\"` uses createable fields, `\"edit\"` uses updatable fields |\n| `initialData` | Pre-filled values for edit mode |\n| `onSubmit` | Handler for form submission |\n| `onCancel` | Handler for cancel button |\n\nFeatures:\n\n- Fields determined from guards (createable for create, updatable for edit)\n- Immutable fields shown as disabled with lock icon\n- Protected fields shown as disabled with \"Updated via actions only\" note\n- Client-side validation from schema rules\n- Boolean fields grouped in a \"Settings\" section\n- Required fields marked with red asterisk\n\n### FieldInput\n\nSingle form input that adapts to the column type and validation rules.\n\n```typescript\ninterface FieldInputProps {\n column: ColumnMeta;\n validation?: ValidationRule;\n value: unknown;\n onChange: (value: unknown) => void;\n error?: string;\n disabled?: boolean;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `column` | Column metadata (determines input type) |\n| `validation` | Validation rules (enum values, min/max, email) |\n| `value` | Current field value |\n| `onChange` | Handler for value changes |\n| `error` | Error message to display |\n| `disabled` | Whether the input is disabled |\n\nRenders as: text input, number input, email input, URL input, date picker, select dropdown (for enums), textarea (for long text), or checkbox (for booleans).\n\n## Actions\n\n### ActionDialog\n\nModal dialog for executing a custom action with auto-generated input fields.\n\n```typescript\ninterface ActionDialogProps {\n action: ActionMeta;\n record: Record;\n tableName: string;\n onClose: () => void;\n onExecute: (input: Record) => Promise<void>;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `action` | Action metadata (name, description, inputFields, sideEffects) |\n| `record` | The record the action applies to |\n| `tableName` | Table name (for context) |\n| `onClose` | Handler to close the dialog |\n| `onExecute` | Handler to execute the action with form data |\n\nFeatures:\n\n- Auto-generates input fields from action schema\n- Destructive actions get red styling and warning icon\n- File response actions get download icon\n- Side effects warning banner for `sideEffects: \"sync\"`\n- Loading state during execution\n- Error display on failure\n\n## Pages\n\n### PageRenderer\n\nTop-level component that receives a `PageMeta` object and delegates to the appropriate layout component.\n\n```typescript\ninterface PageRendererProps {\n page: PageMeta;\n}\n```\n\nCurrently supports the `split-panel` layout type. Falls back to an error message for unknown layout types.\n\n### SplitPanelLayout\n\nRenders a two-panel layout with drag-and-drop support (via `@dnd-kit/core`), matching engine integration, and page action dialogs.\n\n```typescript\ninterface SplitPanelLayoutProps {\n page: PageMeta;\n}\n```\n\n| Behavior | Description |\n|----------|-------------|\n| Panel rendering | Renders left and right `DataPanel` components side by side |\n| Drag-and-drop | Enables DnD between panels based on panel `features` |\n| Match scoring | Computes match suggestions using `computeMatches()` and passes scores to panels |\n| Action trigger | Opens `PageActionDialog` when a record is dragged from one panel to another |\n| Refresh | Refreshes both panels after a successful action |\n\n### DataPanel\n\nA single panel within a page layout. Fetches data from the API, displays rows with column headers, and supports search.\n\n```typescript\ninterface DataPanelProps {\n panel: PagePanel;\n dataSource: PageDataSource;\n matchScores?: Map<string, number>;\n onDataLoaded?: (records: Record_[]) => void;\n refreshKey?: number;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `panel` | Panel metadata (id, title, position, features) |\n| `dataSource` | Data source config (table, filters, sort, display columns) |\n| `matchScores` | Map of record ID to best match score (for confidence badges) |\n| `onDataLoaded` | Callback when records are fetched (used by parent for match computation) |\n| `refreshKey` | Incrementing key to trigger a re-fetch |\n\n### PanelRow\n\nA single row within a `DataPanel`. Integrates with `@dnd-kit` for drag-source and drop-target behavior.\n\n```typescript\ninterface PanelRowProps {\n record: Record_;\n columns: string[];\n panelId: string;\n features?: string[];\n matchScore?: number;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `record` | The record data for this row |\n| `columns` | Column names to display |\n| `panelId` | Parent panel ID (used for DnD context) |\n| `features` | Panel features (`\"drag-source\"`, `\"drop-target\"`) |\n| `matchScore` | Match confidence score (renders `ConfidenceBadge` when present) |\n\n### PageActionDialog\n\nModal dialog triggered by drag-and-drop. Resolves input mappings from source and target records and executes a page action.\n\n```typescript\ninterface PageActionDialogProps {\n pageAction: PageAction;\n sourceRecord: Record_;\n targetRecord: Record_;\n sourceDataSource: string;\n targetDataSource: string;\n onClose: () => void;\n onSuccess: () => void;\n}\n```\n\n| Prop | Description |\n|------|-------------|\n| `pageAction` | The page action definition (table, action, inputMapping, label, icon, confirm) |\n| `sourceRecord` | The dragged record |\n| `targetRecord` | The drop-target record |\n| `sourceDataSource` | Data source name for the source record |\n| `targetDataSource` | Data source name for the target record |\n| `onClose` | Close handler |\n| `onSuccess` | Called after successful action execution (triggers panel refresh) |\n\n### ConfidenceBadge\n\nDisplays a match confidence score as a colored percentage badge.\n\n```typescript\ninterface ConfidenceBadgeProps {\n score: number; // 0-1\n}\n```\n\n| Score Range | Color |\n|-------------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n### computeMatches (utility)\n\nNot a component — a utility function that runs the matching engine. Compares left and right record arrays using the page's matching rules and returns sorted match suggestions.\n\n```typescript\nfunction computeMatches(\n leftRecords: Record_[],\n rightRecords: Record_[],\n page: PageMeta\n): MatchSuggestion[];\n\ninterface MatchSuggestion {\n leftId: string;\n rightId: string;\n score: number;\n ruleScores: { rule: string; score: number }[];\n}\n```\n\nReturns an array of suggestions sorted by score (highest first). Only includes matches above the page's `confidenceThreshold`.\n\n## Next Steps\n\n- **[Schema Format Reference](/stack/cms/schema-format)** — TypeScript types consumed by these components\n- **[Table Views](/stack/cms/table-views)** — How DataTable and SpreadsheetTable are used\n- **[Inline Editing](/stack/cms/inline-editing)** — SpreadsheetTable editing details"
|
|
383
363
|
},
|
|
384
|
-
"stack/
|
|
385
|
-
"title": "
|
|
386
|
-
"content": "
|
|
364
|
+
"stack/cms/connecting": {
|
|
365
|
+
"title": "Connecting",
|
|
366
|
+
"content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for non-admins.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view` CRUD** is gated on `userRole: [\"admin\"]` rather than org membership, so saved views can't be listed or modified without admin rights.\n- **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource CRUD endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `crud.access.roles` you defined.\n\nTo allow any authenticated user to access the CMS, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.\n\n## Multi-Tenant vs Single-Tenant\n\nThe CMS supports two authentication modes depending on your project's organization configuration.\n\n### Multi-Tenant (Default)\n\nIn multi-tenant mode, the CMS gates access behind organization membership:\n\n1. User logs in via Better Auth session\n2. CMS fetches the user's organization memberships\n3. If the user belongs to multiple organizations, an **org selector** is displayed\n4. Once an org is selected, the user's role within that org determines their CMS permissions\n\nThis is the default behavior for all Quickback projects.\n\n### Single-Tenant Mode\n\nWhen your project disables organizations (`features.organizations: false` in config), the compiler sets `singleTenant: true` in the schema registry. In this mode:\n\n- No org gate or org selector is shown\n- The user's role is read directly from `user.role` on the session\n- All data is unscoped (no `organizationId` filtering)\n\nSingle-tenant mode is useful for internal tools, personal projects, or apps that don't need multi-org isolation.\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Security](/stack/cms/security)** — How roles, guards, and masking work in the CMS"
|
|
387
367
|
},
|
|
388
|
-
"stack/
|
|
389
|
-
"title": "
|
|
390
|
-
"content": "
|
|
368
|
+
"stack/cms/dashboard": {
|
|
369
|
+
"title": "Dashboard",
|
|
370
|
+
"content": "# Dashboard\n\nThe CMS dashboard is the home page you see when opening the admin interface. It provides an at-a-glance overview of your entire schema and quick navigation to any table.\n\n## Stats Grid\n\nThe top of the dashboard displays aggregate statistics across your entire schema:\n\n| Stat | Description |\n|------|-------------|\n| **Tables** | Total non-internal tables (excludes join tables and system tables) |\n| **Columns** | Total columns across all tables |\n| **Actions** | Total custom actions across all tables |\n| **Views** | Total named views across all tables |\n| **Masked Fields** | Total fields with masking rules |\n\n## Feature Cards\n\nBelow the stats grid, the dashboard displays a card for each feature group. Each card lists the feature's tables with metadata:\n\n- **Column count** — number of columns in the table\n- **Action count** — number of custom actions (shown with a lightning icon)\n- **View count** — number of named views (shown with an eye icon)\n- **Mask count** — number of masked fields (shown with a shield icon)\n\nClicking a table name navigates directly to that table's browse view.\n\n## Role Context\n\nThe dashboard shows the current user's role. In demo mode, this reflects the role selected in the role switcher. In live mode, it shows the role from the authenticated session.\n\n## Internal Tables\n\nTables marked as `internal: true` in the schema registry (those without a `defineTable()` resource config) are excluded from the dashboard. These are typically join tables or system tables that don't need direct admin access.\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/stack/cms/pages)** — Multi-panel pages with matching and drag-drop"
|
|
371
|
+
},
|
|
372
|
+
"stack/cms": {
|
|
373
|
+
"title": "Quickback CMS",
|
|
374
|
+
"content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (admin-only by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for non-admins.\n2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"admin\"` and returns `403` otherwise.\n4. **`custom_view` CRUD** — the CMS-internal saved-views table is gated on `userRole: [\"admin\"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.\n\nYour resource CRUD endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `crud.access.roles` you defined.\n\nTo allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\n### Optional: Skip SPA rebuild\n\nAfter the first compile, you can skip rebuilding the CMS SPA on subsequent compiles:\n\n```typescript\ncms: { build: false }\n```\n\nThis is useful when you're iterating on API features and don't need to rebuild the CMS UI each time — it saves significant compile time. Set `build: true` (or omit it) when you need to update the CMS assets.\n\n### Optional: Custom output directory\n\n```typescript\ncms: { outputDir: \"my-custom-path/cms\" }\n```\n\nThis changes where the compiled CMS assets are placed (relative to project root), instead of the default `src/apps/cms/`.\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — Understand the JSON format the compiler generates\n- **[Connecting](/stack/cms/connecting)** — Demo mode, live mode, CLI command, and auth modes\n- **[Dashboard](/stack/cms/dashboard)** — Stats grid and feature navigation\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/stack/cms/pages)** — Split-panel layouts, matching engine, and drag-drop\n- **[Inline Editing](/stack/cms/inline-editing)** — Spreadsheet-style editing and FK typeahead\n- **[Security](/stack/cms/security)** — How the CMS enforces all four security layers\n- **[Actions](/stack/cms/actions)** — Custom actions with input forms, access filtering, and CMS metadata\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types for schema-registry.json\n- **[Components Reference](/stack/cms/components)** — All CMS components and their props"
|
|
375
|
+
},
|
|
376
|
+
"stack/cms/inline-editing": {
|
|
377
|
+
"title": "Inline Editing",
|
|
378
|
+
"content": "# Inline Editing\n\nThe CMS provides spreadsheet-style inline editing in Data Table mode, plus auto-generated create and edit forms in the record detail view. All editable fields are determined from your table's guard configuration.\n\n## Spreadsheet Editing\n\nIn Data Table mode, every editable cell becomes an inline editor. Select a cell, start typing, and the value is saved automatically when you move to another cell or press Enter.\n\n### Editable Fields\n\nThe CMS determines which fields are editable from the table's guards:\n\n- **`guards.updatable`** fields are editable in existing records\n- **`guards.createable`** fields are editable in new record forms\n- **`guards.immutable`** fields are locked after creation (shown as disabled in edit mode)\n- **`guards.protected`** fields can only be changed via actions (marked \"Updated via actions only\")\n\nIf a table has no explicit guard config, the CMS falls back to making all non-system columns editable (excluding `id`, audit fields, `organizationId`, and `deletedAt`).\n\n## Cell Types\n\nEach column type gets a specialized editor:\n\n### Text\n\nStandard text input. Type freely and press Enter or Tab to save.\n\n### Number\n\nNumeric input with step controls. Supports decimal values (step `0.01` for currency fields). The CMS detects money fields from column names containing `amount`, `total`, `price`, `cost`, `balance`, `rate`, etc.\n\n### Boolean\n\nA Yes/No dropdown. Click to toggle between the two values.\n\n### FK Typeahead\n\nForeign key columns (ending in `Id`) get a typeahead dropdown with server-side search:\n\n- **Debounced search** — Queries are debounced at 200ms to avoid flooding the API\n- **Server-side filtering** — Sends `?search=query&pageSize=20` to the FK target table's list endpoint\n- **Keyboard navigation** — Arrow keys to navigate options, Enter to select, Escape to close\n- **Auto-loads initial options** — Opens with the first 20 records sorted by display column\n- **Display labels** — Shows the target table's display column value (e.g., \"John Smith\" instead of `usr_abc123`)\n\nThe FK target table is derived by stripping the `Id` suffix from the column name. For example, `contactId` searches the `contact` table, and `accountCodeId` searches the `accountCode` table.\n\n### Enum / Select\n\nColumns with `validation.enum` render as a select dropdown with all allowed values.\n\n## Display Labels\n\nFK cells in the table view show human-readable names instead of raw IDs. The API enriches list responses with `_label` fields:\n\n```\ncontactId: \"cnt_abc123\" → displays \"Acme Corporation\"\nprojectId: \"prj_xyz789\" → displays \"Beach House Renovation\"\n```\n\nThe label comes from the referenced table's display column (auto-detected from `name`, `title`, `code`, etc.). This works in both Table mode and Data Table mode.\n\n## Keyboard Shortcuts\n\n| Shortcut | Action |\n|----------|--------|\n| Arrow keys | Navigate between cells |\n| Tab | Move to next editable cell |\n| Shift + Tab | Move to previous editable cell |\n| Enter | Start editing / confirm edit and move down |\n| Escape | Cancel current edit / deselect cell |\n| Type any character | Start editing the selected cell |\n\n### Navigation Flow\n\n1. **Select** a cell by clicking or using arrow keys\n2. **Edit** by pressing Enter, Tab, or just typing\n3. **Save** by pressing Enter (moves down), Tab (moves right to next editable), or clicking elsewhere\n4. **Cancel** by pressing Escape (reverts to previous value)\n\nWhen you press Tab, the cursor skips non-editable cells and jumps to the next editable cell in the row. At the end of a row, it wraps to the first editable cell of the next row.\n\n## Record Detail View\n\nClicking a row in Table mode navigates to the record detail view. Fields are automatically grouped by type:\n\n| Group | Fields Included |\n|-------|----------------|\n| Identity | `name`, `code`, `status`, `title`, `companyName`, fields ending in `Type` or `Status` |\n| Contact Info | `email`, `phone`, `mobile`, `website`, `address1`, `address2`, `city`, `state`, `zip`, `country` |\n| Financial | Money fields, fields with `Percent`, `Rate`, `Markup`, `Discount`, `Currency`, `exchange` |\n| References | All FK columns (ending in `Id`, excluding `id` and `organizationId`) |\n| Settings | Boolean fields |\n| Dates | Date/time fields |\n| Audit | `createdAt`, `createdBy`, `modifiedAt`, `modifiedBy` |\n| Other | Remaining ungrouped fields |\n\nEach group is rendered as a card with the group label as a header. Fields display formatted values — dates are localized, money shows currency formatting, booleans render as Yes/No badges, enums use color-coded pills, and FK references are clickable links to the target record.\n\n## Auto-Generated Forms\n\nThe CMS generates create and edit forms from the table's guard configuration:\n\n### Create Form\n\nShows all fields listed in `guards.createable`. Required fields (notNull without a default) are marked with a red asterisk. Validation rules from the schema (min/max length, enum constraints, email format) are enforced client-side.\n\n### Edit Form\n\nShows all fields listed in `guards.updatable`. Additionally:\n\n- **Immutable fields** appear as disabled inputs with a lock icon\n- **Protected fields** appear as disabled inputs with the note \"Updated via actions only\"\n- **Validation** is applied on submit, with error messages shown per field\n\n### Field Input Types\n\nThe auto-form selects the appropriate input control based on column type and validation:\n\n| Detection | Input Type |\n|-----------|-----------|\n| `mode: \"boolean\"` | Checkbox |\n| `validation.enum` present | Select dropdown |\n| Column name matches date pattern | Date/time picker |\n| Column name matches money pattern | Number input (step 0.01) |\n| Column name matches URL pattern | URL input |\n| `validation.email: true` | Email input |\n| `type: \"integer\"` or `type: \"real\"` | Number input |\n| Long text (description, notes) | Textarea |\n| Default | Text input |\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse mode and view projections\n- **[Security](/stack/cms/security)** — How guards control editability\n- **[Actions](/stack/cms/actions)** — Trigger actions from the detail view"
|
|
379
|
+
},
|
|
380
|
+
"stack/cms/pages": {
|
|
381
|
+
"title": "Custom Pages",
|
|
382
|
+
"content": "# Custom Pages\n\nCustom pages extend the CMS beyond standard table views. Define split-panel layouts, matching rules for record reconciliation, drag-and-drop interactions, and page-level actions — all from a single `definePage()` call.\n\n## Defining a Page\n\nPages are defined in your feature directory under a `pages/` folder:\n\n```\nquickback/definitions/features/\n banking/\n bank-accounts.ts # One table per file — any filename\n bank-transactions.ts\n actions.ts\n pages/\n bank-reconciliation.ts\n```\n\nEach page file exports a `definePage()` call:\n\n```typescript title=\"features/banking/pages/bank-reconciliation.ts\"\n\nexport default definePage({\n slug: 'bank-reconciliation',\n title: 'Bank Reconciliation',\n description: 'Match bank transactions to ledger entries',\n icon: 'landmark',\n feature: 'banking',\n\n access: { roles: ['owner', 'admin'] },\n\n dataSources: {\n bankTransactions: {\n table: 'bankTransaction',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n ledgerEntries: {\n table: 'ledgerEntry',\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'memo', 'amount'],\n },\n },\n\n layout: {\n type: 'split-panel',\n panels: [\n {\n id: 'bank',\n title: 'Bank Transactions',\n dataSource: 'bankTransactions',\n position: 'left',\n features: ['drag-source'],\n },\n {\n id: 'ledger',\n title: 'Ledger Entries',\n dataSource: 'ledgerEntries',\n position: 'right',\n features: ['drop-target'],\n },\n ],\n },\n\n matching: {\n enabled: true,\n confidenceThreshold: 0.5,\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5,\n condition: {\n left: 'bankTransactions.amount',\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n {\n name: 'Date Proximity',\n weight: 0.3,\n condition: {\n left: 'bankTransactions.date',\n right: 'ledgerEntries.date',\n operator: 'within-days',\n value: 7,\n },\n },\n {\n name: 'Description Match',\n weight: 0.2,\n condition: {\n left: 'bankTransactions.description',\n right: 'ledgerEntries.memo',\n operator: 'fuzzy-match',\n },\n },\n ],\n },\n\n pageActions: {\n reconcile: {\n table: 'bankTransaction',\n action: 'reconcile',\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this bank transaction to the selected ledger entry?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n },\n});\n```\n\n## Data Sources\n\nEach page declares one or more named data sources that bind to tables in your schema:\n\n```typescript\ndataSources: {\n bankTransactions: {\n table: 'bankTransaction', // Table name from your schema\n defaultFilters: { status: 'pending' }, // Applied on load\n defaultSort: { field: 'date', order: 'desc' },\n displayColumns: ['date', 'description', 'amount'],\n },\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `table` | `string` | Table name to query (required) |\n| `defaultFilters` | `Record<string, unknown>` | Filters applied on initial load |\n| `defaultSort` | `{ field, order }` | Default sort column and direction |\n| `displayColumns` | `string[]` | Columns shown in the panel (defaults to `[\"id\"]`) |\n\n## Layout\n\nPages use a layout configuration to arrange panels. Currently the only layout type is `split-panel`:\n\n```typescript\nlayout: {\n type: 'split-panel',\n panels: [\n { id: 'bank', title: 'Bank Txs', dataSource: 'bankTransactions', position: 'left', features: ['drag-source'] },\n { id: 'ledger', title: 'Ledger', dataSource: 'ledgerEntries', position: 'right', features: ['drop-target'] },\n ],\n}\n```\n\n### Panel Features\n\nPanels can enable interactive features:\n\n| Feature | Description |\n|---------|-------------|\n| `drag-source` | Rows in this panel can be dragged |\n| `drop-target` | Rows in this panel accept drops |\n\nWhen a row is dragged from one panel and dropped onto a row in the other panel, the first page action is triggered with both records as context.\n\n## Matching Engine\n\nThe matching engine compares records across two panels and computes confidence scores for potential matches. Matched rows display a colored confidence badge.\n\n### Rules\n\nEach rule defines a comparison between fields from two data sources:\n\n```typescript\nmatching: {\n enabled: true,\n confidenceThreshold: 0.5, // Minimum score to show (0-1)\n rules: [\n {\n name: 'Amount Match',\n weight: 0.5, // Weight in final score (0-1)\n condition: {\n left: 'bankTransactions.amount', // dataSourceName.fieldName\n right: 'ledgerEntries.amount',\n operator: 'abs-equals',\n },\n },\n ],\n}\n```\n\n### Operators\n\n| Operator | Description | Returns |\n|----------|-------------|---------|\n| `abs-equals` | Absolute values are equal | `1.0` if match, `0` otherwise |\n| `within-days` | Dates are within N days | `1 - (daysDiff / maxDays)`, clamped to 0 |\n| `fuzzy-match` | Word overlap between strings | Overlap ratio (0-1) |\n\nThe `within-days` operator uses the `value` parameter to set the maximum number of days (defaults to 7).\n\n### Confidence Scoring\n\nThe final confidence score is the weighted average of all rule scores:\n\n```\nscore = sum(ruleScore * ruleWeight) / sum(ruleWeights)\n```\n\nOnly matches above `confidenceThreshold` are shown. Confidence badges are color-coded:\n\n| Score | Color |\n|-------|-------|\n| 80%+ | Green |\n| 50-79% | Yellow |\n| Below 50% | Orange |\n\n## Page Actions\n\nPage actions trigger table actions using data from both the source (dragged) and target (dropped-on) records:\n\n```typescript\npageActions: {\n reconcile: {\n table: 'bankTransaction', // Target table for the action\n action: 'reconcile', // Action name on that table\n label: 'Reconcile',\n icon: 'check-circle',\n confirm: 'Match this transaction?',\n inputMapping: {\n transactionId: 'bankTransactions.$id',\n ledgerEntryId: 'ledgerEntries.$id',\n amount: 'bankTransactions.$amount',\n },\n },\n}\n```\n\n### Input Mapping\n\nInput mapping resolves field references from the source and target records into the action's input fields. The format is `\"dataSourceName.$fieldName\"`:\n\n- `bankTransactions.$id` — resolves to the `id` field of the dragged record from the `bankTransactions` data source\n- `ledgerEntries.$amount` — resolves to the `amount` field of the drop-target record from the `ledgerEntries` data source\n\nThe `$` prefix denotes a field reference on the record. The data source name determines which record (source or target) to read from.\n\n## Access Control\n\nRestrict page access by role:\n\n```typescript\naccess: { roles: ['owner', 'admin'] }\n```\n\nWhen set, only users with the specified roles can view the page. The page link is hidden from the sidebar for unauthorized users.\n\n## Sidebar Navigation\n\nCustom pages appear in the CMS sidebar under their feature group. Each page is listed alongside the feature's tables, making them easily discoverable.\n\n## Validation\n\nThe compiler validates page definitions at compile time:\n\n- `slug` must start with a lowercase letter and contain only lowercase letters, digits, and hyphens\n- At least one data source is required\n- Every panel's `dataSource` must reference a declared data source\n- Matching rule weights must be between 0 and 1\n- `confidenceThreshold` must be between 0 and 1\n\n## Next Steps\n\n- **[Dashboard](/stack/cms/dashboard)** — The CMS home page with schema stats\n- **[Components Reference](/stack/cms/components)** — Page-related component details\n- **[Schema Format Reference](/stack/cms/schema-format)** — PageMeta type definition"
|
|
383
|
+
},
|
|
384
|
+
"stack/cms/record-layouts": {
|
|
385
|
+
"title": "Record Layouts",
|
|
386
|
+
"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](/stack/cms/table-views)** — Column projections for list views\n- **[Schema Format](/stack/cms/schema-format)** — Full TypeScript type reference\n- **[Database Schema](/compiler/definitions/schema)** — defineTable() configuration reference"
|
|
387
|
+
},
|
|
388
|
+
"stack/cms/schema-format": {
|
|
389
|
+
"title": "Schema Format Reference",
|
|
390
|
+
"content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n singleTenant?: boolean;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Per-operation (create, read, update, delete) access config |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions for this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, successMessage, onSuccess, order) |\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/stack/cms/components)** — All CMS React components"
|
|
391
|
+
},
|
|
392
|
+
"stack/cms/schema-registry": {
|
|
393
|
+
"title": "Schema Registry",
|
|
394
|
+
"content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"singleTenant\": false,\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `singleTenant` | `boolean?` | When `true`, no organization layer |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; // Per-operation access rules\n guards: {\n createable: string[]; // Fields allowed on create\n updatable: string[]; // Fields allowed on update\n immutable: string[]; // Fields locked after creation\n protected: Record<string, string[]>; // Fields only updatable via actions\n };\n masking: Record<string, MaskingRule>; // Per-field masking rules\n views: Record<string, ViewConfig>; // Named column projections\n validation: Record<string, ValidationRule>; // Per-field validation\n actions: ActionMeta[]; // Available actions for this table\n displayColumn?: string; // Human-readable label column\n internal?: boolean; // Hidden from CMS sidebar when true\n}\n```\n\n## ColumnMeta\n\nEach column in the `columns` array:\n\n```typescript\ninterface ColumnMeta {\n name: string; // Property name (camelCase)\n dbName: string; // SQL column name (snake_case)\n type: \"text\" | \"integer\" | \"real\" | \"blob\"; // SQLite type\n mode?: \"boolean\"; // When an integer represents a boolean\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string; // Target table name for FK columns\n}\n```\n\nThe compiler automatically includes the system columns (`id`, `organizationId`), the audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`), and the soft-delete pair (`deletedAt`, `deletedBy` — when soft delete is enabled) at the beginning of every table's column list.\n\n### fkTarget — FK Resolution\n\nColumns ending in `Id` may have a `fkTarget` property indicating which table they reference. This is resolved in priority order:\n\n1. **Explicit `references`** — from your `defineTable()` config (highest priority)\n2. **Drizzle `.references()`** — parsed from schema source code\n3. **Convention** — strip `Id` suffix, match table name directly\n\n```json\n{\n \"name\": \"vendorId\",\n \"type\": \"text\",\n \"fkTarget\": \"contact\"\n}\n```\n\nThe CMS uses `fkTarget` to render typeahead/lookup inputs that search the correct table instead of showing raw IDs.\n\n## Input Hints\n\nTables with `inputHints` configured in `defineTable()` include an `inputHints` map in their metadata:\n\n```json\n{\n \"name\": \"invoice\",\n \"inputHints\": {\n \"status\": \"select\",\n \"sortOrder\": \"radio\",\n \"isPartialPaymentDisabled\": \"checkbox\",\n \"headerMessage\": \"textarea\",\n \"description\": \"richtext\"\n }\n}\n```\n\nThe CMS reads these hints to render the appropriate form control for each field. The `\"richtext\"` hint renders a tiptap editor in edit mode and formatted HTML in view mode. See [Input Hints](/compiler/definitions/schema#input-hints) for the full list of supported values.\n\n## Display Column\n\nThe `displayColumn` field tells the CMS which column to use as a human-readable label for a record. This is used in:\n\n- FK typeahead dropdowns (showing names instead of IDs)\n- Record titles in detail views\n- Breadcrumb labels\n\n### Auto-Detection\n\nIf you don't explicitly set `displayColumn` in your resource config, the compiler auto-detects it by scanning column names in priority order:\n\n1. `name`\n2. `title`\n3. `label`\n4. `headline`\n5. `subject`\n6. `code`\n7. `displayName`\n8. `fullName`\n9. `description`\n\nThe first match wins. If no candidate matches, the table has no display column and the CMS falls back to showing IDs.\n\n### Explicit Config\n\nSet it explicitly in your table definition:\n\n```typescript\nexport default defineTable(contacts, {\n displayColumn: \"companyName\",\n // ...\n});\n```\n\n## FK Label Resolution\n\nWhen a table has foreign key columns (ending in `Id`), the API enriches list responses with `_label` fields. For example, a `roomTypeId` column gets a corresponding `roomType_label` field containing the display column value from the referenced table.\n\nThe CMS uses these `_label` fields to show human-readable names in table cells and FK typeahead dropdowns instead of raw UUIDs.\n\n```\nroomTypeId: \"rt_abc123\" → displayed as \"Master Bedroom\"\naccountCodeId: \"ac_xyz789\" → displayed as \"4100 - Revenue\"\n```\n\nThe FK target table is resolved from the `fkTarget` property on each column. For simple cases like `roomTypeId` → `roomType`, the compiler auto-detects it. For non-obvious mappings (e.g., `vendorId` → `contact`), use explicit [`references`](/compiler/definitions/schema#references) in your `defineTable()` config.\n\n## Pages\n\nWhen features include `definePage()` files (in `features/{name}/pages/`), the compiler includes them in the registry under two fields:\n\n- **`pages`** — Map of page slug to full `PageMeta` object (data sources, layout, matching rules, page actions)\n- **`pagesByFeature`** — Map of feature name to array of page slugs belonging to that feature\n\nThe CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/stack/cms/pages) for the full `definePage()` API.\n\n## Single-Tenant Mode\n\nWhen `singleTenant` is `true` in the registry (set when the project config has `features.organizations: false`), the CMS skips the organization gate and reads the user's role directly from `user.role` on the session instead of from organization membership.\n\n## Next Steps\n\n- **[Connecting](/stack/cms/connecting)** — Demo mode vs. live mode setup\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types"
|
|
395
|
+
},
|
|
396
|
+
"stack/cms/security": {
|
|
397
|
+
"title": "Security",
|
|
398
|
+
"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## CMS Access (admin-only by default)\n\nThe CMS is restricted to Better Auth platform admins (`user.role === \"admin\"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach 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 redirects the user to `/account/profile`.\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](/stack/cms/actions)** — Action dialogs and input forms\n- **[Table Views](/stack/cms/table-views)** — View projections and toolbar\n- **[Inline Editing](/stack/cms/inline-editing)** — How guards affect editability"
|
|
399
|
+
},
|
|
400
|
+
"stack/cms/table-views": {
|
|
401
|
+
"title": "Table Views",
|
|
402
|
+
"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](/stack/cms/inline-editing)** — Deep dive into spreadsheet editing, FK typeahead, and keyboard shortcuts\n- **[Security](/stack/cms/security)** — How roles and guards affect the table UI\n- **[Actions](/stack/cms/actions)** — Custom actions in the row menu and detail view"
|
|
391
403
|
},
|
|
392
404
|
"stack": {
|
|
393
405
|
"title": "Quickback Stack",
|
|
394
|
-
"content": "Quickback Stack is the
|
|
406
|
+
"content": "**Quickback Stack** is the runtime services that surround your compiled API. While the [Quickback Compiler](/compiler) generates your routes and security policies, the Stack is everything else you need to ship a real application — auth, storage, realtime, queues, an admin UI, an account UI — all on your own Cloudflare account.\n\n## What you get\n\n| Component | Service | Purpose |\n|-----------|---------|---------|\n| [Auth](/stack/auth) | Better Auth | Email/OTP, passkeys, organizations, admin |\n| [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |\n| [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |\n| [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |\n| [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |\n| [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |\n| [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |\n| [Account UI](/stack/account-ui) | Embedded SPA | Login, profile, orgs, admin |\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Cloudflare Edge │\n├─────────────────────────────────────────────────────────────┤\n│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │\n│ │ Workers │ │ Durable │ │ KV │ │\n│ │ (API/CMS) │ │ Objects │ │ (Cache) │ │\n│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │\n│ │ │ │ │\n│ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │\n│ │ D1 │ │ Realtime │ │ R2 │ │\n│ │ (or Neon) │ │ (WebSocket)│ │ (Storage) │ │\n│ └─────────────┘ └─────────────┘ └─────────────┘ │\n│ │\n│ ┌─────────────┐ ┌─────────────────────────────────┐ │\n│ │ Queues │ │ Better Auth │ │\n│ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │\n│ └─────────────┘ └─────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Your account, your data\n\nEverything in Quickback Stack runs on your own Cloudflare account:\n\n- **Workers** — your deployments, your logs\n- **Storage** — your KV namespaces, your R2 buckets\n- **Secrets** — your API keys, in your Wrangler secrets\n\nQuickback provides the architecture and the code generation. You own the infrastructure.\n\n## Quick start\n\n```bash\nnpm install -g wrangler @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\nquickback compile\nwrangler deploy\n```\n\n## See also\n\n- [Quickback Compiler](/compiler) — the build tool that generates your API\n- [Quickback for Hono API](/compiler/targets/hono-api) — what the compiler outputs\n- [Definitions](/compiler/definitions) — the security model the Stack runs"
|
|
395
407
|
},
|
|
396
408
|
"stack/queues/handlers": {
|
|
397
409
|
"title": "Custom Queue Handlers",
|
|
@@ -435,7 +447,7 @@ export const DOCS = {
|
|
|
435
447
|
},
|
|
436
448
|
"stack/storage/using-r2": {
|
|
437
449
|
"title": "Using R2",
|
|
438
|
-
"content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\n## Upload Flow\n\nThe generated API provides a two-step upload process:\n\n1. **Request a presigned URL** — Client calls the upload endpoint to get a time-limited URL\n2. **Upload directly to R2** — Client uploads the file directly to R2 (bypasses your Worker)\n3. **Store the reference** — The API records the file metadata in D1\n\n```bash\n# 1. Request presigned upload URL\ncurl -X POST https://api.example.com/api/v1/files/upload \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"filename\": \"report.pdf\", \"contentType\": \"application/pdf\"}'\n\n# Response:\n# { \"uploadUrl\": \"https://bucket.r2.cloudflarestorage.com/...\", \"fileId\": \"file_abc123\" }\n\n# 2. Upload directly to R2 using the presigned URL\ncurl -X PUT \"<uploadUrl>\" \\\n -H \"Content-Type: application/pdf\" \\\n --data-binary @report.pdf\n```\n\n## Download Flow\n\nFiles are served through your Worker with security checks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/account-ui/features/avatars) — Avatar upload UI integration"
|
|
450
|
+
"content": "Cloudflare R2 provides S3-compatible object storage for file uploads in the Quickback Stack.\n\n## Upload Flow\n\nThe generated API provides a two-step upload process:\n\n1. **Request a presigned URL** — Client calls the upload endpoint to get a time-limited URL\n2. **Upload directly to R2** — Client uploads the file directly to R2 (bypasses your Worker)\n3. **Store the reference** — The API records the file metadata in D1\n\n```bash\n# 1. Request presigned upload URL\ncurl -X POST https://api.example.com/api/v1/files/upload \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"filename\": \"report.pdf\", \"contentType\": \"application/pdf\"}'\n\n# Response:\n# { \"uploadUrl\": \"https://bucket.r2.cloudflarestorage.com/...\", \"fileId\": \"file_abc123\" }\n\n# 2. Upload directly to R2 using the presigned URL\ncurl -X PUT \"<uploadUrl>\" \\\n -H \"Content-Type: application/pdf\" \\\n --data-binary @report.pdf\n```\n\n## Download Flow\n\nFiles are served through your Worker with security checks applied:\n\n```bash\n# Download a file (auth + firewall enforced)\ncurl https://api.example.com/api/v1/files/file_abc123/download \\\n -H \"Authorization: Bearer <token>\"\n```\n\nThe download endpoint:\n1. Validates the user's session\n2. Checks firewall — the file must belong to the user's organization\n3. Checks access — the user must have the required role\n4. Streams the file from R2\n\n## Role-Based Access\n\nFile access respects the same security layers as your API:\n\n- **Firewall** — Users can only access files belonging to their organization\n- **Access** — Role-based download permissions\n\n## See Also\n\n- [R2 Setup](/stack/storage/r2) — Bucket creation, wrangler bindings, and configuration\n- [Avatars](/stack/account-ui/features/avatars) — Avatar upload UI integration"
|
|
439
451
|
},
|
|
440
452
|
"stack/vector/embeddings": {
|
|
441
453
|
"title": "Automatic Embeddings",
|
|
@@ -463,35 +475,8 @@ export const DOCS = {
|
|
|
463
475
|
}
|
|
464
476
|
};
|
|
465
477
|
export const TOPIC_LIST = [
|
|
466
|
-
"account-ui/customization",
|
|
467
|
-
"account-ui/environment-variables",
|
|
468
|
-
"account-ui/features/admin",
|
|
469
|
-
"account-ui/features/api-keys",
|
|
470
|
-
"account-ui/features/avatars",
|
|
471
|
-
"account-ui/features/cli-authorize",
|
|
472
|
-
"account-ui/features",
|
|
473
|
-
"account-ui/features/organizations",
|
|
474
|
-
"account-ui/features/passkeys",
|
|
475
|
-
"account-ui/features/passwordless",
|
|
476
|
-
"account-ui/features/sessions",
|
|
477
|
-
"account-ui",
|
|
478
|
-
"account-ui/library-usage",
|
|
479
|
-
"account-ui/standalone",
|
|
480
|
-
"account-ui/with-quickback",
|
|
481
|
-
"account-ui/worker",
|
|
482
478
|
"changelog",
|
|
483
|
-
"
|
|
484
|
-
"cms/components",
|
|
485
|
-
"cms/connecting",
|
|
486
|
-
"cms/dashboard",
|
|
487
|
-
"cms",
|
|
488
|
-
"cms/inline-editing",
|
|
489
|
-
"cms/pages",
|
|
490
|
-
"cms/record-layouts",
|
|
491
|
-
"cms/schema-format",
|
|
492
|
-
"cms/schema-registry",
|
|
493
|
-
"cms/security",
|
|
494
|
-
"cms/table-views",
|
|
479
|
+
"compiler/claude-code-skill",
|
|
495
480
|
"compiler/cloud-compiler/authentication",
|
|
496
481
|
"compiler/cloud-compiler/cli",
|
|
497
482
|
"compiler/cloud-compiler/endpoints",
|
|
@@ -529,37 +514,67 @@ export const TOPIC_LIST = [
|
|
|
529
514
|
"compiler/getting-started/template-empty",
|
|
530
515
|
"compiler/getting-started/templates",
|
|
531
516
|
"compiler",
|
|
532
|
-
"compiler/
|
|
533
|
-
"compiler/
|
|
534
|
-
"compiler/
|
|
535
|
-
"compiler/
|
|
517
|
+
"compiler/targets/hono-api/cloudflare",
|
|
518
|
+
"compiler/targets/hono-api/database/d1",
|
|
519
|
+
"compiler/targets/hono-api/database",
|
|
520
|
+
"compiler/targets/hono-api/database/neon",
|
|
521
|
+
"compiler/targets/hono-api/database/using-d1",
|
|
522
|
+
"compiler/targets/hono-api",
|
|
523
|
+
"compiler/targets/hono-api/using-the-api/actions-api",
|
|
524
|
+
"compiler/targets/hono-api/using-the-api/batch-operations",
|
|
525
|
+
"compiler/targets/hono-api/using-the-api/caching",
|
|
526
|
+
"compiler/targets/hono-api/using-the-api/crud",
|
|
527
|
+
"compiler/targets/hono-api/using-the-api/errors",
|
|
528
|
+
"compiler/targets/hono-api/using-the-api",
|
|
529
|
+
"compiler/targets/hono-api/using-the-api/openapi",
|
|
530
|
+
"compiler/targets/hono-api/using-the-api/query-params",
|
|
531
|
+
"compiler/targets/hono-api/using-the-api/views-api",
|
|
532
|
+
"compiler/targets",
|
|
533
|
+
"compiler/targets/supabase-rls",
|
|
534
|
+
"compiler/targets/supabase-rls/limitations",
|
|
535
|
+
"compiler/targets/supabase-rls/mappings",
|
|
536
|
+
"compiler/targets/supabase-rls/setup",
|
|
536
537
|
"compiler/troubleshooting",
|
|
537
|
-
"compiler/using-the-api/actions-api",
|
|
538
|
-
"compiler/using-the-api/batch-operations",
|
|
539
|
-
"compiler/using-the-api/caching",
|
|
540
|
-
"compiler/using-the-api/crud",
|
|
541
|
-
"compiler/using-the-api/errors",
|
|
542
|
-
"compiler/using-the-api",
|
|
543
|
-
"compiler/using-the-api/openapi",
|
|
544
|
-
"compiler/using-the-api/query-params",
|
|
545
|
-
"compiler/using-the-api/views-api",
|
|
546
538
|
"index",
|
|
547
|
-
"
|
|
548
|
-
"
|
|
549
|
-
"
|
|
550
|
-
"
|
|
551
|
-
"
|
|
539
|
+
"stack/account-ui/customization",
|
|
540
|
+
"stack/account-ui/environment-variables",
|
|
541
|
+
"stack/account-ui/features/admin",
|
|
542
|
+
"stack/account-ui/features/api-keys",
|
|
543
|
+
"stack/account-ui/features/avatars",
|
|
544
|
+
"stack/account-ui/features/cli-authorize",
|
|
545
|
+
"stack/account-ui/features",
|
|
546
|
+
"stack/account-ui/features/organizations",
|
|
547
|
+
"stack/account-ui/features/passkeys",
|
|
548
|
+
"stack/account-ui/features/passwordless",
|
|
549
|
+
"stack/account-ui/features/sessions",
|
|
550
|
+
"stack/account-ui/hooks",
|
|
551
|
+
"stack/account-ui",
|
|
552
|
+
"stack/account-ui/library-usage",
|
|
553
|
+
"stack/account-ui/standalone",
|
|
554
|
+
"stack/account-ui/with-quickback",
|
|
555
|
+
"stack/account-ui/worker",
|
|
552
556
|
"stack/auth/api-keys",
|
|
553
557
|
"stack/auth/device-auth",
|
|
554
558
|
"stack/auth",
|
|
555
559
|
"stack/auth/jwt-optimization",
|
|
560
|
+
"stack/auth/plugins/aws-ses",
|
|
561
|
+
"stack/auth/plugins/combo-auth",
|
|
556
562
|
"stack/auth/plugins",
|
|
563
|
+
"stack/auth/plugins/upgrade-anonymous",
|
|
557
564
|
"stack/auth/security",
|
|
558
565
|
"stack/auth/using-auth",
|
|
559
|
-
"stack/
|
|
560
|
-
"stack/
|
|
561
|
-
"stack/
|
|
562
|
-
"stack/
|
|
566
|
+
"stack/cms/actions",
|
|
567
|
+
"stack/cms/components",
|
|
568
|
+
"stack/cms/connecting",
|
|
569
|
+
"stack/cms/dashboard",
|
|
570
|
+
"stack/cms",
|
|
571
|
+
"stack/cms/inline-editing",
|
|
572
|
+
"stack/cms/pages",
|
|
573
|
+
"stack/cms/record-layouts",
|
|
574
|
+
"stack/cms/schema-format",
|
|
575
|
+
"stack/cms/schema-registry",
|
|
576
|
+
"stack/cms/security",
|
|
577
|
+
"stack/cms/table-views",
|
|
563
578
|
"stack",
|
|
564
579
|
"stack/queues/handlers",
|
|
565
580
|
"stack/queues",
|