Crap CMS
Crap CMS is a headless content management system built in Rust. It combines a compiled core with Lua hooks (neovim-style) and an overridable HTMX admin UI.
Motivation
I built several Rust/WebAssembly frontend projects and couldn’t find a CMS that fit the stack. So I built one.
The idea: a simple CMS written in Rust, extensible via a lightweight scripting language, with no complicated build steps or infrastructure requirements.
Inspiration came from what I consider the best solutions out there:
- Lua scripting API — modeled after Neovim and Awesome WM, where Lua gives users deep control without touching core code
- Configuration & hook system — inspired by Payload CMS, an excellent and highly recommended CMS for anyone needing a production-ready solution
- CLI tooling — influenced by Laravel’s comprehensive Artisan CLI
- SQLite + WAL + FTS — sufficient for most of my use cases, and it bundles cleanly into a single binary with zero external dependencies. The database layer is abstracted behind a trait, so alternative relational backends could be added in the future if the need arises
- Pure JavaScript with JSDoc types — no TypeScript, no bundler, no build step. Type safety through JSDoc annotations, checkable with
tsc --checkJswithout compiling anything - HTMX + Web Components — easy to theme (similar to WordPress child themes), no frontend build step. Web Components are a native browser standard — no framework updates, no outdated dependencies, no breaking changes
- gRPC API — binary protocol with streaming support, ideal for service-to-service communication. And because I wanted it. A separate REST proxy is available for those who prefer plain JSON over HTTP
The project is functional but not yet production-ready — it still needs to prove itself.
Warning: While in alpha (0.x), breaking changes may appear without prior notice.
Design Philosophy
- Lua is the single source of truth for schemas. Collections and fields are defined in Lua files, not in the database. The database stores content, not structure.
- Single binary. The admin UI (Axum) and gRPC API (Tonic) run in one process on two ports.
- Config directory pattern. All customization lives in one directory, auto-detected from CWD (or set explicitly with
--config/-C). - No JS build step. The admin UI uses Handlebars templates + HTMX with plain CSS.
- Hooks are the extension system. Lua hooks at three levels (field, collection, global) provide full lifecycle control with transaction-safe CRUD access.
Feature Set
- Collections with 20 field types (text, number, textarea, richtext, select, radio, checkbox, date, email, json, code, relationship, array, group, upload, blocks, row, collapsible, tabs, join)
- Globals — single-document collections for site-wide settings
- Hooks — field-level, collection-level, and globally registered lifecycle hooks
- Access Control — collection-level and field-level, with filter constraint support
- Authentication — JWT sessions, password login, custom auth strategies, email verification, password reset
- Uploads — file uploads with automatic image resizing and format conversion (WebP, AVIF)
- Relationships — has-one and has-many with configurable population depth
- Localization — per-field opt-in localization with locale-suffixed columns
- Versions & Drafts — document version history with draft/publish workflow
- Live Updates — real-time mutation events via SSE and gRPC streaming
- Admin UI — template overlay system, theme switching, Web Components
- gRPC API — full CRUD with filtering, pagination, and server reflection
- CLI Tooling — interactive scaffolding wizard, blueprints, data export/import, backups
Tech Stack
| Component | Technology |
|---|---|
| Language | Rust (edition 2024) |
| Web framework | Axum |
| gRPC | Tonic + Prost |
| Database | SQLite via rusqlite, r2d2 pool, WAL mode |
| Templates | Handlebars + HTMX |
| Hooks | Lua 5.4 via mlua |
| IDs | nanoid |
Installation
Quick Install (Linux)
curl -fsSL https://raw.githubusercontent.com/dkluhzeb/crap-cms/main/scripts/install.sh | bash
The installer auto-detects your architecture (x86_64 or aarch64), downloads the matching release, verifies its SHA256, and lays out a version store under ~/.local/share/crap-cms/:
~/.local/share/crap-cms/
├── versions/
│ └── v0.1.0-alpha.5/crap-cms
└── current -> versions/v0.1.0-alpha.5/crap-cms
~/.local/bin/crap-cms -> ~/.local/share/crap-cms/current
After install, make sure ~/.local/bin is on your PATH — the installer prints the exact export PATH=… line to add to ~/.bashrc / ~/.zshrc if it isn’t.
Verify before running
If you don’t want to pipe straight into bash:
curl -fsSL https://raw.githubusercontent.com/dkluhzeb/crap-cms/main/scripts/install.sh -o install.sh
less install.sh # audit the script
sha256sum install.sh # compare against scripts/install.sh in the repo
bash install.sh # run once satisfied
Pin to a specific tag for a reproducible install:
curl -fsSL https://raw.githubusercontent.com/dkluhzeb/crap-cms/v0.1.0-alpha.5/scripts/install.sh | bash
Override the locations via environment variables:
XDG_DATA_HOME=/opt/crap-cms BIN_DIR=/usr/local/bin \
curl -fsSL https://raw.githubusercontent.com/dkluhzeb/crap-cms/main/scripts/install.sh | bash
Managing Versions
Once the binary is installed via the script, crap-cms update acts as a built-in version manager — similar to rustup or nvm:
| Command | What it does |
|---|---|
crap-cms update check | Compare the running version to the latest GitHub release. Exit 0 if up-to-date, 1 otherwise. Caches the result for 24h. |
crap-cms update list | List all remote release tags. Installed versions are marked (installed); the active one is marked *. |
crap-cms update install <version> | Download + verify + stage a specific version in the store (does not switch). |
crap-cms update use <version> | Switch the current symlink to an installed version. Atomic. |
crap-cms update uninstall <version> | Remove an installed version. Refuses the active one. |
crap-cms update where | Print the resolved path of the currently active binary. |
crap-cms update | Install latest + switch to it. Prompts for confirmation (skip with -y). |
On crap-cms serve startup, a one-line notice prints when a newer release is in the cache. Silence it via crap.toml:
[update]
check_on_startup = false
Distro-managed installs refuse self-update. If the running binary lives under /usr/, /opt/, or /nix/, crap-cms update refuses with a message telling you to update via your package manager. Use --force to bypass.
Windows. crap-cms update install / use / the bare crap-cms update are not supported on Windows yet — the version-store layout uses symlinks, which require Developer Mode or admin privileges on Windows. The read-only subcommands (check, list, where) still work. Windows users should download crap-cms-windows-x86_64.exe manually from the releases page and replace their binary to upgrade.
Direct Download
Prefer to install manually? Grab a binary straight from GitHub Releases. No runtime dependencies:
curl -L -o crap-cms \
https://github.com/dkluhzeb/crap-cms/releases/latest/download/crap-cms-linux-x86_64
chmod +x crap-cms
sudo mv crap-cms /usr/local/bin/
Available binaries:
| File | Platform |
|---|---|
crap-cms-linux-x86_64 | Linux x86_64 (musl, fully static) |
crap-cms-linux-aarch64 | Linux ARM64 (musl, fully static) |
crap-cms-windows-x86_64.exe | Windows x86_64 |
Binaries installed to /usr/local/bin this way cannot be self-updated via crap-cms update (same rule as distro packages). Use the quick installer if you want version management.
Docker
docker run -p 3000:3000 -p 50051:50051 \
ghcr.io/dkluhzeb/crap-cms:latest serve -C /example
Images are Alpine-based (~30 MB) and published to ghcr.io/dkluhzeb/crap-cms. See the README for production usage and available tags.
Building from Source
Requires a Rust toolchain (edition 2024) via rustup and a C compiler:
git clone https://github.com/dkluhzeb/crap-cms.git
cd crap-cms
cargo build --release
The binary is at target/release/crap-cms. SQLite and Lua are bundled — no system libraries needed.
Optional Tools
- grpcurl — for testing the gRPC API from the command line. See grpcurl installation.
- lua-language-server (LuaLS) — for IDE autocompletion in Lua config files. The project provides type definitions in
types/crap.lua.
Quick Start
1. Scaffold a new project
The fastest way to get started is the interactive init wizard:
crap-cms init ./my-project
The wizard walks you through:
- Admin port (default: 3000)
- gRPC port (default: 50051)
- Localization — enable and choose locales (e.g.,
en,de,fr) - Auth collection — creates a
userscollection with email/password login - First admin user — prompts for email and password right away
- Upload collection — creates a
mediacollection for file/image uploads - Additional collections — keep adding as many as you need
A JWT auth secret is auto-generated and written to crap.toml so tokens survive restarts.
When it finishes you’ll have a ready-to-run config directory:
my-project/
├── crap.toml
├── init.lua
├── .luarc.json
├── .gitignore
├── stylua.toml
├── collections/
│ ├── users.lua
│ └── media.lua
├── globals/
├── hooks/
├── access/
├── jobs/
├── plugins/
├── migrations/
├── templates/
├── static/
├── types/
│ └── crap.lua
├── data/
└── uploads/
2. Start the server
cd my-project
crap-cms serve
This starts:
- Admin UI at http://localhost:3000/admin
- gRPC API at
localhost:50051
3. Log in to the admin UI
Visit http://localhost:3000/admin/login and sign in with the credentials you created during init.
If you skipped user creation during init, bootstrap one now:
# Interactive (prompts for password)
crap-cms user create -e admin@example.com
# Non-interactive
crap-cms user create \
-e admin@example.com \
-p secret123 \
-f role=admin \
-f name="Admin User"
4. Create content via gRPC
Use grpcurl to interact with the API. The server supports reflection, so no proto import is needed:
# List all posts
grpcurl -plaintext localhost:50051 crap.ContentAPI/Find \
-d '{"collection": "posts"}'
# Create a post
grpcurl -plaintext localhost:50051 crap.ContentAPI/Create \
-d '{
"collection": "posts",
"data": {
"title": "Hello World",
"slug": "hello-world",
"status": "draft",
"content": "My first post."
}
}'
Alternative: Run with the example config
The repository includes an example/ config directory with sample collections, useful if you’re building from source:
git clone https://github.com/dkluhzeb/crap-cms.git
cd crap-cms
cargo build --release
./target/release/crap-cms serve -C ./example
Then bootstrap an admin user:
crap-cms user create -C ./example -e admin@example.com
Config Directory
All customization lives in a single config directory. When you run CLI commands from inside this directory (or a subdirectory), the config is auto-detected by walking up and looking for crap.toml. You can also set it explicitly with --config/-C or the CRAP_CONFIG_DIR environment variable.
Directory Structure
my-project/
├── crap.toml # Server/database/auth configuration
├── init.lua # Runs at startup (register global hooks, etc.)
├── .luarc.json # LuaLS config for IDE support
├── .gitignore # Ignores data/, uploads/, types/ by default
├── stylua.toml # StyLua formatter config for Lua files
├── collections/ # One .lua file per collection
│ ├── posts.lua
│ ├── users.lua
│ └── media.lua
├── globals/ # One .lua file per global
│ └── site_settings.lua
├── hooks/ # Lua modules referenced by hook strings
│ ├── posts.lua
│ └── access.lua
├── access/ # Reusable access-control Lua modules
├── jobs/ # Job handler Lua modules (see `jobs` feature)
├── plugins/ # Plugin Lua modules (see `plugins` feature)
├── migrations/ # Custom SQL migrations (see `migrate` command)
├── templates/ # Handlebars overrides for admin UI
│ └── fields/
│ └── custom.hbs
├── translations/ # (optional, user-created) Admin UI translation overrides (JSON per locale)
│ └── de.json
├── static/ # Static file overrides (CSS, JS, fonts)
├── data/ # Runtime data (auto-created)
│ ├── crap.db # SQLite database
│ ├── crap.pid # Process ID file (when running with --detach)
│ └── logs/ # Rotating log files (when [logging] file = true)
├── uploads/ # Uploaded files (auto-created per collection)
│ └── media/
└── types/ # Auto-generated type definitions (see `typegen`)
├── crap.lua # API surface (crap.* functions, hook context, …)
├── hooks.lua # Per-collection hook types (data, doc, filters)
├── client.<ext> # Per-collection types for API clients (ts, go, py, rs)
└── proto.rs # (optional) `From<proto::Document>` impls for Rust gRPC
The access/, jobs/, plugins/, migrations/, templates/, and static/ directories are created empty by crap-cms init — populate them as needed. The translations/ directory is not scaffolded; create it yourself when you want to override admin UI strings (see Localization).
File Loading Order
crap.tomlis loaded first (or defaults are used if absent)collections/*.luafiles are loaded alphabeticallyglobals/*.luafiles are loaded alphabeticallyinit.luais executed last
Lua Package Path
The config directory is prepended to Lua’s package.path:
<config_dir>/?.lua;<config_dir>/?/init.lua;...
This means require("hooks.posts") resolves to <config_dir>/hooks/posts.lua.
LuaLS Support
Create a .luarc.json in your config directory for IDE autocompletion:
{
"runtime": { "version": "Lua 5.4" },
"workspace": { "library": ["./types"] }
}
Generate the server-side Lua type definitions with:
crap-cms typegen lua
This writes two files: types/crap.lua (the crap.* API surface) and types/hooks.lua (per-collection hook/data/doc shapes derived from your field definitions). Under admin.dev_mode = true, crap-cms serve regenerates them on every startup so they stay in sync while you iterate.
External API consumers (TypeScript, Go, Python, Rust) get their own per-collection types via:
crap-cms typegen client -l ts # types/client.ts
crap-cms typegen client -l ts,go,py # multiple languages in one pass
See typegen for the full subcommand reference.
crap.toml
The crap.toml file configures the server, database, authentication, and other global settings. All sections and fields are optional — sensible defaults are used when omitted.
If no crap.toml file exists in the config directory, all defaults are used. An empty file is also valid — all defaults apply.
Top-Level Fields
| Field | Type | Default | Description |
|---|---|---|---|
crap_version | string | — | Expected CMS version. If set, a warning is logged on startup when the running binary doesn’t match. Supports exact ("0.1.0") or prefix ("0.1") matching. |
Environment Variable Substitution
String values in crap.toml can reference environment variables using ${VAR} syntax:
[auth]
secret = "${JWT_SECRET}"
[database]
path = "${DB_PATH:-data/crap.db}"
[email]
smtp_pass = "${SMTP_PASSWORD}"
${VAR}— replaced with the value ofVAR. Startup fails ifVARis not set.${VAR:-default}— replaced withVARif set and non-empty, otherwise usesdefault.
Substitution only applies to string values — ${VAR} patterns in comments are safely ignored.
This allows keeping secrets out of config files and varying configuration across environments.
Duration Values
Most time-related fields accept an integer (seconds), a human-readable string with a suffix, or a bare number string:
# These are all equivalent:
token_expiry = 7200
token_expiry = "7200"
token_expiry = "2h"
# Supported suffixes: s (seconds), m (minutes), h (hours), d (days)
poll_interval = "5s"
login_lockout_seconds = "5m"
auto_purge = "7d"
Fields that support this: token_expiry, login_lockout_seconds, reset_token_expiry, forgot_password_window_seconds, max_age, poll_interval, cron_interval, heartbeat_interval, auto_purge, grpc_rate_limit_window, connection_timeout, smtp_timeout, busy_timeout, request_timeout, grpc_timeout.
File Size Values
File size fields accept both an integer (bytes) and a human-readable string:
# These are equivalent:
max_file_size = 52428800
max_file_size = "50MB"
# Supported suffixes (case-insensitive, 1024-based):
# B (bytes), KB (kilobytes), MB (megabytes), GB (gigabytes)
max_file_size = "500B"
max_file_size = "100KB"
max_file_size = "1GB"
Fields that support this: max_file_size (global and per-collection), max_memory, http_max_response_bytes, grpc_max_message_size.
Configuration Validation
crap.toml is validated at startup. Fatal validation errors prevent the server from starting with a descriptive error message. Non-fatal issues log warnings.
Fatal errors:
database.pool_max_size = 0database.connection_timeout = 0hooks.vm_pool_size = 0server.admin_portorserver.grpc_portis0server.admin_port == server.grpc_port(ports must be distinct)auth.password_policy.min_length > auth.password_policy.max_length
Warnings (server starts but logs a warning):
jobs.max_concurrent = 0— no jobs will executeauth.secretis set but shorter than 32 charactersdepth.max_depth = 0— all population requests capped to 0
Full Reference
# Optional: warn if the running binary doesn't match this version
# crap_version = "0.1.0"
[server]
admin_port = 3000 # Admin UI port
grpc_port = 50051 # gRPC API port
host = "0.0.0.0" # Bind address
# public_url = "https://cms.example.com" # Public-facing base URL for generated links
# h2c = false # Enable HTTP/2 cleartext (for reverse proxies)
# trust_proxy = false # Trust X-Forwarded-For (enable behind reverse proxy)
# compression = "off" # "off" (default), "gzip", "br", "all"
# grpc_reflection = false # Enable gRPC server reflection (default: false)
# grpc_rate_limit_requests = 0 # Per-IP request limit (0 = disabled, recommended: 100)
# grpc_rate_limit_window = 60 # Sliding window in seconds (or "1m")
# grpc_max_message_size = "16MB" # Max gRPC message size (default 16MB)
# request_timeout = "30s" # Admin HTTP request timeout (none by default)
# grpc_timeout = "30s" # gRPC request timeout (none by default)
[database]
path = "data/crap.db" # Relative to config dir, or absolute
pool_max_size = 64 # Max connections in the pool
busy_timeout = "30s" # SQLite busy timeout (integer ms or "30s", "1m")
connection_timeout = 30 # Pool checkout timeout (seconds or "30s")
cache_size = -16384 # Page cache in KB (negative = KB; default 16MB)
mmap_size = 268435456 # Memory-mapped I/O in bytes (default 256MB, 0 = off)
wal_autocheckpoint = 1000 # WAL auto-checkpoint threshold in pages
[admin]
dev_mode = false # Reload templates per-request (enable in development)
require_auth = true # Block admin when no auth collection exists (default: true)
# access = "access.admin_panel" # Lua function: which users can access the admin UI
# [admin.csp] # Content-Security-Policy (enabled by default)
# enabled = true
# script_src = ["'self'", "'unsafe-inline'", "https://unpkg.com"]
# style_src = ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"]
# font_src = ["'self'", "https://fonts.gstatic.com"]
# img_src = ["'self'", "data:"]
# connect_src = ["'self'"]
# frame_ancestors = ["'none'"]
# form_action = ["'self'"]
# base_uri = ["'self'"]
[auth]
secret = "" # JWT signing key. Empty = auto-generated and persisted to data/.jwt_secret
token_expiry = "2h" # Default token expiry (accepts integer seconds or "2h", "30m", etc.)
max_login_attempts = 5 # Failed attempts per email before temporary lockout
max_ip_login_attempts = 20 # Failed attempts per IP before lockout (higher for shared IPs)
login_lockout_seconds = "5m" # Lockout duration after max attempts
reset_token_expiry = "1h" # Password reset token expiry
max_forgot_password_attempts = 3 # Forgot-password requests per email before rate limiting
forgot_password_window_seconds = "15m" # Rate limit window for forgot-password
[auth.password_policy]
min_length = 8 # Minimum password length
max_length = 128 # Maximum password length (DoS protection)
# require_uppercase = false # Require at least one uppercase letter
# require_lowercase = false # Require at least one lowercase letter
# require_digit = false # Require at least one digit
# require_special = false # Require at least one special character
[depth]
default_depth = 1 # Default population depth for FindByID (Find always defaults to 0)
max_depth = 10 # Hard cap on population depth (prevents abuse)
[cache]
backend = "memory" # Cache backend: "memory" (default), "redis", "none", "custom"
# max_entries = 10000 # Soft cap for memory backend (default: 10000)
# max_age_secs = 0 # Periodic full clear interval (0 = disabled)
# redis_url = "redis://127.0.0.1:6379" # Redis connection URL
# prefix = "crap:" # Key prefix for Redis backend
[pagination]
default_limit = 20 # Default limit for Find queries (when none is specified)
max_limit = 1000 # Hard cap on limit — requests above this are clamped
# mode = "page" # "page" (offset) or "cursor" (keyset)
[upload]
storage = "local" # Storage backend: "local" (default), "s3", or "custom"
max_file_size = "50MB" # Global max file size (accepts bytes or "50MB", "1GB", etc.)
# [upload.s3] # S3-compatible storage (requires --features s3-storage)
# bucket = "my-uploads"
# region = "us-east-1"
# endpoint = "" # custom endpoint for MinIO, R2, etc.
# access_key = "${AWS_ACCESS_KEY}"
# secret_key = "${AWS_SECRET_KEY}"
# prefix = "" # optional key prefix
# public_url_base = "" # CDN URL base (empty = S3 URLs)
# path_style = false # true for MinIO
[email]
provider = "smtp" # "smtp" (default), "webhook", "log", or "custom"
smtp_host = "" # SMTP server hostname. Empty = falls back to log provider
smtp_port = 587 # SMTP port (587 for STARTTLS, 465 for TLS, 25/1025 for plain)
smtp_user = "" # SMTP username
smtp_pass = "" # SMTP password
smtp_tls = "starttls" # "starttls" (default), "tls" (implicit TLS), "none" (plain/test)
from_address = "noreply@example.com" # Sender email address
from_name = "Crap CMS" # Sender display name
# smtp_timeout = 30 # SMTP connection/send timeout in seconds (or "30s")
# webhook_url = "" # URL for webhook provider (POST JSON)
# webhook_headers = { Authorization = "Bearer ${API_KEY}" } # Extra headers for webhook
[hooks]
on_init = [] # Lua function refs to run at startup (with CRUD access)
# max_depth = 3 # Max hook recursion depth (0 = no hooks from Lua CRUD)
vm_pool_size = 8 # Number of Lua VMs for concurrent hook execution
# Default: number of CPU cores (fallback: 4)
max_instructions = 10000000 # Max Lua instructions per hook (0 = unlimited)
max_memory = "50MB" # Max Lua memory per VM (0 = unlimited)
allow_private_networks = false # Block HTTP requests to private/loopback IPs
http_max_response_bytes = "10MB" # Max HTTP response body size
[live]
enabled = true # Enable SSE + gRPC Subscribe for live mutation events
default_mode = "metadata" # Default event delivery mode: "metadata" or "full"
transport = "memory" # Event transport: "memory" (default, in-process) or "redis" (cross-node fanout)
channel_capacity = 1024 # Broadcast channel buffer size
# max_sse_connections = 1000 # Max concurrent SSE connections (0 = unlimited)
# max_subscribe_connections = 1000 # Max concurrent gRPC Subscribe streams (0 = unlimited)
# subscriber_send_timeout_ms = 1000 # Drop subscribers whose outbound send exceeds this (ms)
[locale]
default_locale = "en" # Default locale code
locales = ["en", "de"] # Supported locales (empty = disabled)
fallback = true # Fall back to default locale if field is NULL
[jobs]
max_concurrent = 10 # Cluster-wide cap on concurrent jobs (counted via DB)
poll_interval = "1s" # How often to poll for pending jobs
cron_interval = "1m" # How often to check cron schedules
heartbeat_interval = "10s" # How often running jobs update their heartbeat
auto_purge = "7d" # Auto-purge completed/failed runs older than this
priority_decay = 0 # Priority aging ("1m", "30s", "1h"); 0 = disabled
[jobs.queues]
# Per-queue scheduling knobs: { concurrency, timeout, retries }. All
# concurrency caps are cluster-wide (counted from the shared DB).
# Composition: strictest of max_concurrent / queue cap / per-slug
# JobDefinition.concurrency wins. `timeout` and `retries` apply to
# system jobs (_system_image_convert, _system_email) — user Lua jobs
# use their JobDefinition values.
#
# Framework defaults applied by `apply_queue_defaults`:
# images = { concurrency = 2, timeout = "5m", retries = 2 }
# email = { concurrency = 5, timeout = "30s", retries = 3 }
images = { concurrency = 2 } # keeps framework timeout + retries
# email = { concurrency = 8, timeout = "1m", retries = 5 }
# reports = { concurrency = 1 }
[access]
default_deny = true # When true (default), deny all operations without explicit access functions
[cors]
allowed_origins = [] # Origins allowed for CORS. Empty = CORS disabled (default)
# Use ["*"] to allow any origin
allowed_methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
allowed_headers = ["Content-Type", "Authorization"]
exposed_headers = [] # Response headers exposed to the browser
max_age = "1h" # How long browsers cache preflight results
allow_credentials = false # Allow cookies/Authorization. Cannot use with ["*"] origins
[mcp]
# enabled = false # Enable MCP server
# http = false # Mount POST /mcp on admin server
# config_tools = false # Enable config read/write tools
# api_key = "" # API key for HTTP transport
# include_collections = [] # Only expose these collections
# exclude_collections = [] # Hide these collections
Section Details
[server]
| Field | Type | Default | Description |
|---|---|---|---|
admin_port | integer | 3000 | Port for the Axum admin UI |
grpc_port | integer | 50051 | Port for the Tonic gRPC API |
host | string | "0.0.0.0" | Bind address for both servers |
h2c | boolean | false | Enable HTTP/2 cleartext (h2c). Allows reverse proxies (Caddy, nginx) to speak HTTP/2 to the backend without TLS. Browsers that don’t support h2c fall back to HTTP/1.1 on the same port. |
trust_proxy | boolean | false | Trust the X-Forwarded-For header for client IP extraction on the admin HTTP server. Enable when running behind a reverse proxy (nginx, Caddy, etc.) so per-IP rate limiting uses the real client IP. When false (default), the TCP socket address is used and XFF is ignored — preventing IP spoofing when exposed directly to the internet. Does not affect the gRPC server, which always uses the TCP peer address from Tonic’s remote_addr(). |
compression | string | "off" | Response compression. "off" = disabled (default), "gzip" = gzip only, "br" = brotli only, "all" = gzip + brotli. Most deployments use a reverse proxy (nginx/caddy) for compression, so this is opt-in. |
grpc_reflection | boolean | false | Enable gRPC server reflection. Allows clients (e.g., grpcurl, Postman) to discover services and methods without a .proto file. Disabled by default to hide the API surface from unauthenticated probing. |
public_url | string | — | Public-facing base URL (e.g., "https://cms.example.com"). Used for password reset emails and other generated links. If not set, defaults to http://{host}:{admin_port}. |
grpc_rate_limit_requests | integer | 0 | Maximum number of gRPC requests per IP within the sliding window. 0 = disabled (default). Recommended to enable in production (e.g., 100). When enabled, requests exceeding the limit receive ResourceExhausted status. |
grpc_rate_limit_window | integer/string | 60 ("1m") | Sliding window duration for rate limiting. Accepts seconds (integer) or human-readable ("1m", "30s"). |
grpc_max_message_size | integer/string | 16777216 ("16MB") | Maximum gRPC message size in bytes (applies to both send and receive). Tonic’s built-in default is 4MB, which can be exceeded by large Find responses with deep population. Accepts bytes or file size string ("16MB", "32MB"). |
request_timeout | integer/string | — (none) | Admin HTTP request timeout. When set, requests exceeding this duration return 408 Request Timeout. SSE streams are exempt (handled by shutdown). Accepts seconds or human-readable ("30s", "5m"). |
grpc_timeout | integer/string | — (none) | gRPC request timeout. When set, RPCs exceeding this duration return DEADLINE_EXCEEDED. Applies to all RPCs including Subscribe streams. Accepts seconds or human-readable ("30s", "5m"). |
[database]
| Field | Type | Default | Description |
|---|---|---|---|
path | string | "data/crap.db" | SQLite database path. Relative paths are resolved from the config directory. Absolute paths are used as-is. |
pool_max_size | integer | 64 | Maximum number of connections in the SQLite connection pool. |
cache_size | integer | -16384 | SQLite page cache size. Negative = KB, positive = pages. Default 16MB. |
mmap_size | integer | 268435456 | SQLite memory-mapped I/O size in bytes. Default 256MB. Set to 0 to disable. |
wal_autocheckpoint | integer | 1000 | WAL auto-checkpoint threshold in pages. |
busy_timeout | duration | 30000 ("30s") | SQLite busy timeout in milliseconds. Controls how long a connection waits for locks before returning SQLITE_BUSY. Accepts integer ms or human-readable string ("30s", "1m"). |
connection_timeout | duration | 30 | Pool checkout timeout in seconds. How long pool.get() waits for a free connection before returning an error. Should be >= busy_timeout so SQLite’s WAL-writer retry loop resolves before the pool-level timeout fires. |
[admin]
| Field | Type | Default | Description |
|---|---|---|---|
dev_mode | boolean | false | When true, templates are reloaded from disk on every request. The scaffold sets this to true for new projects. Set to false in production for cached templates. |
require_auth | boolean | true | When true and no auth collection exists, the admin panel shows a “Setup Required” page (HTTP 503) instead of being open. Set to false for fully open dev mode without authentication. |
access | string | — | Lua function ref (e.g., "access.admin_panel") that gates admin panel access. Called after successful authentication with { user } context. Return true to allow, false/nil to deny (HTTP 403). |
default_timezone | string | "" | Default IANA timezone for date fields with timezone = true that don’t specify their own default_timezone. Pre-selects the timezone in the admin dropdown. Example: "America/New_York". |
csp | table | (see below) | Content-Security-Policy header configuration. See [admin.csp]. |
[admin.csp]
Content-Security-Policy header configuration for the admin UI. Each field is a list of CSP sources for the corresponding directive. Theme developers can extend these lists to allow external resources (CDNs, custom fonts, analytics, etc.).
| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable the CSP header. Set to false to disable entirely. |
default_src | string[] | ["'self'"] | Fallback for any directive not explicitly set. |
script_src | string[] | ["'self'", "'unsafe-inline'", "https://unpkg.com"] | Allowed script sources. Includes 'unsafe-inline' for theme bootstrap and CSRF injection scripts. |
style_src | string[] | ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"] | Allowed stylesheet sources. Includes 'unsafe-inline' for Web Component Shadow DOM styles. |
font_src | string[] | ["'self'", "https://fonts.gstatic.com"] | Allowed font sources. Includes Google Fonts for Material Symbols icons. |
img_src | string[] | ["'self'", "data:"] | Allowed image sources. Includes data: for inline SVGs. |
connect_src | string[] | ["'self'"] | Allowed targets for fetch, XHR, and WebSocket connections. |
frame_ancestors | string[] | ["'none'"] | Who can embed this page in a frame. 'none' prevents clickjacking. |
form_action | string[] | ["'self'"] | Allowed form submission targets. |
base_uri | string[] | ["'self'"] | Allowed URLs for <base> tags. |
Example: allowing a custom CDN and analytics:
[admin.csp]
script_src = ["'self'", "'unsafe-inline'", "https://unpkg.com", "https://cdn.example.com", "https://analytics.example.com"]
style_src = ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.example.com"]
font_src = ["'self'", "https://fonts.gstatic.com", "https://cdn.example.com"]
img_src = ["'self'", "data:", "https://cdn.example.com"]
connect_src = ["'self'", "https://analytics.example.com"]
[auth]
| Field | Type | Default | Description |
|---|---|---|---|
secret | string | "" (empty) | JWT signing secret. If empty, a random secret is auto-generated and persisted to data/.jwt_secret so tokens survive restarts. Set explicitly if you prefer to manage the secret yourself. |
token_expiry | integer/string | 7200 ("2h") | Default JWT token lifetime. Accepts seconds (integer) or human-readable ("2h", "30m"). Can be overridden per auth collection. |
max_login_attempts | integer | 5 | Maximum failed login attempts per email before temporary lockout. |
max_ip_login_attempts | integer | 20 | Maximum failed login attempts per IP before temporary lockout. Higher than per-email to tolerate shared IPs (offices, NAT). Also used as the per-IP threshold for forgot-password requests. |
login_lockout_seconds | integer/string | 300 ("5m") | Duration of lockout after max_login_attempts or max_ip_login_attempts is reached. Accepts seconds or human-readable. |
reset_token_expiry | integer/string | 3600 ("1h") | Password reset token expiry. The “Forgot password” email link expires after this duration. Accepts seconds or human-readable. |
max_forgot_password_attempts | integer | 3 | Maximum forgot-password requests per email address before rate limiting. Further requests silently return success without sending email. |
forgot_password_window_seconds | integer/string | 900 ("15m") | Rate limit window for forgot-password requests. Also used as the per-IP window for forgot-password rate limiting. Accepts seconds or human-readable. |
session_cookie_samesite | string | "lax" | SameSite attribute for the crap_session admin cookie. Accepts "lax" (default — cookie sent on top-level cross-site navigations, balanced CSRF protection), "strict" (cookie never sent on cross-site requests — breaks links from emails/external sites but hardens the admin against CSRF), or "none" (reserved; currently falls back to "lax" at runtime). |
[auth.password_policy]
Password strength requirements applied to all password-setting paths (create, update, reset, CLI).
| Field | Type | Default | Description |
|---|---|---|---|
min_length | integer | 8 | Minimum password length in Unicode characters (codepoints). Multi-byte characters (accented letters, CJK, emoji) each count as 1. Must be ≤ max_length or the server refuses to start. |
max_length | integer | 128 | Maximum password length in bytes. Prevents DoS via Argon2 on huge inputs. Uses byte count (not characters) to bound hashing cost. |
require_uppercase | boolean | false | Require at least one uppercase letter (A-Z). |
require_lowercase | boolean | false | Require at least one lowercase letter (a-z). |
require_digit | boolean | false | Require at least one digit (0-9). |
require_special | boolean | false | Require at least one special (non-alphanumeric) character. |
rate_limit_backend | string | "memory" | Rate limit storage backend: "memory" (default, per-server), "redis" (shared across servers, requires --features redis), "none" (disabled). |
rate_limit_redis_url | string | "" | Redis URL for rate limit backend. Falls back to cache.redis_url if empty. |
rate_limit_prefix | string | "crap:rl:" | Key prefix for Redis rate limit backend. |
[depth]
| Field | Type | Default | Description |
|---|---|---|---|
default_depth | integer | 1 | Default population depth for FindByID. Find always defaults to 0. |
max_depth | integer | 10 | Maximum allowed depth for any request. Hard cap to prevent excessive queries. |
[cache]
| Field | Type | Default | Description |
|---|---|---|---|
backend | string | "memory" | Cache backend: "memory" (in-memory DashMap), "redis" (shared, requires --features redis), "none" (disabled), or "custom" (Lua-delegated, planned). |
max_entries | integer | 10000 | Soft cap on entries for the memory backend. Once reached, new insertions are skipped until a clear. |
max_age_secs | integer | 0 | Periodic full cache clear interval in seconds. 0 = disabled (only write-through invalidation). Set > 0 to limit staleness when the database may be modified outside the API. |
redis_url | string | "redis://127.0.0.1:6379" | Redis connection URL. Only used when backend = "redis". |
prefix | string | "crap:" | Key prefix for the Redis backend. All keys are stored as {prefix}{key}. |
[pagination]
| Field | Type | Default | Description |
|---|---|---|---|
default_limit | integer | 20 | Default page size applied to Find queries when no limit is specified. |
max_limit | integer | 1000 | Hard cap on limit. Requests above this value are clamped to max_limit. |
mode | string | "page" | Pagination mode: "page" (offset-based with page/totalPages) or "cursor" (keyset-based with startCursor/endCursor). In cursor mode, pass after_cursor (forward) or before_cursor (backward) instead of page. |
[upload]
| Field | Type | Default | Description |
|---|---|---|---|
storage | string | "local" | Storage backend: "local" (filesystem), "s3" (S3-compatible, requires --features s3-storage), or "custom" (Lua-delegated). |
max_file_size | integer/string | 52428800 ("50MB") | Global maximum file size. Accepts bytes (integer) or human-readable ("50MB", "1GB"). Per-collection max_file_size overrides this. Also sets the HTTP body limit (with 1MB overhead for multipart encoding). |
[upload.s3]
S3-compatible storage configuration. Only used when storage = "s3".
| Field | Type | Default | Description |
|---|---|---|---|
bucket | string | (required) | S3 bucket name. |
region | string | "us-east-1" | AWS region. |
endpoint | string | (AWS default) | Custom endpoint URL for MinIO, R2, B2, etc. |
access_key | string | (required) | AWS access key ID. |
secret_key | string | (required) | AWS secret access key. |
prefix | string | "" | Optional key prefix prepended to all storage keys. |
public_url_base | string | "" | Base URL for public file links (e.g., CDN). Empty = S3 URLs. |
path_style | boolean | false | Use path-style addressing (required for MinIO). |
[email]
| Field | Type | Default | Description |
|---|---|---|---|
provider | string | "smtp" | Email provider: "smtp" (default), "webhook" (HTTP POST), "log" (dev mode), or "custom" (Lua). |
smtp_host | string | "" (empty) | SMTP server hostname. Empty with smtp provider = falls back to log provider. |
smtp_port | integer | 587 | SMTP port. 587 is the standard STARTTLS port. |
smtp_user | string | "" | SMTP authentication username. |
smtp_pass | string | "" | SMTP authentication password. |
smtp_tls | string | "starttls" | TLS mode: "starttls" (default, port 587), "tls" (implicit TLS, port 465), "none" (plain, for testing). |
from_address | string | "noreply@example.com" | Sender email address for outgoing mail. |
from_name | string | "Crap CMS" | Sender display name. |
smtp_timeout | integer/string | 30 | SMTP connection and send timeout in seconds. Accepts integer or duration string ("30s", "1m"). |
webhook_url | string | "" | URL for the webhook email provider. Receives POST with JSON body. |
webhook_headers | map | {} | Extra HTTP headers for webhook requests (e.g., { Authorization = "Bearer ..." }). |
Background email delivery (queue size, retry budget, per-attempt
timeout) is configured via [jobs.queues.email] —
same per-queue mechanism as image conversions. Framework defaults
match alpha.8 (retries = 3, timeout = "30s", concurrency = 5),
so operators who never touched these fields don’t need to migrate.
When configured, email enables password reset (“Forgot password?” link on login), email verification (optional per-collection), and the crap.email.send() Lua API. The log provider is useful for development — it logs email content to tracing without sending. The custom provider delegates to Lua via crap.email.register().
[hooks]
| Field | Type | Default | Description |
|---|---|---|---|
on_init | string[] | [] | Lua function refs to execute at startup. These run synchronously with CRUD access — failure aborts startup. |
max_depth | integer | 3 | Maximum hook recursion depth. When Lua CRUD in hooks triggers more hooks, this caps the chain. 0 = never run hooks from Lua CRUD. |
vm_pool_size | integer | CPU cores | Number of Lua VMs in the pool for concurrent hook execution. Default is the number of available CPU cores (fallback: 4 if detection fails). |
max_instructions | integer | 10000000 | Maximum Lua instructions per hook invocation. 0 = unlimited. |
max_memory | integer/string | 52428800 (50 MB) | Maximum Lua memory per VM in bytes. Accepts integer or filesize string ("50MB", "100MB"). 0 = unlimited. |
allow_private_networks | boolean | false | Allow crap.http.request to reach private/loopback/link-local IPs. |
http_max_response_bytes | integer/string | 10485760 (10 MB) | Maximum HTTP response body size. Accepts integer or filesize string ("10MB", "1GB"). |
[live]
| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable live event streaming (SSE + gRPC Subscribe). |
default_mode | string | "metadata" | Default event delivery mode. "metadata" sends only event type, collection, and document ID. "full" sends the complete document payload. |
transport | string | "memory" | Event transport. "memory" keeps events in-process (does not cross nodes). "redis" fans events out across all servers subscribed to the same Redis instance — requires the redis feature and reuses [cache] redis_url. |
channel_capacity | integer | 1024 | Internal broadcast channel buffer size. Increase if subscribers lag. |
max_sse_connections | integer | 1000 | Maximum concurrent SSE connections. When reached, new connections receive 503 Service Unavailable. 0 = unlimited. |
max_subscribe_connections | integer | 1000 | Maximum concurrent gRPC Subscribe streams. When reached, new subscriptions receive UNAVAILABLE status. 0 = unlimited. |
subscriber_send_timeout_ms | integer | 1000 | Per-subscriber outbound send timeout (ms). If forwarding an event to a specific live-update client (SSE or gRPC) takes longer than this, that subscriber is dropped to protect other subscribers from head-of-line blocking. |
See Live Updates for full documentation.
[locale]
| Field | Type | Default | Description |
|---|---|---|---|
default_locale | string | "en" | Default locale code. Content without an explicit locale uses this. |
locales | string[] | [] (empty) | Supported locale codes. Empty = localization disabled. When empty, all fields behave as before (single value, no locale columns). |
fallback | boolean | true | When reading a non-default locale, fall back to the default locale value if the requested locale field is NULL. Uses COALESCE in SQL. |
[jobs]
| Field | Type | Default | Description |
|---|---|---|---|
max_concurrent | integer | 10 | Maximum concurrent job executions across all queues. |
poll_interval | integer/string | 1 ("1s") | How often to poll for pending jobs. Accepts seconds or human-readable. |
cron_interval | integer/string | 60 ("1m") | How often to evaluate cron schedules. Accepts seconds or human-readable. |
heartbeat_interval | integer/string | 10 ("10s") | How often running jobs update their heartbeat. Used to detect stale jobs. Accepts seconds or human-readable. |
auto_purge | integer/string | "7d" | Auto-purge completed/failed runs older than this duration. Accepts seconds or human-readable ("7d", "24h", "30m", "3600"). Set to "" (empty string) to disable auto-purge. Absent = 7 days default. |
priority_decay | integer/string | 0 | Priority aging period: wait time required for a job’s effective scheduling priority to bump by +1. 0 disables decay (pure static priority DESC, created_at ASC ordering — index-friendly fast path). Positive durations ("1m", "30s", "1h") enable aging-based promotion so older lower-priority jobs eventually get claimed instead of starving forever. |
[jobs.queues]
Per-queue aggregate concurrency caps, keyed by queue name. Used to
throttle resource-shared work (a emails queue with a shared SMTP
pool, an images queue limited by CPU, …) independent of per-job
caps.
[jobs.queues]
emails = { concurrency = 4, timeout = "1m" }
images = { concurrency = 2 } # keeps framework timeout + retries defaults
reports = { concurrency = 1, timeout = "30m", retries = 0 }
| Field | Type | Default | Description |
|---|---|---|---|
concurrency | integer | 0 (unlimited) | Max concurrent runs across all slugs in this queue. 0 means no per-queue cap; only the global [jobs] max_concurrent and per-slug JobDefinition::concurrency apply. |
timeout | integer/string | unset (worker default) | Per-job wall-clock timeout for jobs in this queue. Applies to system jobs (_system_image_convert, _system_email) that don’t carry their own JobDefinition; user Lua jobs use the timeout declared on the JobDefinition itself. Accepts seconds or human-readable ("5m", "30s"). |
retries | integer | unset (worker default) | Default max_attempts for jobs in this queue, expressed as retries: total attempts = retries + 1. Used by system jobs AND by user Lua jobs that omit retries in crap.jobs.define. Explicit JobDefinition.retries (including retries = 0) overrides the queue default. crap.email.queue{ retries = N } overrides for that one call. |
Each field is independent — supplying only concurrency leaves the
framework’s timeout / retries defaults intact for that queue.
Framework-supplied defaults — the following queues get sensible defaults applied at config load time unless the operator explicitly sets them:
| Queue | Field | Default | Why |
|---|---|---|---|
images | concurrency | 2 | AVIF / WebP encoders are CPU-bound; cap to avoid pinning every core during an upload burst. |
images | timeout | "5m" | Large originals can spend minutes in libheif on slow disks; the worker’s hardcoded 120s was too tight for production-sized files. |
images | retries | 2 | Image jobs flake on transient I/O — total 3 attempts is the historic worker default and survives one storage hiccup with a retry to spare. |
email | concurrency | 5 | Bounded burst for shared SMTP pools; matches the historic [email] queue_concurrency default. |
email | timeout | "30s" | SMTP handshake + delivery; matches the historic [email] queue_timeout default. |
email | retries | 3 | Survives greylisting + brief outbound network blips; matches the historic [email] queue_retries default. |
Operator overrides win — partial overrides are merged field-by-field
([jobs.queues.images] concurrency = 4 keeps the framework’s
timeout and retries defaults).
Composition — when claiming a job, all of the following caps apply, strictest wins. All three caps are cluster-wide (counted from the shared DB):
[jobs] max_concurrent— total jobs in flight across the cluster[jobs.queues.<name>] concurrency— jobs in flight in that queueJobDefinition::concurrency— jobs in flight of that specific slug
Queues without an entry in [jobs.queues] are unconstrained beyond
the global cap. The scheduler warns at startup if [jobs.queues]
references a queue name that no defined job uses (catches typos).
See Multi-server semantics for how these caps interact when multiple servers share the same DB.
[access]
| Field | Type | Default | Description |
|---|---|---|---|
default_deny | boolean | true | When true (default), collections and globals without an explicit access function deny all operations. Set to false to allow all operations when no access function is defined. |
Enable this to enforce a “secure by default” posture — every collection must explicitly declare its access rules. Without it, collections without access functions are open to any authenticated (or anonymous) user.
[cors]
| Field | Type | Default | Description |
|---|---|---|---|
allowed_origins | string[] | [] (empty) | Origins allowed to make cross-origin requests. Empty = CORS disabled (no layer added, default). Use ["*"] to allow any origin. |
allowed_methods | string[] | ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] | HTTP methods allowed in CORS preflight. |
allowed_headers | string[] | ["Content-Type", "Authorization"] | Request headers allowed in CORS requests. |
exposed_headers | string[] | [] (empty) | Response headers the browser is allowed to access. |
max_age | integer/string | 3600 ("1h") | How long browsers may cache preflight results. Accepts seconds or human-readable. |
allow_credentials | boolean | false | Allow credentials (cookies, Authorization header). Cannot be used with allowed_origins = ["*"] — if both are set, credentials are ignored with a warning. |
When CORS is enabled, the layer is added to both the admin UI (Axum) and gRPC API (Tonic) servers. CORS runs before CSRF middleware, so preflight OPTIONS requests get CORS headers without triggering CSRF validation.
[mcp]
| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable the MCP (Model Context Protocol) server. Required for both stdio and HTTP transports. |
http | boolean | false | Mount POST /mcp on the admin server for HTTP-based MCP access. |
config_tools | boolean | false | Enable config generation tools (read_config_file, write_config_file, list_config_files). Opt-in because they allow filesystem writes. |
api_key | string | "" (empty) | API key for HTTP transport. Required when http = true — the server will refuse to start without one. Requests must include Authorization: Bearer <key>. |
include_collections | string[] | [] (empty) | Only expose these collections via MCP. Empty = all collections. Enforced at both tool listing and execution time. |
exclude_collections | string[] | [] (empty) | Hide these collections from MCP. Takes precedence over include_collections. Enforced at both tool listing and execution time. |
See MCP Overview for usage details.
[logging]
| Field | Type | Default | Description |
|---|---|---|---|
file | boolean | false | Enable file-based logging. When false (default), logs go to stdout only. Auto-enabled when running with --detach (where stdout is unavailable). |
path | string | "data/logs" | Log directory path. Relative paths are resolved from the config directory. Use an absolute path to log elsewhere. |
rotation | string | "daily" | Log rotation strategy: "daily" (one file per day), "hourly" (one file per hour), or "never" (single file, no rotation). |
max_files | integer | 30 | Maximum rotated log files to keep. Old files are pruned on startup. |
File logging writes to rotating files in the configured directory. Each project has its own log directory, so multiple instances on the same machine are naturally isolated.
Use crap-cms logs to view log output, crap-cms logs -f to follow in real time, and crap-cms logs clear to remove old rotated files. See the CLI Reference for details.
When locales are configured, any field with localized = true in its Lua definition gets one column per locale (title__en, title__de) instead of a single title column. The API accepts a locale parameter on Find, FindByID, Create, Update, GetGlobal, and UpdateGlobal to control which locale to read/write. The admin UI shows a locale selector in the edit sidebar.
Special locale values:
"all"— returns all locales as nested objects:{ title: { en: "Hello", de: "Hallo" } }- Any locale code (e.g.,
"en","de") — returns flat field names with that locale’s values - Omitted — uses the default locale
Example
[server]
admin_port = 8080
grpc_port = 9090
host = "127.0.0.1"
[database]
path = "/var/lib/crap/production.db"
[admin]
dev_mode = false
# require_auth = true
# access = "access.admin_panel"
[auth]
secret = "a-very-long-random-string-for-jwt-signing"
token_expiry = "24h"
max_login_attempts = 10
login_lockout_seconds = "10m"
[depth]
default_depth = 1
max_depth = 5
[upload]
max_file_size = "100MB"
[email]
smtp_host = "smtp.example.com"
smtp_port = 587
smtp_user = "noreply@example.com"
smtp_pass = "your-smtp-password"
from_address = "noreply@example.com"
from_name = "My App"
[logging]
file = true
# path = "data/logs"
# rotation = "daily"
# max_files = 30
[hooks]
on_init = ["hooks.seed.run"]
vm_pool_size = 8
max_instructions = 10000000
max_memory = "50MB"
allow_private_networks = false
http_max_response_bytes = "10MB"
Localization
Crap CMS supports per-field localization, allowing content to be managed in multiple languages. Any field type can be marked localized, and the API returns data differently based on a locale parameter.
Configuration
Enable localization by adding a [locale] section to crap.toml:
[locale]
default_locale = "en"
locales = ["en", "de", "fr"]
fallback = true
| Field | Default | Description |
|---|---|---|
default_locale | "en" | Default locale code. Content without an explicit locale uses this. |
locales | [] | Supported locale codes. Empty = localization disabled. |
fallback | true | Fall back to default locale value when the requested locale field is NULL. |
When locales is empty (the default), localization is completely disabled and all behavior is unchanged.
Per-Field Opt-In
Mark individual fields as localized in your Lua definitions:
crap.collections.define("pages", {
fields = {
crap.fields.text({
name = "title",
required = true,
localized = true, -- this field has per-locale values
}),
crap.fields.text({
name = "slug",
required = true,
-- not localized — single value shared across all locales
}),
},
})
Only fields with localized = true are affected. Non-localized fields behave exactly as before.
Storage
Localized fields use suffixed columns in SQLite:
- A field
titlewith locales["en", "de"]becomes columnstitle__enandtitle__de - Non-localized fields keep their single column
requiredis only enforced on the default locale column (title__en)uniquechecks the locale-specific column being written to (e.g., writing locale"de"checkstitle__de)- Junction tables (arrays, blocks, has-many) get a
_localecolumn
Unique + Localized
When a field has both unique = true and localized = true, uniqueness is enforced per locale. Two documents can have the same value in different locales, but not in the same locale:
crap.fields.text({
name = "slug",
unique = true,
localized = true,
})
| Scenario | Result |
|---|---|
Doc A has slug__en = "hello", Doc B creates with slug__en = "hello" | Rejected — duplicate in same locale |
Doc A has slug__en = "hello", Doc B creates with slug__de = "hello" | Allowed — different locales |
| Writing with no locale parameter | Checks the default locale column |
This also applies to fields inside a localized Group — uniqueness is checked against the fully suffixed column (e.g., seo__slug__en).
API Behavior
All read and write RPCs accept an optional locale parameter:
Reading
| Locale Parameter | Behavior |
|---|---|
| Omitted | Returns default locale values with flat field names |
"en" or "de" | Returns that locale’s values with flat field names |
"all" | Returns all locales as nested objects |
Flat response (single locale):
{ "title": "Hello World" }
Nested response (locale = "all"):
{ "title": { "en": "Hello World", "de": "Hallo Welt" } }
When fallback = true and a field is NULL for the requested locale, the default locale value is returned instead.
Writing
Writes target a single locale. The locale parameter determines which locale column to write to:
# Write German title
grpcurl -plaintext -d '{
"collection": "pages",
"id": "abc123",
"locale": "de",
"data": { "title": "Hallo Welt" }
}' localhost:50051 crap.ContentAPI/Update
Non-localized fields are always written to their single column regardless of the locale parameter.
Admin UI
When locales are configured, the admin edit page shows a locale selector in the sidebar. Clicking a locale tab reloads the form with that locale’s data. The save action writes to the selected locale.
When editing in a non-default locale, non-localized fields are shown as readonly with a “Shared Field” badge. This prevents accidentally overwriting values that are shared across all locales.
Lua API
Locale in CRUD Operations
All Lua CRUD functions accept an optional locale parameter:
-- Find with locale
local result = crap.collections.pages.find({ locale = "de" })
-- Find by ID with locale
local doc = crap.collections.pages.find_by_id(id, { locale = "de" })
-- Create in a specific locale
crap.collections.pages.create(data, { locale = "de" })
-- Update in a specific locale
crap.collections.pages.update(id, data, { locale = "de" })
-- Globals
local settings = crap.globals.site_settings.get({ locale = "de" })
crap.globals.site_settings.update(data, { locale = "de" })
Locale Configuration Access
-- Check if localization is enabled
if crap.locale.is_enabled() then
local default = crap.locale.get_default() -- "en"
local all = crap.locale.get_all() -- {"en", "de", "fr"}
end
Hook Context
The locale is available in hook context:
function M.before_change(ctx)
if ctx.locale then
print("Writing to locale: " .. ctx.locale)
end
return ctx
end
Admin Label Localization
Field labels, descriptions, placeholders, select option labels, block labels, and collection/global display names can all be localized. Instead of a plain string, provide a table keyed by locale:
crap.collections.define("pages", {
labels = {
singular = { en = "Page", de = "Seite" },
plural = { en = "Pages", de = "Seiten" },
},
fields = {
crap.fields.text({
name = "title",
required = true,
localized = true,
admin = {
label = { en = "Title", de = "Titel" },
placeholder = { en = "Enter page title", de = "Seitentitel eingeben" },
description = { en = "The main heading", de = "Die Hauptüberschrift" },
},
}),
crap.fields.select({
name = "status",
options = {
{ label = { en = "Draft", de = "Entwurf" }, value = "draft" },
{ label = { en = "Published", de = "Veröffentlicht" }, value = "published" },
},
}),
},
})
Plain strings still work — they’re used as-is regardless of locale:
admin = { label = "Title", placeholder = "Enter title" }
The admin UI resolves labels based on default_locale from crap.toml.
Admin UI Translations
All built-in admin UI text (buttons, labels, headings, error messages) can be translated. The system uses a {{t "key"}} Handlebars helper that looks up translation strings.
Built-in English
English translations are compiled into the binary. No configuration needed for English.
Custom Translations
Place a JSON file at <config_dir>/translations/<locale>.json to override or add strings:
{
"save": "Speichern",
"delete": "Löschen",
"create": "Neu erstellen",
"cancel": "Abbrechen",
"search_placeholder": "Suchen...",
"collections": "Sammlungen",
"globals": "Globale",
"dashboard": "Übersicht"
}
The file must match your default_locale in crap.toml. Keys not present in the override file fall back to English.
Interpolation
Translation strings support {{variable}} placeholders:
{
"page_of": "Seite {{page}} von {{total}}",
"no_items_yet": "Keine {{name}} vorhanden"
}
Templates pass values as hash parameters: {{t "page_of" page=pagination.page total=pagination.total_pages}}.
Available Keys
See translations/en.json in the source tree for all available translation keys.
Backward Compatibility
- No
[locale]config or emptylocales= feature completely disabled - No
localized = trueon fields = no locale columns created - All existing behavior is preserved when localization is not configured
- Plain string labels/descriptions/placeholders work exactly as before
Command-Line Reference
crap-cms <COMMAND> [OPTIONS]
Use crap-cms --help to list all commands, or crap-cms <command> --help for details on a specific command.
Global Flags
| Flag | Description |
|---|---|
-C, --config <PATH> | Path to the config directory (overrides auto-detection) |
-V, --version | Print version and exit |
-h, --help | Print help |
Config Directory Resolution
Most commands need a config directory (the folder containing crap.toml). The CLI resolves it in this order:
--config/-Cflag — explicit path, highest priorityCRAP_CONFIG_DIRenvironment variable — useful for CI/Docker- Auto-detection — walks up from the current working directory looking for
crap.toml
If you cd into your project directory (or any subdirectory), commands just work without any flags:
cd my-project
crap-cms serve
crap-cms status
crap-cms user list
From elsewhere, use -C:
crap-cms -C ./my-project serve
crap-cms -C ./my-project status
Or set the environment variable:
export CRAP_CONFIG_DIR=./my-project
crap-cms serve
Commands
serve — Start the server
crap-cms serve [-d] [--stop] [--restart] [--status] [--json] [--only <admin|api>] [--no-scheduler]
| Flag | Description |
|---|---|
-d, --detach | Run in the background (prints PID and exits) |
--stop | Stop a running detached instance (SIGTERM, then SIGKILL after 10s) |
--restart | Restart a running detached instance (stop + start) |
--status | Show whether a detached instance is running (PID, uptime) |
--json | Output logs as structured JSON (for log aggregation) |
--only <admin|api> | Start only the specified server. Omit to start both. |
--no-scheduler | Disable the background job scheduler |
--detach, --stop, --restart, and --status are mutually exclusive.
crap-cms serve # foreground
crap-cms serve -d # detached (background)
crap-cms serve --status # is it running?
crap-cms serve --stop # stop detached instance
crap-cms serve --restart # stop + start detached
crap-cms serve --json
crap-cms serve --only admin # admin UI only
crap-cms serve --only api # gRPC API only
crap-cms serve --no-scheduler # both servers, no scheduler
crap-cms serve --only admin --no-scheduler
crap-cms serve -d --only api # detached, API only
work — Run a standalone job worker
crap-cms work [--detach] [--stop] [--restart] [--status] [--queues <list>] [--concurrency <n>] [--no-cron]
Runs a dedicated job worker without HTTP/gRPC servers. For multi-server deployments where app servers run serve --no-scheduler and dedicated workers process jobs.
| Flag | Description |
|---|---|
-d, --detach | Run in the background |
--stop | Stop a running detached worker |
--restart | Restart a running detached worker |
--status | Show whether a detached worker is running |
--queues <list> | Comma-separated queue names to process (default: all) |
--concurrency <n> | Override jobs.max_concurrent for this worker |
--no-cron | Skip cron scheduling (let another worker handle it) |
crap-cms work # process all queues
crap-cms work --queues email # email queue only
crap-cms work --queues heavy --concurrency 2 # heavy jobs, limited concurrency
crap-cms work --no-cron # skip cron, just process queued jobs
crap-cms work -d # detached
crap-cms work --status # check if running
crap-cms work --stop # stop detached worker
Multi-server deployment:
# App servers (no job processing)
crap-cms serve --no-scheduler
# Dedicated workers
crap-cms work -d # general worker
crap-cms work -d --queues email # email-only worker
crap-cms work -d --queues heavy --concurrency 2 # heavy processing
status — Show project status
crap-cms status [--check]
| Flag | Description |
|---|---|
--check | Run best-practice health checks on configuration and project state |
Prints a comprehensive project overview:
- Server config — ports, compression, rate limiting
- Database — path, size (SQLite), or backend name (PostgreSQL)
- Uploads — total size and file count
- Locales — configured locales and fallback setting
- Collections — row counts, trash counts (soft-deleted documents), and tags (auth, upload, versions, soft_delete)
- Globals — registered global documents
- Versioning — which collections have drafts enabled and max version limits
- Access rules — read/create/update/delete functions per collection and global, with default deny/allow indicator
- Hooks — which lifecycle hooks are wired and to which functions
- Live events — event mode per target (metadata, full, disabled, or filter function)
- Migrations — total, applied, pending
- Jobs — defined, running, failed in last 24h
status --check
Runs a best-practice audit with 24 checks across four categories:
Security:
- Auth secret too short or placeholder value
- Brute-force protection disabled
default_deny = false(collections publicly accessible)- Collections without access rules
- gRPC rate limiting disabled with auth collections
- CORS wildcard origin with credentials
Performance:
max_depth > 3(N+1 query growth)- Cache disabled with relationship fields
- Pool size too small or connection timeout too aggressive
- Response compression disabled
pagination.max_limit > 500- Too many hooks or before_change hooks per collection
- Too many collections with
live_mode = "full"
Configuration:
dev_modeenableddefault_depthexceedsmax_depth- Email provider set to
"log"withverify_emailenabled
Operations:
- Pending migrations
- Auth collection without soft_delete
- Upload collection without versioning
- Soft delete without retention policy
- Empty auth collection (0 users)
crap-cms status # project overview
crap-cms status --check # overview + health audit
bench — Benchmark hooks, queries, and write cycles
Developer performance profiling tool. Measures hook execution time, query latency, and end-to-end write cycle duration.
bench hooks
crap-cms bench hooks [-c <COLLECTION>] [-n <ITERATIONS>] [--hooks <LIST>] [--exclude <LIST>] [--all] [-d <JSON>]
| Flag | Short | Default | Description |
|---|---|---|---|
--collection | -c | — | Filter to a specific collection |
--iterations | -n | 10 | Number of iterations per hook |
--hooks | — | — | Run only these hooks (comma-separated function refs) |
--exclude | — | — | Run all hooks except these (comma-separated) |
--all | — | — | Run all hooks (skip interactive selection) |
--data | -d | — | Input data as JSON object |
Safety model: Hooks may have external side effects (webhooks, API calls). By default, an interactive MultiSelect wizard lets you choose which hooks to benchmark. Use --hooks or --all for non-interactive use.
Data resolution: --data JSON > existing document from DB > synthetic fallback. Hook errors are caught and reported without stopping the benchmark.
crap-cms bench hooks # interactive wizard
crap-cms bench hooks --all # run all (with warning)
crap-cms bench hooks --hooks hooks.auto_slug -n 20 # specific hook, 20 iterations
crap-cms bench hooks -c posts --exclude hooks.send_webhook # all posts hooks except one
bench queries
crap-cms bench queries [-c <COLLECTION>] [--explain] [-w <JSON>]
| Flag | Short | Default | Description |
|---|---|---|---|
--collection | -c | — | Filter to a specific collection |
--explain | — | — | Show EXPLAIN QUERY PLAN output (SQLite only) |
--where | -w | — | JSON filter clause (same format as gRPC where parameter) |
Read-only — no side effects, no confirmation needed. The --where filter uses the same JSON syntax as the gRPC API (e.g., {"slug": {"equals": "my-post"}}). Combined with --explain, this shows whether queries hit indexes.
crap-cms bench queries # all collections
crap-cms bench queries -c posts --explain # single collection with query plan
crap-cms bench queries -c posts --where '{"status": "published"}' --explain # filtered + plan
bench create
crap-cms bench create <COLLECTION> [-n <ITERATIONS>] [-d <JSON>] [--no-hooks] [-y]
| Flag | Short | Default | Description |
|---|---|---|---|
--iterations | -n | 5 | Number of iterations |
--data | -d | — | Input data as JSON object |
--no-hooks | — | — | Skip hooks (measure pure validation + persist) |
--yes | -y | — | Skip confirmation prompt |
Runs the full service-layer create cycle (access check, validation, before-hooks, persist, after-hooks) inside a transaction that is rolled back after each iteration. No data is persisted.
When hooks are enabled and -y is not set, a confirmation prompt is shown because hooks may call external APIs. Unique fields are automatically randomized per iteration to avoid constraint violations.
crap-cms bench create posts # full cycle with confirmation
crap-cms bench create posts -y # skip confirmation
crap-cms bench create posts --no-hooks # pure validation + persist
crap-cms bench create posts -y -n 20 # 20 iterations, no prompt
crap-cms bench create posts -d '{"title": "test", "slug": "bench-test"}' # custom data
user — User management
user create
crap-cms user create [-c <COLLECTION>] [-e <EMAIL>] [-p <PASSWORD>] [-f <KEY=VALUE>]...
| Flag | Short | Default | Description |
|---|---|---|---|
--collection | -c | users | Auth collection slug |
--email | -e | — | User email (prompted if omitted) |
--password | -p | — | User password (prompted if omitted) |
--field | -f | — | Extra fields as key=value (repeatable) |
# Interactive (prompts for password)
crap-cms user create -e admin@example.com
# Non-interactive
crap-cms user create \
-e admin@example.com \
-p secret123 \
-f role=admin \
-f name="Admin User"
user list
crap-cms user list [-c <COLLECTION>]
Lists all users with ID, email, locked status, and verified status (if email verification is enabled).
crap-cms user list
crap-cms user list -c admins
user info
crap-cms user info [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>]
Shows detailed info for a single user: ID, email, locked/verified status, password status, timestamps, and all field values.
crap-cms user info -e admin@example.com
crap-cms user info --id abc123
user delete
crap-cms user delete [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>] [-y]
| Flag | Short | Description |
|---|---|---|
--collection | -c | Auth collection slug (default: users) |
--email | -e | User email |
--id | — | User ID |
--confirm | -y | Skip confirmation prompt |
user lock / user unlock
crap-cms user lock [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>]
crap-cms user unlock [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>]
user verify / user unverify
crap-cms user verify [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>]
crap-cms user unverify [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>]
Manually mark a user’s email as verified or unverified. Only works on collections with verify_email = true. Useful when email is not configured.
user change-password
Change a user’s password. Prompts for the new password if -p is omitted.
crap-cms user change-password [-c <COLLECTION>] [-e <EMAIL>] [--id <ID>] [-p <PASSWORD>]
init — Scaffold a new config directory
crap-cms init [DIR] [--no-input]
Runs an interactive wizard that scaffolds a complete config directory. Defaults to ./crap-cms if no directory is given.
The wizard prompts for:
| Prompt | Default | Description |
|---|---|---|
| Admin port | 3000 | Port for the admin UI |
| gRPC port | 50051 | Port for the gRPC API |
| Enable localization? | No | If yes, prompts for default locale and additional locales |
| Default locale | en | Default locale code (only if localization enabled) |
| Additional locales | — | Comma-separated (e.g., de,fr) |
| Create auth collection? | Yes | Creates a users collection with email/password login |
| Create first admin user? | Yes | Prompts for email and password immediately |
| Create upload collection? | Yes | Creates a media collection for file/image uploads |
| Create another collection? | No | Repeat to add more collections interactively |
A 64-character auth secret is auto-generated and written to crap.toml. A .mcp.json file is also created for Claude Code integration.
crap-cms init ./my-project
After scaffolding:
cd my-project
crap-cms serve
make — Generate scaffolding files
make collection
crap-cms make collection [SLUG] [-F <FIELDS>] [-T] [--auth] [--upload] [--versions] [--no-input] [-f]
| Flag | Short | Description |
|---|---|---|
--fields | -F | Inline field shorthand (see below) |
--no-timestamps | -T | Set timestamps = false |
--auth | — | Enable auth (email/password login) |
--upload | — | Enable uploads (file upload collection) |
--versions | — | Enable versioning (draft/publish workflow) |
--no-input | — | Non-interactive mode — skip all prompts, use flags and defaults only |
--force | -f | Overwrite existing file |
Without --no-input, missing arguments (slug, fields) are collected via interactive prompts. The field survey asks for name, type, required, and localized (if localization is enabled).
Field shorthand syntax:
name:type[:modifier][:modifier]...
Modifiers are order-independent:
| Modifier | Description |
|---|---|
required | Field is required |
localized | Field has per-locale values (see Localization) |
# Basic
crap-cms make collection posts
# With fields
crap-cms make collection articles \
-F "title:text:required,body:richtext"
# With localized fields
crap-cms make collection pages \
-F "title:text:required:localized,body:textarea:localized,slug:text:required"
# Auth collection
crap-cms make collection users --auth
# Upload collection
crap-cms make collection media --upload
# Non-interactive with versions
crap-cms make collection posts \
-F "title:text:required,body:richtext" --versions --no-input
make global
crap-cms make global [SLUG] [-F <FIELDS>] [-f]
| Flag | Short | Description |
|---|---|---|
--fields | -F | Inline field shorthand (same syntax as make collection) |
--force | -f | Overwrite existing file |
crap-cms make global site_settings
crap-cms make global nav -F "links:array(label:text:required,url:text)"
make hook
crap-cms make hook [NAME] [-t <TYPE>] [-c <COLLECTION>] [-l <POSITION>] [-F <FIELD>] [--force]
| Flag | Short | Description |
|---|---|---|
--type | -t | Hook type: collection, field, access, or condition |
--collection | -c | Target collection or global slug |
--position | -l | Lifecycle position (e.g., before_change, after_read) |
--field | -F | Target field name (field hooks only; watched field for condition hooks) |
--force | — | Overwrite existing file |
Missing flags are resolved via interactive prompts. The wizard lists collections and globals from the registry (globals are tagged). For non-interactive mode, the slug is auto-detected as a global if it exists in the globals registry.
Valid positions by type:
| Type | Positions |
|---|---|
collection | before_validate, before_change, after_change, before_read, after_read, before_delete, after_delete, before_broadcast |
field | before_validate, before_change, after_change, after_read |
access | read, create, update, delete |
condition | table, boolean |
Generated hooks use per-collection typed annotations for IDE support:
- Collection hooks:
crap.hook.Posts,crap.hook.global_site_settings - Field hooks:
crap.field_hook.Posts,crap.field_hook.global_site_settings - Condition hooks:
crap.data.Posts,crap.global_data.SiteSettings - Delete hooks: generic
crap.HookContext(data only contains the document ID) - Access hooks: generic
crap.AccessContext
# Interactive (prompts for everything)
crap-cms make hook
# Fully specified
crap-cms make hook auto_slug \
-t collection -c posts -l before_change
# Field hook
crap-cms make hook normalize_email \
-t field -c users -l before_validate -F email
# Access hook
crap-cms make hook owner_only \
-t access -c posts -l read
# Condition hook (client-side table)
crap-cms make hook show_external_url \
-t condition -c posts -l table -F post_type
make job
crap-cms make job [SLUG] [-s <SCHEDULE>] [-q <QUEUE>] [-r <RETRIES>] [-t <TIMEOUT>] [-f]
| Flag | Short | Default | Description |
|---|---|---|---|
--schedule | -s | — | Cron expression (e.g., "0 3 * * *") |
--queue | -q | default | Queue name |
--retries | -r | 0 | Max retry attempts |
--timeout | -t | 60 | Timeout in seconds |
--force | -f | — | Overwrite existing file |
# Interactive (prompts for slug)
crap-cms make job
# With schedule
crap-cms make job cleanup_expired -s "0 3 * * *" -r 3 -t 300
# Simple job (triggered from hooks)
crap-cms make job send_welcome_email
blueprint — Manage saved blueprints
blueprint save
crap-cms blueprint save <NAME> [-f]
Saves the current config directory as a reusable blueprint (excluding data/, uploads/, types/). A .crap-blueprint.toml manifest is written with the CMS version and timestamp.
blueprint use
crap-cms blueprint use <NAME> [DIR]
Creates a new project from a saved blueprint. If the blueprint was saved with a different CMS version, a warning is printed (but the operation proceeds).
blueprint list
crap-cms blueprint list
Lists saved blueprints with collection/global counts and the CMS version they were saved with.
blueprint remove
crap-cms blueprint remove <NAME>
db — Database tools
db console
crap-cms db console
Opens an interactive sqlite3 session on the project database.
db cleanup
crap-cms db cleanup [--confirm]
| Flag | Description |
|---|---|
--confirm | Actually drop orphan columns (default: dry-run report only) |
Detects columns in collection tables that don’t correspond to any field in the current Lua definitions. System columns (_-prefixed like _password_hash, _locked) are always kept. Plugin columns are safe because plugins run during schema loading — their fields are part of the live definitions.
# Dry run — show orphans without removing them
crap-cms db cleanup
# Actually drop orphan columns
crap-cms db cleanup --confirm
export — Export collection data
crap-cms export [-c <COLLECTION>] [-o <FILE>]
| Flag | Short | Description |
|---|---|---|
--collection | -c | Export only this collection (default: all) |
--output | -o | Output file (default: stdout) |
Export includes crap_version and exported_at metadata in the JSON envelope. On import, a version mismatch produces a warning (but does not abort).
crap-cms export
crap-cms export -c posts -o posts.json
import — Import collection data
crap-cms import <FILE> [-c <COLLECTION>]
| Flag | Short | Description |
|---|---|---|
--collection | -c | Import only this collection (default: all in file) |
crap-cms import backup.json
crap-cms import backup.json -c posts
typegen — Generate typed definitions
Three subcommands, one per artifact / audience:
crap-cms typegen lua [-o <DIR>]
crap-cms typegen client -l <LANG[,LANG...]> [-o <DIR>]
crap-cms typegen proto -m <MODULE_PATH> [-o <DIR>]
| Subcommand | Writes | Audience |
|---|---|---|
lua | types/crap.lua (API surface) + types/hooks.lua (per-collection hook narrowings) | Server-side Lua hook / access / job authors |
client | types/client.<ext> per requested language (ts, go, py, rs) | External gRPC / REST API consumers |
proto | types/proto.rs | Rust gRPC servers wanting From<proto::Document> conversions |
| Flag | Short | Default | Subcommand | Description |
|---|---|---|---|---|
--lang | -l | — | client | Comma list of client languages (ts, go, py, rs). Required. |
--module | -m | — | proto | Rust module path to the prost-generated proto types (e.g. "crate::proto"). Required. |
--output | -o | <config>/types/ | all | Output directory. |
crap-cms typegen lua # types/crap.lua + types/hooks.lua
crap-cms typegen client -l ts # types/client.ts
crap-cms typegen client -l ts,go,py -o ./shared # multiple langs, custom dir
crap-cms typegen proto -m "crate::proto" # types/proto.rs
Running crap-cms typegen with no subcommand prints help. Under admin.dev_mode = true, the serve command auto-regenerates crap.lua + hooks.lua on startup so hook authors don’t have to remember typegen lua after editing collections — production startups skip this.
proto — Export proto file
crap-cms proto [-o <PATH>]
Writes content.proto to stdout or the given path. No config directory needed.
crap-cms proto
crap-cms proto -o ./proto/
migrate — Run database migrations
crap-cms migrate <create|up|down|list|fresh>
| Subcommand | Description |
|---|---|
create <NAME> | Generate a new migration file (e.g., backfill_slugs) |
up | Sync schema + run pending migrations |
down [-s|--steps N] | Roll back last N migrations (default: 1) |
list | Show all migration files with status |
fresh [-y|--confirm] | Drop all tables and recreate (destructive, requires confirmation) |
crap-cms migrate create backfill_slugs
crap-cms migrate up
crap-cms migrate list
crap-cms migrate down -s 2
crap-cms migrate fresh -y
backup — Backup database
crap-cms backup [-o <DIR>] [-i]
| Flag | Short | Description |
|---|---|---|
--output | -o | Output directory (default: <config>/backups/) |
--include-uploads | -i | Also compress the uploads directory |
crap-cms backup
crap-cms backup -o /tmp/backups -i
restore — Restore from backup
crap-cms restore <BACKUP> [-i] [-y]
| Flag | Short | Description |
|---|---|---|
--include-uploads | -i | Also restore uploads from uploads.tar.gz if present |
--confirm | -y | Required — confirms the destructive operation |
Replaces the current database with a backup snapshot. Cleans up stale WAL/SHM files.
crap-cms restore ./backups/backup-2026-03-07T10-00-00 -y
crap-cms restore /tmp/backups/backup-2026-03-07T10-00-00 -i -y
templates — Manage admin template / static customizations
Extract the compiled-in admin templates and static files into your config directory for customization, then track drift between your customizations and upstream.
Each extracted file gets a crap-cms:source <version> header (in the file’s native comment syntax) so templates status can report which version your customizations were extracted from.
templates list
crap-cms templates list [-t <TYPE>] [-v]
| Flag | Short | Description |
|---|---|---|
--type | -t | Filter: templates or static (default: both) |
--verbose | -v | Show full file tree with individual sizes (default: compact summary) |
crap-cms templates list
crap-cms templates list -t templates
crap-cms templates list -v
templates extract
crap-cms templates extract [PATHS...] [-a] [-t <TYPE>] [-f]
| Flag | Short | Description |
|---|---|---|
--all | -a | Extract all files |
--type | -t | Filter: templates or static (only with --all) |
--force | -f | Overwrite existing files |
# Extract specific files
crap-cms templates extract layout/base.hbs styles.css
# Extract all templates
crap-cms templates extract --all --type templates
# Extract everything, overwriting existing
crap-cms templates extract --all --force
templates status
crap-cms templates status
Reports the relationship between every customized file in <config_dir>/{templates,static}/ and the upstream embedded default. Each file is classified as one of:
✓ current— extracted from the running version⚠ behind: extracted from <ver>— older version, may be missing upstream fixes↑ ahead: extracted from <ver>— newer than running (downgrade scenario)= pristine (matches upstream)— extracted but never customized? no source header— hand-written, or header was stripped? unparseable source header— header found but version isn’t valid semver✗ orphaned— file no longer exists in the embedded upstream
templates diff
crap-cms templates diff <PATH>
Shows a unified diff between a customized file and its embedded default. The path is relative to the config dir (e.g. templates/layout/base.hbs, static/styles.css).
crap-cms templates diff templates/layout/base.hbs
fmt — Format Handlebars templates
Format .hbs files in place using the project’s built-in Handlebars formatter. Same role as cargo fmt for Rust or biome check --write for JS/CSS — keeps the templates’ style consistent.
crap-cms fmt [PATHS...] [--check] [--stdio]
| Flag | Description |
|---|---|
| (none) | Format every .hbs under the given paths in place. Default scope is templates/. |
--check | Don’t write — exit non-zero if any file would change. CI gate. |
--stdio | Read from stdin, write the formatted result to stdout. Used by editor formatter integrations. Mutually exclusive with --check. |
crap-cms fmt # format all templates/
crap-cms fmt templates/auth/ # one subtree
crap-cms fmt templates/fields/text.hbs # one file
crap-cms fmt --check # CI: exit 1 if any file would change
cat my.hbs | crap-cms fmt --stdio # editor pipe
The formatter is idempotent (fmt(fmt(x)) == fmt(x)) and applies the rule set documented in the Admin UI: Template Formatter page (block-helper indentation, attribute stacking, comment preservation, etc.).
Editor integration (Neovim + conform.nvim):
-- ~/.config/nvim/lua/plugins/conform.lua
opts = {
formatters_by_ft = { handlebars = { 'crap_cms' } },
formatters = {
crap_cms = {
command = 'crap-cms',
args = { 'fmt', '--stdio' },
stdin = true,
},
},
},
Pre-commit hook entry:
echo "Running crap-cms fmt..."
cargo run --quiet --bin crap-cms -- fmt --check
jobs — Manage background jobs
jobs list
crap-cms jobs list
Lists all defined jobs with their configuration (handler, schedule, queue, retries, timeout, concurrency).
jobs trigger
crap-cms jobs trigger <SLUG> [-d <DATA>]
| Flag | Short | Default | Description |
|---|---|---|---|
--data | -d | "{}" | JSON data to pass to the job |
Manually queue a job for execution. Works even while the server is running (SQLite WAL allows concurrent access). Prints the queued job run ID.
jobs status
crap-cms jobs status [--id <ID>] [-s <SLUG>] [-l <LIMIT>]
| Flag | Short | Default | Description |
|---|---|---|---|
--id | — | — | Show details for a specific run |
--slug | -s | — | Filter by job slug |
--limit | -l | 20 | Max results to show |
Show recent job runs. If --id is given, shows details for that specific run. Otherwise lists recent runs across all jobs.
jobs cancel
crap-cms jobs cancel [--slug <SLUG>]
| Flag | Default | Description |
|---|---|---|
--slug, -s | (all) | Only cancel pending jobs with this slug. Without it, cancels all pending jobs. |
Deletes pending jobs from the queue. Useful for clearing stuck or unwanted jobs that keep retrying.
jobs purge
crap-cms jobs purge [--older-than <DURATION>]
| Flag | Default | Description |
|---|---|---|
--older-than | 7d | Delete completed/failed/stale runs older than this. Supports Nd, Nh, Nm formats. |
jobs healthcheck
crap-cms jobs healthcheck
Checks job system health and prints a summary: defined jobs, stale jobs (running but heartbeat expired), failed jobs in the last 24 hours, pending jobs waiting longer than 5 minutes, and scheduled jobs that have never completed a run.
Exit status: healthy (no issues), warning (failed or long-pending jobs), unhealthy (stale jobs detected).
crap-cms jobs list
crap-cms jobs trigger cleanup_expired
crap-cms jobs status
crap-cms jobs status --id abc123
crap-cms jobs cancel
crap-cms jobs cancel -s process_inquiry
crap-cms jobs purge --older-than 30d
crap-cms jobs healthcheck
images — Manage image processing queue
Inspect and manage the background image format conversion queue. See Image Processing for how to enable queued conversion.
images list
crap-cms images list [-s <STATUS>] [-l <LIMIT>]
| Flag | Short | Default | Description |
|---|---|---|---|
--status | -s | — | Filter by status: pending, processing, completed, failed |
--limit | -l | 20 | Max entries to show |
images stats
crap-cms images stats
Shows counts by status (pending, processing, completed, failed) and total.
images retry
crap-cms images retry [--id <ID>] [--all] [-y]
| Flag | Short | Description |
|---|---|---|
--id | — | Retry a specific failed entry by ID |
--all | — | Retry all failed entries |
--confirm | -y | Required with --all |
images purge
crap-cms images purge [--older-than <DURATION>]
| Flag | Default | Description |
|---|---|---|
--older-than | 7d | Delete completed/failed entries older than this. Supports Nd, Nh, Nm, Ns formats. |
crap-cms images list
crap-cms images list -s failed
crap-cms images stats
crap-cms images retry --id abc123
crap-cms images retry --all -y
crap-cms images purge --older-than 30d
trash — Manage soft-deleted documents
Inspect, restore, and purge documents in the trash (only for collections with soft_delete = true). See Soft Deletes for details on the soft-delete model.
trash list
crap-cms trash list [-c <COLLECTION>]
| Flag | Short | Description |
|---|---|---|
--collection | -c | Filter by collection slug (default: all collections with soft delete) |
trash restore
crap-cms trash restore <COLLECTION> <ID>
Restore a single trashed document back to the active list. Both COLLECTION and ID are positional arguments.
trash purge
crap-cms trash purge [-c <COLLECTION>] [--older-than <DURATION>] [--dry-run]
| Flag | Short | Default | Description |
|---|---|---|---|
--collection | -c | — | Filter by collection slug (default: all soft-delete collections) |
--older-than | — | all | Purge documents deleted more than this ago (e.g. 30d, 24h, 30m), or all for every trashed document |
--dry-run | — | — | Print what would be deleted without actually deleting |
trash empty
crap-cms trash empty <COLLECTION> [-y]
| Flag | Short | Description |
|---|---|---|
--confirm | -y | Required — confirms the destructive operation |
Permanently delete every trashed document in the given collection.
crap-cms trash list
crap-cms trash list -c posts
crap-cms trash restore posts abc123
crap-cms trash purge --older-than 7d
crap-cms trash purge -c posts --dry-run
crap-cms trash empty posts -y
mcp — Start the MCP server (stdio)
Start an MCP (Model Context Protocol) server over stdio for AI assistant integration.
crap-cms mcp
Reads JSON-RPC 2.0 from stdin, writes responses to stdout. Use with Claude Desktop, Cursor, VS Code, or any MCP-compatible client. See MCP Overview for configuration and usage.
logs — View and manage log files
crap-cms logs [-f] [-n <lines>]
crap-cms logs clear
View log output from file-based logging. Requires [logging] file = true in crap.toml (auto-enabled when running with --detach).
| Flag | Description |
|---|---|
-f, --follow | Follow log output in real time (like tail -f) |
-n, --lines <N> | Number of lines to show (default: 100) |
Subcommands:
| Subcommand | Description |
|---|---|
clear | Remove old rotated log files, keeping only the current one |
crap-cms logs # show last 100 lines
crap-cms logs -f # follow in real time
crap-cms logs -n 50 # show last 50 lines
crap-cms logs clear # remove old rotated files
Log files are stored in data/logs/ (or the path configured in [logging] path). Old files are automatically pruned on startup based on max_files. See Configuration Reference for all logging options.
update — Manage installed versions
crap-cms update [-y] [--force]
crap-cms update <SUBCOMMAND>
Without a subcommand, checks for a newer release and installs + activates it (with confirmation prompt).
| Flag | Description |
|---|---|
-y, --yes | Skip confirmation prompts |
--force | Allow self-update even when the binary looks distro-managed |
update check
crap-cms update check
Compare current version to the latest GitHub release. Exit code 0 if up-to-date, 1 if newer is available.
update list
crap-cms update list
List available release tags, marking installed versions and the active one.
update install
crap-cms update install <VERSION> [--reinstall]
Download, verify (SHA256), and stage a version in the local store (~/.local/share/crap-cms/versions/). Does not activate — use update use to switch.
update use
crap-cms update use <VERSION>
Switch the current symlink to the given installed version. Also auto-installs shell completions for the user’s login shell (bash, zsh, or fish) — see update completions for where files are written and how the zsh $fpath is probed.
update uninstall
crap-cms update uninstall <VERSION>
Remove an installed version from the store. Refuses to uninstall the active version. If this removes the last installed version, auto-installed shell completion files are cleaned up too.
update where
crap-cms update where
Print the resolved path of the currently active binary.
update completions
crap-cms update completions <SHELL>
crap-cms update completions <SHELL> --uninstall
crap-cms update completions --uninstall
Generate shell completions (to stdout) or remove installed files. Supported shells: bash, zsh, fish, elvish, powershell.
For bash, zsh, and fish, completions are also auto-installed after update use and bare update:
- Zsh: the install directory is chosen by probing
$fpath(zsh -i -c 'print -l $fpath'). If~/.zfuncis already on$fpath, the file goes there; otherwise the first user-owned directory on$fpathis used. If neither is available, the file is written to~/.zfuncand an activation hint (fpath=(~/.zfunc $fpath)beforecompinit) is shown on every install until it’s wired up. - Bash: installed under
$XDG_DATA_HOME/bash-completion/completions/crap-cms. A hint is emitted if thebash-completionentry point isn’t present on the system. - Fish: installed under
$XDG_CONFIG_HOME/fish/completions/crap-cms.fish— auto-loaded by fish.
--uninstall without a shell removes every auto-installed completion file. With a shell, it removes just that shell’s file. update uninstall of the last installed version also runs this cleanup automatically.
crap-cms update # install latest + activate
crap-cms update -y # non-interactive
crap-cms update check # check for updates
crap-cms update list # list available versions
crap-cms update install v0.1.0-alpha.7 # download + verify
crap-cms update use v0.1.0-alpha.7 # switch to version
crap-cms update uninstall v0.1.0-alpha.6 # remove old version
crap-cms update where # print active binary path
crap-cms update completions bash # print bash completions
eval "$(crap-cms update completions bash)" # source directly
Environment Variables
| Variable | Description |
|---|---|
CRAP_CONFIG_DIR | Path to the config directory (same as --config flag; flag takes priority) |
RUST_LOG | Controls log verbosity. Default: crap_cms=debug,info for serve, crap_cms=error for all other commands. Example: RUST_LOG=crap_cms=trace |
CRAP_LOG_FORMAT | Set to json for structured JSON log output (same as --json flag) |
Collections
Collections are the core data model in Crap CMS. Each collection maps to a SQLite table and is defined in a Lua file.
Basics
- One Lua file per collection in the
collections/directory - Files are loaded alphabetically at startup
- Each file calls
crap.collections.define(slug, config) - The
slugbecomes the table name and URL segment - Fields, hooks, access control, auth, and uploads are all configured in the definition
Example
-- collections/posts.lua
crap.collections.define("posts", {
labels = {
singular = "Post",
plural = "Posts",
},
timestamps = true,
admin = {
use_as_title = "title",
default_sort = "-created_at",
list_searchable_fields = { "title", "slug" },
},
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.text({ name = "slug", required = true, unique = true }),
crap.fields.select({
name = "status",
default_value = "draft",
options = {
{ label = "Draft", value = "draft" },
{ label = "Published", value = "published" },
},
}),
crap.fields.richtext({ name = "content" }),
},
hooks = {
before_change = { "hooks.posts.auto_slug" },
},
access = {
read = "hooks.access.public_read",
create = "hooks.access.authenticated",
delete = "hooks.access.admin_only",
},
})
System Fields
Every collection automatically has these columns (not in your field definitions):
| Field | Type | Description |
|---|---|---|
id | TEXT PRIMARY KEY | Auto-generated nanoid |
created_at | TEXT | ISO 8601 timestamp (if timestamps = true) |
updated_at | TEXT | ISO 8601 timestamp (if timestamps = true) |
Auth collections also get a hidden _password_hash TEXT column.
Versioned collections with drafts = true also get:
| Field | Type | Description |
|---|---|---|
_status | TEXT | "published" or "draft" (auto-managed) |
Versioned collections also get a companion _versions_{slug} table that stores JSON snapshots of every save. See Versions & Drafts.
Schema Sync
On startup, Crap CMS compares each Lua definition against the existing SQLite table:
- Missing table — creates it with all defined columns
- Missing columns — adds them via
ALTER TABLE - Removed columns — logged as a warning (SQLite doesn’t easily drop columns)
- Type changes — not automatically migrated (manual intervention needed)
Collection Definition Schema
Full reference for every property accepted by crap.collections.define(slug, config).
Top-Level Properties
| Property | Type | Default | Description |
|---|---|---|---|
labels | table | {} | Display names for the admin UI |
labels.singular | string | slug | Singular name (e.g., “Post”) |
labels.plural | string | slug | Plural name (e.g., “Posts”) |
timestamps | boolean | true | Auto-manage created_at and updated_at |
fields | FieldDefinition[] | {} | Field definitions (see Fields) |
admin | table | {} | Admin UI options |
hooks | table | {} | Lifecycle hook references |
auth | boolean or table | nil | Authentication config (see Auth Collections) |
upload | boolean or table | nil | Upload config (see Uploads) |
access | table | {} | Access control function refs |
versions | boolean or table | nil | Versioning and drafts config (see Versions & Drafts) |
soft_delete | boolean | false | Enable soft deletes (see Soft Deletes) |
soft_delete_retention | string | nil | Auto-purge retention period (e.g., "30d"). Requires soft_delete = true. |
live | boolean or string | nil | Live update broadcasting (see Live Updates) |
mcp | table | {} | MCP tool config. { description = "..." } for MCP tool descriptions. |
indexes | IndexDefinition[] | {} | Compound indexes (see Indexes below) |
admin
| Property | Type | Default | Description |
|---|---|---|---|
use_as_title | string | nil | Field name to display as the row label in admin lists |
default_sort | string | nil | Default sort field. Prefix with - for descending (e.g., "-created_at") |
hidden | boolean | false | Hide this collection from the admin sidebar |
list_searchable_fields | string[] | {} | Fields to search when using the admin list search bar |
hooks
All hook values are arrays of string references in module.function format.
| Property | Type | Description |
|---|---|---|
before_validate | string[] | Runs before field validation. Has CRUD access. |
before_change | string[] | Runs after validation, before write. Has CRUD access. |
after_change | string[] | Runs after create/update (inside transaction). Has CRUD access. Errors roll back. |
before_read | string[] | Runs before returning read results. No CRUD access. |
after_read | string[] | Runs after read, before response. No CRUD access. |
before_delete | string[] | Runs before delete. Has CRUD access. |
after_delete | string[] | Runs after delete (inside transaction). Has CRUD access. Errors roll back. |
before_broadcast | string[] | Runs after commit, before broadcast. No CRUD access. See Live Updates. |
See Hooks for full details.
auth
Set to true for defaults, or provide a config table:
-- Simple
auth = true
-- With options
auth = {
token_expiry = 3600,
disable_local = false,
strategies = {
{ name = "api-key", authenticate = "hooks.auth.api_key_check" },
},
}
See Auth Collections for the full schema.
upload
Set to true for defaults, or provide a config table:
-- Simple
upload = true
-- With options
upload = {
mime_types = { "image/*" },
max_file_size = 10485760,
image_sizes = {
{ name = "thumbnail", width = 300, height = 300, fit = "cover" },
},
format_options = {
webp = { quality = 80 },
},
}
See Uploads for the full schema.
access
| Property | Type | Description |
|---|---|---|
read | string | Lua function ref for read access. |
create | string | Lua function ref for create access. |
update | string | Lua function ref for update access. |
delete | string | Lua function ref for delete access. |
If a property is omitted, that operation is allowed for everyone.
See Access Control for full details.
versions
Set to true for defaults (drafts enabled, unlimited versions), or provide a config table:
-- Simple: versions with drafts
versions = true
-- With options
versions = {
drafts = true,
max_versions = 20,
}
-- Versions without drafts (pure audit trail)
versions = {
drafts = false,
max_versions = 50,
}
| Property | Type | Default | Description |
|---|---|---|---|
drafts | boolean | true | Enable draft/publish workflow with _status field |
max_versions | integer | 0 | Max versions per document. 0 = unlimited. |
See Versions & Drafts for the full workflow.
Indexes
Field-Level Indexes
Set index = true on a field to create a B-tree index on its column. This speeds up queries that filter or sort on that field. Unique fields are already indexed by SQLite, so index = true is skipped when unique = true.
crap.fields.text({ name = "status", index = true }),
crap.fields.date({ name = "published_at", index = true }),
For localized fields, one index is created per locale column (e.g., idx_posts_title__en, idx_posts_title__de).
Compound Indexes
Use the top-level indexes array for multi-column indexes:
indexes = {
{ fields = { "status", "created_at" } },
{ fields = { "category", "slug" }, unique = true },
}
| Property | Type | Default | Description |
|---|---|---|---|
fields | string[] | required | Column names to include in the index. |
unique | boolean | false | Create a UNIQUE index. |
Indexes are synced idempotently on startup: missing indexes are created with CREATE INDEX IF NOT EXISTS, and stale indexes (from removed fields or changed definitions) are dropped. Only indexes with the idx_{collection}_ naming prefix are managed — external indexes are left untouched.
Complete Example
crap.collections.define("posts", {
labels = {
singular = "Post",
plural = "Posts",
},
timestamps = true,
admin = {
use_as_title = "title",
default_sort = "-created_at",
hidden = false,
list_searchable_fields = { "title", "slug", "content" },
},
fields = {
crap.fields.text({
name = "title",
required = true,
hooks = {
before_validate = { "hooks.posts.trim_title" },
},
}),
crap.fields.text({
name = "slug",
required = true,
unique = true,
}),
crap.fields.select({
name = "status",
required = true,
default_value = "draft",
options = {
{ label = "Draft", value = "draft" },
{ label = "Published", value = "published" },
{ label = "Archived", value = "archived" },
},
}),
crap.fields.richtext({ name = "content" }),
crap.fields.relationship({
name = "tags",
relationship = { collection = "tags", has_many = true },
}),
},
hooks = {
before_change = { "hooks.posts.auto_slug" },
},
access = {
read = "hooks.access.public_read",
create = "hooks.access.authenticated",
update = "hooks.access.authenticated",
delete = "hooks.access.admin_only",
},
})
Versions & Drafts
Crap CMS supports document versioning with an optional draft/publish workflow.
Enabling Versions
Add versions to your collection definition:
-- Simple: enables versions with drafts
crap.collections.define("articles", {
versions = true,
fields = { ... },
})
-- With options
crap.collections.define("articles", {
versions = {
drafts = true,
max_versions = 20,
},
fields = { ... },
})
Config Properties
| Property | Type | Default | Description |
|---|---|---|---|
drafts | boolean | true | Enable draft/publish workflow with _status field |
max_versions | integer | 0 | Max versions per document. 0 = unlimited. Oldest versions are pruned first. |
Setting versions = true is equivalent to { drafts = true, max_versions = 0 }.
Setting versions = false or omitting it disables versioning entirely.
How It Works
When versioning is enabled, every create and update operation saves a JSON snapshot of the document to a _versions_{slug} table. This provides a full audit trail with the ability to restore any previous version.
Database Changes
Versioned collections get an additional table:
_versions_articles (
id TEXT PRIMARY KEY,
_parent TEXT NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
_version INTEGER NOT NULL,
_status TEXT NOT NULL, -- "published" or "draft"
_latest INTEGER NOT NULL DEFAULT 0, -- 1 for the most recent version
snapshot TEXT NOT NULL, -- full JSON snapshot
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
)
When drafts = true, the main table also gets a _status column (TEXT NOT NULL DEFAULT 'published').
Draft/Publish Workflow
When drafts = true, documents have a _status field that is either "published" or "draft".
Creating Documents
| Action | Result |
|---|---|
| Create (publish) | Document inserted with _status = 'published' + version snapshot |
| Create (draft) | Document inserted with _status = 'draft' + version snapshot |
Updating Documents
| Action | Result |
|---|---|
| Update (publish) | Main table updated, _status = 'published' + new version snapshot |
| Update (draft) | Version-only save — main table is NOT modified, only a new draft version snapshot is created |
| Unpublish | _status set to 'draft' + new version snapshot |
The version-only draft save is key: it lets authors iterate on changes without affecting the published version. The main table always reflects the last published state.
Reading Documents
| API Call | Default Behavior |
|---|---|
Find | Returns only _status = 'published' documents |
Find with draft = true | Returns all documents (published + draft) |
FindByID | Returns the main table document (published version) |
FindByID with draft = true | Returns the latest version snapshot (may be a newer draft) |
Validation
Required field validation is skipped for draft saves. This lets authors save incomplete work. Validation is enforced when publishing (draft = false).
gRPC API
Draft Parameter
The draft parameter is available on these RPCs:
// Create a draft
CreateRequest { collection, data, draft: true }
// Draft update (version-only, main table unchanged)
UpdateRequest { collection, id, data, draft: true }
// Find all documents including drafts
FindRequest { collection, draft: true }
// Get the latest version (may be a newer draft)
FindByIDRequest { collection, id, draft: true }
ListVersions
List version history for a document:
grpcurl -plaintext -d '{
"collection": "articles",
"id": "abc123",
"limit": "10"
}' localhost:50051 crap.ContentAPI/ListVersions
Response:
{
"versions": [
{ "id": "v1", "version": 3, "status": "draft", "latest": true, "created_at": "..." },
{ "id": "v2", "version": 2, "status": "published", "latest": false, "created_at": "..." },
{ "id": "v3", "version": 1, "status": "published", "latest": false, "created_at": "..." }
]
}
RestoreVersion
Restore a previous version, writing its snapshot data back to the main table:
grpcurl -plaintext -d '{
"collection": "articles",
"document_id": "abc123",
"version_id": "v3"
}' localhost:50051 crap.ContentAPI/RestoreVersion
This overwrites the main table with the snapshot data, sets _status to "published", and creates a new version entry for the restore.
Lua API
The draft option is available on create and update:
-- Create as draft
local doc = crap.collections.articles.create({
title = "Work in progress",
}, { draft = true })
-- Draft update (version-only save)
crap.collections.articles.update(doc.id, {
title = "Still editing...",
}, { draft = true })
-- Publish
crap.collections.articles.update(doc.id, {
title = "Final Title",
}) -- draft defaults to false
Admin UI
Buttons
When drafts are enabled, the edit form shows context-aware buttons:
| Document State | Primary Button | Secondary Button | Extra |
|---|---|---|---|
| Create (new) | Publish | Save as Draft | |
| Editing (draft) | Publish | Save Draft | |
| Editing (published) | Update | Save Draft | Unpublish |
Status Badge
A status badge (published or draft) appears in the document meta panel and in the collection list view.
Version History
The edit sidebar shows a “Version History” panel listing recent versions with:
- Version number
- Status badge (published/draft)
- Timestamp
- Restore button (for non-latest versions)
Clicking Restore writes the snapshot data back to the main table and redirects to the edit form.
Access Control
Draft operations use the existing update access rule. There is no separate access rule for drafts. If you need finer-grained control (e.g., only admins can publish, but editors can save drafts), inspect the incoming data._status field in your access hooks:
function hooks.access.publish_control(ctx)
if ctx.data and ctx.data._status == "draft" then
-- Any authenticated user can save drafts
return ctx.user ~= nil
end
-- Only admins can publish
return ctx.user and ctx.user.role == "admin"
end
Versions Without Drafts
You can enable version history without the draft/publish workflow:
versions = {
drafts = false,
max_versions = 50,
}
This creates version snapshots on every save but does not add a _status column, does not filter by publish state, and does not show draft/publish buttons in the admin UI. Useful for pure audit trails.
Example
crap.collections.define("articles", {
labels = { singular = "Article", plural = "Articles" },
timestamps = true,
versions = {
drafts = true,
max_versions = 20,
},
admin = {
use_as_title = "title",
default_sort = "-created_at",
},
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.text({ name = "slug", required = true, unique = true }),
crap.fields.textarea({ name = "summary" }),
crap.fields.richtext({ name = "body" }),
},
access = {
read = "hooks.access.public_read",
create = "hooks.access.authenticated",
update = "hooks.access.authenticated",
delete = "hooks.access.admin_only",
},
})
Soft Deletes
Collections can opt into soft deletes so that deleted documents are moved to trash instead of being permanently removed. Trashed documents can be restored or permanently purged after a configurable retention period.
Enabling
crap.collections.define("posts", {
soft_delete = true,
soft_delete_retention = "30d", -- optional: auto-purge after 30 days
-- ...
})
When soft_delete = true:
- Deleting a document sets a
_deleted_attimestamp instead of removing the row - Soft-deleted documents are excluded from all reads, counts, and search
- Upload files are preserved until the document is permanently purged
- Version history is preserved
Permissions
Soft deletes introduce a split between trashing (reversible) and permanent deletion (destructive):
| Action | Permission | Fallback | Description |
|---|---|---|---|
| Move to trash | access.trash | access.update | Soft-delete a document |
| Restore from trash | access.trash | access.update | Un-delete a trashed document |
| Delete permanently | access.delete | (blocks if not set) | Permanently remove a document |
| Empty trash | access.delete | (blocks if not set) | Permanently remove all trashed documents |
| Auto-purge | (none) | — | System-level scheduler, always runs |
Example configuration:
access = {
read = "access.anyone",
create = "access.editor_or_above",
update = "access.editor_or_above",
trash = "access.editor_or_above", -- editors can trash and restore
delete = "access.admin_or_director", -- only admins can permanently delete
}
If access.trash is not set, it falls back to access.update — any user who can edit a document can also trash it. If access.delete is not set, permanent deletion is only possible via the auto-purge scheduler.
Admin UI
Trash view
The collection list shows a Trash button when soft_delete is enabled. Clicking it shows the trash view (?trash=1) with:
- Restore button — moves the document back to the active list
- Delete permanently button — permanently removes the document (only shown when
access.deleteis configured) - Empty trash button — permanently removes all trashed documents (only shown when
access.deleteis configured)
Delete dialog
The delete button on list rows and the edit sidebar opens a modal dialog:
- Soft-delete collections: Shows “Move to trash” (primary) and “Delete permanently” (danger) buttons
- Hard-delete collections: Shows only “Delete permanently” button
- “Delete permanently” is hidden when the user lacks
access.deletepermission
Retention & Auto-Purge
Set soft_delete_retention to automatically purge expired documents:
soft_delete_retention = "30d" -- purge after 30 days
soft_delete_retention = "7d" -- purge after 7 days
soft_delete_retention = "90d" -- purge after 90 days
The scheduler runs the purge job periodically. Documents with _deleted_at older than the retention period are permanently deleted, including upload file cleanup.
If soft_delete_retention is not set, trashed documents persist indefinitely until manually purged via the admin UI or CLI.
Supported formats: "30d" (days), "24h" (hours), or raw seconds.
API
gRPC
// Soft-delete (default for soft_delete collections)
rpc Delete (DeleteRequest) returns (DeleteResponse);
// Force permanent deletion
DeleteRequest { collection: "posts", id: "abc", force_hard_delete: true }
// Undelete from trash
rpc Undelete (UndeleteRequest) returns (UndeleteResponse);
The DeleteResponse includes a soft_deleted boolean indicating whether the deletion was soft or hard.
Querying trashed documents
Use trash = true on Find and FindByID to access soft-deleted documents:
# List all trashed posts (sorted by deletion date, most recent first)
grpcurl -plaintext -d '{
"collection": "posts",
"trash": true
}' localhost:50051 crap.ContentAPI/Find
# Find a specific trashed document by ID
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"trash": true
}' localhost:50051 crap.ContentAPI/FindByID
When trash = true:
- Only documents with a
_deleted_attimestamp are returned - Default sort is
-_deleted_at(most recently deleted first) access.trashis evaluated (falls back toaccess.update, same as delete/undelete operations). This means users who can only read but not trash/update cannot browse the trash.- Ignored if the collection does not have
soft_delete = true
Lua
-- Soft delete (moves to trash)
crap.collections.posts.delete(id)
-- Force permanent delete
crap.collections.posts.delete(id, { forceHardDelete = true })
-- Undelete from trash
crap.collections.posts.undelete(id)
MCP
MCP delete tools automatically use soft delete when the collection has it enabled.
CLI
# List all trashed documents
crap-cms trash list
# List trashed documents in a specific collection
crap-cms trash list --collection posts
# Restore a document from trash
crap-cms trash restore posts abc123
# Purge all expired documents (respects soft_delete_retention)
crap-cms trash purge
# Purge documents older than 7 days
crap-cms trash purge --older-than 7d
# Dry run — show what would be purged without deleting
crap-cms trash purge --dry-run
# Empty all trash in a collection (requires --confirm)
crap-cms trash empty posts --confirm
Database Schema
When soft_delete = true, a _deleted_at TEXT column is added to the collection table. The value is NULL for active documents and an ISO 8601 timestamp for soft-deleted documents.
All read queries automatically append AND _deleted_at IS NULL to exclude trashed documents. The include_deleted flag on FindQuery overrides this for the trash view.
Notes
- Soft-deleted documents retain all join table data (arrays, blocks, relationships) — nothing is cascaded
- FTS index entries are removed on soft-delete and re-synced on restore
- Upload files are kept on disk until the document is permanently purged
- Version history is preserved through soft-delete and restore
- Back-reference warnings still appear on the delete confirmation for upload/media collections
Fields
Fields define the schema of a collection or global. Each field maps to a SQLite column (except arrays and has-many relationships, which use join tables).
Defining Fields
There are two ways to define fields: factory functions (recommended) and plain tables.
Factory Functions (Recommended)
crap.fields.* functions set the type automatically and return a plain table. Your editor shows only the properties relevant to each field type — no blocks on a text field, no options on a checkbox.
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.select({ name = "status", options = {
{ label = "Draft", value = "draft" },
{ label = "Published", value = "published" },
}}),
crap.fields.relationship({ name = "author", relationship = { collection = "users" } }),
}
Plain Tables
You can also define fields as plain tables with an explicit type key. This is fully supported and equivalent — factories just set type for you.
fields = {
{ name = "title", type = "text", required = true },
{ name = "status", type = "select", options = { ... } },
}
Both syntaxes can be freely mixed in the same fields array.
Why factories? The
types/crap.luafile ships per-type LuaLS classes (e.g.,crap.SelectField,crap.ArrayField). When you usecrap.fields.select({...}), your editor autocompletes only the properties that apply to select fields. With plain tables, the singlecrap.FieldDefinitionclass shows every possible property.
Common Properties
Every field type accepts these properties:
| Property | Type | Default | Description |
|---|---|---|---|
name | string | required | Column name. Must be a valid SQL identifier (alphanumeric + underscore). |
required | boolean | false | Validation: must have a non-empty value on create/update. |
unique | boolean | false | Unique constraint. Checked in the current transaction. For localized fields, enforced per locale. |
index | boolean | false | Create a B-tree index on this column. Skipped when unique = true (already indexed by SQLite). |
localized | boolean | false | Enable per-locale values. Requires localization to be configured. |
validate | string | nil | Lua function ref for custom validation (see below). |
default_value | any | nil | Default value applied on create if no value provided. |
hidden | boolean | false | Strip from all read responses (gRPC, Lua, MCP, admin JSON, REST) and skip in the admin form. Writes are not stripped — internal hooks/Lua can still write the column. For admin-form-only hiding (value still returned by API), use admin.hidden instead. |
admin | table | {} | Admin UI display options. |
hooks | table | {} | Per-field lifecycle hooks. |
access | table | {} | Per-field access control. |
Supported Types
| Type | SQLite Column | Description |
|---|---|---|
text | TEXT | Single-line string (has_many for tag input) |
number | REAL | Integer or float (has_many for tag input) |
textarea | TEXT | Multi-line text |
richtext | TEXT | Rich text (HTML string) |
select | TEXT | Single value from predefined options |
radio | TEXT | Single value from predefined options (radio button UI) |
checkbox | INTEGER | Boolean (0 or 1) |
date | TEXT | Date/datetime/time/month with picker_appearance control |
email | TEXT | Email address |
json | TEXT | Arbitrary JSON blob |
code | TEXT | Code string with syntax-highlighted editor |
relationship | TEXT (has-one) or join table (has-many) | Reference to one or more collections; supports polymorphic (collection = { "posts", "pages" }) |
array | join table | Repeatable group of sub-fields |
group | prefixed columns | Visual grouping of sub-fields (no extra table) |
upload | TEXT (has-one) or join table (has-many) | File reference to upload collection; supports has_many for multi-file |
blocks | join table | Flexible content blocks with different schemas |
join | (none) | Virtual reverse relationship (read-only, computed at read time) |
admin Properties
| Property | Type | Default | Description |
|---|---|---|---|
label | string | table | nil | UI label (defaults to title-cased field name). Supports localized strings. |
placeholder | string | table | nil | Input placeholder text. Supports localized strings. |
description | string | table | nil | Help text displayed below the input. Supports localized strings. |
hidden | boolean | false | Hide from the admin edit form. The field’s value is still returned in API responses (gRPC, Lua, MCP, REST) so consumers and admin widgets (e.g. upload preview, focal-point selector) can read it. For full API stripping, use the top-level hidden field property instead. |
readonly | boolean | false | Display but don’t allow editing |
width | string | nil | Field width: "full" (default), "half", or "third" |
position | string | "main" | Form layout position: "main" or "sidebar" |
condition | string | nil | Lua function ref for conditional visibility (see Conditions) |
step | string | nil | Step attribute for number inputs (e.g., "1", "0.01", "any") |
rows | integer | nil | Visible rows for textarea fields |
collapsed | boolean | true | Default collapsed state for groups, collapsibles, array/block rows |
Layout Wrappers
Row, Collapsible, and Tabs are layout wrappers — they exist only for admin UI grouping. They are transparent at the data layer: sub-fields are promoted as top-level columns with no prefix (unlike Group, which creates prefixed columns).
Nesting
Layout wrappers can be nested inside each other and inside Array/Blocks sub-fields at arbitrary depth:
crap.fields.array({
name = "team_members",
fields = {
crap.fields.tabs({
name = "member_tabs",
tabs = {
{
label = "Personal",
fields = {
crap.fields.row({
name = "name_row",
fields = {
crap.fields.text({ name = "first_name", required = true }),
crap.fields.text({ name = "last_name", required = true }),
},
}),
crap.fields.email({ name = "email" }),
},
},
{
label = "Professional",
fields = {
crap.fields.text({ name = "job_title" }),
},
},
},
}),
},
})
In this example, first_name, last_name, email, and job_title all become flat columns in the {collection}_team_members join table — the Tabs and Row wrappers are invisible at the data and API layer.
All combinations work: Row inside Tabs, Tabs inside Collapsible, Collapsible inside Row, etc.
Depth limit
The admin UI rendering caps layout nesting at 5 levels deep. Beyond this, fields are silently omitted from the form. This limit is a safety guard against infinite recursion — realistic schemas never hit it (5 levels means something like Array → Tabs → Collapsible → Row → Tabs → field).
The data layer (DDL, read, write, versions) has no depth limit.
Custom Validation
The validate property references a Lua function in module.function format. The function receives (value, context) and returns:
nilortrue— validfalse— invalid with a generic messagestring— invalid with a custom error message
-- hooks/validators.lua
local M = {}
function M.min_length_3(value, ctx)
if type(value) == "string" and #value < 3 then
return ctx.field_name .. " must be at least 3 characters"
end
end
return M
-- In field definition:
crap.fields.text({ name = "title", validate = "hooks.validators.min_length_3" })
The context table contains:
| Field | Type | Description |
|---|---|---|
collection | string | Collection slug |
field_name | string | Name of the field being validated |
data | table | Full document data |
user | table/nil | Authenticated user document (nil if unauthenticated) |
ui_locale | string/nil | Admin UI locale code (e.g., "en", "de") |
Text
Single-line string field. The most common field type.
SQLite Storage
TEXT column.
Definition
crap.fields.text({
name = "title",
required = true,
unique = true,
default_value = "Untitled",
admin = {
placeholder = "Enter title",
description = "The display title",
},
})
Multi-Value (has_many)
Store multiple text values as a JSON array in a TEXT column. Renders as a tag-style input in the admin UI.
crap.fields.text({
name = "tags",
has_many = true,
min_length = 2, -- each tag must be at least 2 chars
max_rows = 10, -- at most 10 tags
})
- Values are stored as
["tag1","tag2","tag3"]in the TEXT column min_length/max_lengthvalidate each individual valuemin_rows/max_rowsvalidate the count of values- Duplicate values are prevented in the admin UI
- Type generation maps to
string[]/Vec<String>/list[str]etc.
Admin Rendering
Renders as an <input type="text"> element. When has_many = true, renders as a tag input where users type and press Enter to add chips.
Notes
- Empty strings are stored as
NULLin SQLite - Unknown field types default to
text
Number
Numeric field for integers or floating-point values.
SQLite Storage
REAL column. Empty values are stored as NULL.
Definition
crap.fields.number({
name = "price",
required = true,
default_value = 0,
admin = {
placeholder = "0.00",
},
})
Multi-Value (has_many)
Store multiple numbers as a JSON array in a TEXT column. Renders as a tag-style input in the admin UI.
crap.fields.number({
name = "scores",
has_many = true,
min = 0,
max = 100,
max_rows = 5,
})
- Values are stored as
["10","20","30"]in the TEXT column min/maxvalidate each individual valuemin_rows/max_rowsvalidate the count of values- Type generation maps to
number[]/Vec<f64>/list[float]etc.
Step
Set admin.step to control the number input step attribute:
crap.fields.number({
name = "price",
admin = { step = "0.01" },
})
Valid values: "1" (integers only), "0.01" (cents), "any" (no step constraint). Defaults to browser default ("1").
Admin Rendering
Renders as an <input type="number"> element. When has_many = true, renders as a tag input where users type and press Enter to add number chips.
Value Coercion
String values from form submissions are parsed as f64. If parsing fails, NULL is stored.
Textarea
Multi-line text field for longer content.
SQLite Storage
TEXT column.
Definition
crap.fields.textarea({
name = "description",
admin = {
placeholder = "Enter a description...",
rows = 12,
resizable = false,
},
})
Admin Options
| Option | Type | Default | Description |
|---|---|---|---|
rows | integer | 8 | Number of visible rows |
resizable | boolean | true | Allow vertical resize via drag handle |
Admin Rendering
Renders as a <textarea> element. By default, the textarea is vertically resizable.
Set admin.resizable = false to disable the resize handle.
Rich Text
Rich text field with a ProseMirror-based WYSIWYG editor. Stored as HTML (default) or ProseMirror JSON.
SQLite Storage
TEXT column containing HTML content (default) or ProseMirror JSON document.
Definition
crap.fields.richtext({
name = "content",
admin = {
placeholder = "Write your content...",
},
})
Storage Format
By default, richtext fields store raw HTML. Set admin.format = "json" to store the
ProseMirror document structure as JSON instead:
crap.fields.richtext({
name = "content",
admin = {
format = "json",
},
})
HTML vs JSON
| HTML (default) | JSON | |
|---|---|---|
| Storage | Raw HTML string | ProseMirror doc.toJSON() |
| Round-trip fidelity | Loses some structural info | Lossless |
| Programmatic manipulation | Parse HTML | Walk JSON tree |
| FTS search | Indexed as-is | Plain text extracted automatically |
| API response | HTML string | JSON string |
Important notes
- Changing format does NOT migrate existing data. If you switch from
"html"to"json"(or vice versa), existing documents retain their original format. The editor will attempt to parse the stored content according to the current format setting. - The API returns the stored format as-is (HTML string or JSON string).
- Full-text search automatically extracts plain text from JSON-format richtext fields.
Toolbar Configuration
By default, all toolbar features are enabled. Use admin.features to limit which
features are available:
crap.fields.richtext({
name = "content",
admin = {
features = { "bold", "italic", "heading", "link", "bulletList" },
},
})
Available Features
| Feature | Description |
|---|---|
bold | Bold text (Ctrl+B) |
italic | Italic text (Ctrl+I) |
code | Inline code (Ctrl+`) |
link | Hyperlinks |
heading | H1, H2, H3 headings |
blockquote | Block quotes |
orderedList | Numbered lists |
bulletList | Bullet lists |
codeBlock | Code blocks (```) |
horizontalRule | Horizontal rule |
When features is omitted or empty, all features are enabled (backward compatible).
Undo/redo buttons are always available regardless of feature configuration.
Custom Nodes
Custom ProseMirror nodes let you embed structured components (CTAs, embeds, alerts,
mentions, etc.) inside richtext content. Register nodes in init.lua, then enable
them on specific fields via admin.nodes.
Registration
Node attributes use the same crap.fields.* factory functions as collection fields.
Only scalar types are allowed: text, number, textarea, select, radio,
checkbox, date, email, json, code.
-- init.lua
crap.richtext.register_node("cta", {
label = "Call to Action",
inline = false, -- block-level node
attrs = {
crap.fields.text({ name = "text", required = true, admin = { label = "Button Text" } }),
crap.fields.text({ name = "url", required = true, admin = { label = "URL", placeholder = "https://..." } }),
crap.fields.select({ name = "style", admin = { label = "Style" }, options = {
{ label = "Primary", value = "primary" },
{ label = "Secondary", value = "secondary" },
}}),
},
searchable_attrs = { "text" },
render = function(attrs)
return string.format(
'<a href="%s" class="btn btn--%s">%s</a>',
attrs.url, attrs.style or "primary", attrs.text
)
end,
})
Field configuration
crap.fields.richtext({
name = "content",
admin = {
format = "json",
nodes = { "cta" },
features = { "bold", "italic", "heading", "link", "bulletList" },
},
})
Node spec options
| Option | Type | Description |
|---|---|---|
label | string | Display label (defaults to node name) |
inline | boolean | Inline vs block-level (default: false) |
attrs | table[] | Attribute definitions (see below) |
searchable_attrs | string[] | Attr names included in FTS search index |
render | function | Server-side render function: (attrs) -> html |
Allowed attribute types
Node attrs support all scalar field types. Complex types (array, group, blocks,
relationship, upload, richtext, row, collapsible, tabs, join) are rejected
at registration time.
| Type | Admin Input |
|---|---|
text | Text input |
number | Number input |
textarea | Multi-line textarea |
select | Dropdown with options |
radio | Radio button group |
checkbox | Checkbox |
date | Date picker |
email | Email input |
json | Monospace textarea |
code | Monospace textarea |
Supported attribute features
Node attrs support most field features that make sense in the richtext context.
Admin display hints
These control how attributes appear in the node edit modal:
| Feature | Effect |
|---|---|
admin.hidden | Attribute is not rendered in the modal (value preserved) |
admin.readonly | Input is read-only / disabled |
admin.width | CSS width on the field container (e.g. "50%") |
admin.step | step attribute on number inputs (e.g. "0.01") |
admin.rows | Number of rows for textarea/code/json fields |
admin.language | Language label suffix for code fields (e.g. "JSON") |
admin.placeholder | Placeholder text on inputs |
admin.description | Help text below the input |
min / max | Min/max on number inputs |
min_length / max_length | Minlength/maxlength on text/textarea inputs |
min_date / max_date | Min/max on date inputs |
picker_appearance | Date input type: "dayOnly" (default), "dayAndTime", "timeOnly", "monthOnly" |
Server-side validation
Node attribute values inside richtext content are validated server-side on create/update. The following checks run automatically:
| Check | Description |
|---|---|
required | Attribute must have a non-empty value |
validate | Custom Lua validation function |
min_length / max_length | Text length bounds |
min / max | Numeric bounds |
min_date / max_date | Date bounds |
| email format | Valid email for email type attrs |
| option validity | Value must be in options for select/radio |
Validation errors reference the node location: "content[cta#0].url" (first CTA node’s
url attribute in the content field).
before_validate hooks
Node attrs support hooks.before_validate for normalizing values before validation:
crap.richtext.register_node("cta", {
label = "CTA",
attrs = {
crap.fields.text({
name = "url",
required = true,
hooks = {
before_validate = { "hooks.trim_whitespace" },
},
}),
},
})
The hook receives (value, context) and returns the transformed value. Runs before
validation checks.
Unsupported features
These features have no effect on node attributes and will produce a warning at registration time:
| Feature | Reason |
|---|---|
hooks.before_change | No per-attr write lifecycle |
hooks.after_change | No per-attr write lifecycle |
hooks.after_read | No per-attr read lifecycle |
access (read/create/update) | No per-attr access control |
unique | No DB column |
index | No DB column |
localized | Richtext field itself is localized or not |
mcp.description | Not exposed as MCP fields |
has_many | Doesn’t apply to scalar node attrs |
admin.condition | Not yet supported (deferred) |
Server-side rendering
Use crap.richtext.render(content) in hooks to replace custom nodes with rendered
HTML. The function auto-detects format (JSON or HTML). Custom nodes with a render
function produce the function’s output; nodes without one pass through as
<crap-node> custom elements.
-- In an after_read hook
function hooks.render_content(context)
local doc = context.doc
if doc.content then
doc.content = crap.richtext.render(doc.content)
end
return context
end
FTS search
Custom node attributes listed in searchable_attrs are automatically extracted
for full-text search when the field uses JSON format.
Resize Behavior
By default, the richtext editor is vertically resizable (no max-height constraint). Set
admin.resizable = false to lock it to a fixed height range (200–600px):
crap.fields.richtext({
name = "content",
admin = {
resizable = false,
},
})
Admin Rendering
Renders as a ProseMirror-based rich text editor with a configurable toolbar. When custom nodes are configured, an insert button group appears in the toolbar for each node type. Nodes display as styled cards (block) or pills (inline) in the editor; double-click to edit attributes.
Notes
- No server-side sanitization is applied — sanitize in hooks if needed
- The toolbar configuration only affects the admin UI; it does not validate or strip content server-side
- Custom node names must be alphanumeric with underscores only
Select
Single-value selection from predefined options.
SQLite Storage
TEXT column storing the selected value.
Definition
crap.fields.select({
name = "status",
required = true,
default_value = "draft",
options = {
{ label = "Draft", value = "draft" },
{ label = "Published", value = "published" },
{ label = "Archived", value = "archived" },
},
})
Options Format
Each option is a table with:
| Property | Type | Description |
|---|---|---|
label | string | Display text in the admin UI |
value | string | Stored value in the database |
Multi-Value (has_many)
Allow selecting multiple options. Values are stored as a JSON array in a TEXT column.
crap.fields.select({
name = "categories",
has_many = true,
options = {
{ label = "News", value = "news" },
{ label = "Tech", value = "tech" },
{ label = "Sports", value = "sports" },
},
})
Admin Rendering
Renders as a <select> dropdown. When has_many = true, renders as a multi-select.
Radio
Single-value selection from predefined options, rendered as radio buttons.
SQLite Storage
TEXT column storing the selected value.
Definition
crap.fields.radio({
name = "priority",
required = true,
options = {
{ label = "Low", value = "low" },
{ label = "Medium", value = "medium" },
{ label = "High", value = "high" },
},
})
Options Format
Each option is a table with:
| Property | Type | Description |
|---|---|---|
label | string | Display text in the admin UI |
value | string | Stored value in the database |
Admin Rendering
Renders as a group of radio buttons (one selectable at a time). Functionally identical to Select but with a different UI presentation — use radio when there are few options and you want them all visible at once.
Checkbox
Boolean field stored as an integer (0 or 1).
SQLite Storage
INTEGER column with DEFAULT 0.
Definition
crap.fields.checkbox({
name = "published",
default_value = false,
})
Admin Rendering
Renders as an <input type="checkbox"> element.
Value Coercion
The following string values are treated as true: "on", "true", "1", "yes". Everything else (including absence) is false.
Special Behavior
- Absent checkboxes are always treated as
false(not as a missing/required field) - The
requiredproperty is effectively ignored for checkboxes — an unchecked checkbox is always valid - Default value is
0at the database level
Date
Date, datetime, time, or month field with configurable picker appearance and automatic normalization.
SQLite Storage
TEXT column. Values are normalized on write (see Storage Format below).
Definition
-- Date only (default) — stored as UTC noon to prevent timezone drift
crap.fields.date({ name = "birthday" })
crap.fields.date({ name = "birthday", picker_appearance = "dayOnly" })
-- Date and time — stored as full ISO 8601 UTC
crap.fields.date({ name = "published_at", picker_appearance = "dayAndTime" })
-- Time only — stored as HH:MM
crap.fields.date({ name = "reminder", picker_appearance = "timeOnly" })
-- Month only — stored as YYYY-MM
crap.fields.date({ name = "birth_month", picker_appearance = "monthOnly" })
Picker Appearance
The picker_appearance option controls the HTML input type in the admin UI and how values are stored:
| Value | HTML Input | Storage Format | Example |
|---|---|---|---|
"dayOnly" (default) | <input type="date"> | YYYY-MM-DDT12:00:00.000Z | 2026-01-15T12:00:00.000Z |
"dayAndTime" | <input type="datetime-local"> | YYYY-MM-DDTHH:MM:SS.000Z | 2026-01-15T09:30:00.000Z |
"timeOnly" | <input type="time"> | HH:MM | 14:30 |
"monthOnly" | <input type="month"> | YYYY-MM | 2026-01 |
Date Normalization
All date values are normalized in coerce_value before writing to the database, regardless of how they arrive (admin form or gRPC API):
- Date only (
2026-01-15) →2026-01-15T12:00:00.000Z(UTC noon prevents timezone drift) - Full ISO 8601 (
2026-01-15T09:00:00Z,2026-01-15T09:00:00+05:00) → converted to UTC, formatted asYYYY-MM-DDTHH:MM:SS.000Z - datetime-local (
2026-01-15T09:00) → treated as UTC, formatted asYYYY-MM-DDTHH:MM:SS.000Z - Time only (
14:30) → stored as-is - Month only (
2026-01) → stored as-is
This normalization ensures consistent storage and correct behavior when filtering and sorting.
Admin Rendering
Renders as the appropriate HTML5 input type based on picker_appearance. For dayOnly and dayAndTime, the stored ISO string is automatically converted to the format the HTML input expects (YYYY-MM-DD and YYYY-MM-DDTHH:MM respectively).
Date Constraints
Use min_date and max_date to restrict the allowed range. Values are validated server-side and set as HTML min/max attributes on the input.
crap.fields.date({
name = "event_date",
min_date = "2026-01-01",
max_date = "2026-12-31",
})
Both values use ISO 8601 format. Dates outside the range produce a validation error.
Validation
Non-empty date values are validated against recognized date/datetime/time/month formats. Invalid formats produce a validation error. If min_date or max_date are set, the value is also checked against those bounds.
Timezone Support
Date fields can opt into timezone awareness with timezone = true. This stores the user’s selected IANA timezone in a companion column and converts between local time and UTC automatically.
Enabling
crap.fields.date({
name = "start_date",
picker_appearance = "dayAndTime",
timezone = true,
default_timezone = "America/New_York", -- optional pre-selected timezone
})
Only dayAndTime supports timezones — timezone only makes sense when there’s a time component. Using timezone = true with dayOnly, timeOnly, or monthOnly emits a warning and is ignored.
How It Works
- Admin UI: A timezone dropdown appears next to the date input. The user selects a timezone and enters a local time.
- On save: The local time is converted to UTC using the selected timezone (via
chrono-tz). Both the UTC date and the IANA timezone string are stored. - On reload: The UTC value is converted back to local time for display. The user always sees the time they entered — re-saving without changes produces the same UTC value (no drift).
Storage
Two columns are created:
| Column | Type | Example |
|---|---|---|
start_date | TEXT | 2026-05-02T12:00:00.000Z (UTC) |
start_date_tz | TEXT | America/Sao_Paulo |
The naming follows the pattern {field_name}_tz. Inside Groups, it becomes {group}__{field}_tz.
API Responses
Both fields appear in gRPC and MCP responses:
{
"start_date": "2026-05-02T12:00:00.000Z",
"start_date_tz": "America/Sao_Paulo"
}
The date is always UTC. Frontends convert to local display:
const local = new Date(doc.start_date)
.toLocaleString("en-US", { timeZone: doc.start_date_tz });
Global Default Timezone
Set a default timezone for all date fields in crap.toml:
[admin]
default_timezone = "America/New_York"
This pre-selects the timezone in the admin dropdown for any date field with timezone = true that doesn’t specify its own default_timezone. The field-level setting takes precedence.
Compatibility
- Localized fields: Each locale gets its own
_tzcolumn (e.g.,start_date_tz__en) - Groups / Rows / Tabs / Collapsible / Arrays: Companion columns follow the parent field’s naming rules
- Versioning: Timezone data is included in version snapshots and restored correctly
- Migration: Adding
timezone = trueto an existing field creates the_tzcolumn viaALTER TABLE ADD COLUMNwith NULL default. No data migration needed. - Lua plugins: The
timezoneanddefault_timezoneproperties survive roundtrips throughcrap.collections.config.list()andcrap.collections.define()
Notes
- Pure dates are stored with UTC noon (
T12:00:00.000Z) so timezone offsets up to ±12h never flip the calendar date - When
timezone = truewithdayOnly, noon is calculated in the selected timezone then converted to UTC - Comparison operators (
greater_than,less_than) work correctly on the normalized ISO string representation - The
picker_appearanceoption controls whether the picker shows date-only or date+time
Email address field.
SQLite Storage
TEXT column.
Definition
crap.fields.email({
name = "contact_email",
required = true,
unique = true,
admin = {
placeholder = "user@example.com",
},
})
Admin Rendering
Renders as an <input type="email"> element with browser-native validation.
Auto-Injection
When a collection has auth = true and no email field is defined, one is automatically injected with required = true and unique = true. See Auth Collections.
JSON
Arbitrary JSON data stored as a text blob.
SQLite Storage
TEXT column containing a JSON string.
Definition
crap.fields.json({
name = "metadata",
admin = {
description = "Arbitrary JSON metadata",
},
})
Admin Rendering
Renders as a <textarea> with monospace font for JSON editing.
Notes
- Values are stored as raw JSON strings
- No schema validation is performed on the JSON content
- Use hooks or custom
validatefunctions to enforce structure if needed
Relationship
Reference to documents in another collection. Supports has-one (single reference) and has-many (multiple references via junction table).
Has-One
Stores a single document ID as a TEXT column on the parent table.
crap.fields.relationship({
name = "author",
relationship = {
collection = "users",
has_many = false, -- default
},
})
At depth=0, the field value is a string ID. At depth=1+, it’s replaced with the full document object.
Has-Many
Uses a junction table ({collection}_{field}) with parent_id, related_id, and _order columns.
crap.fields.relationship({
name = "tags",
relationship = {
collection = "tags",
has_many = true,
},
})
At depth=0, the field value is an array of string IDs. At depth=1+, each ID is replaced with the full document object.
Polymorphic Relationships
A relationship field can reference documents from multiple collections by setting collection to a Lua array of slugs instead of a single string.
crap.fields.relationship({
name = "related_content",
relationship = {
collection = { "posts", "pages" },
has_many = false,
},
})
Has-one storage — the column stores a composite string in "collection/id" format (e.g., "posts/abc123"). At depth=0 the raw composite string is returned. At depth=1+ it is replaced with the full document object.
Has-many storage — uses a junction table (same as a regular has-many) with an additional related_collection TEXT column that records which collection each referenced document belongs to.
crap.fields.relationship({
name = "featured_items",
relationship = {
collection = { "posts", "pages", "events" },
has_many = true,
},
})
Admin UI — the relationship picker fetches and displays search results grouped by collection, so editors can find and select documents from any of the target collections in one widget.
Relationship Config
| Property | Type | Default | Description |
|---|---|---|---|
collection | string | string[] | required | Target collection slug, or an array of slugs for polymorphic relationships |
has_many | boolean | false | Use a junction table for many-to-many |
max_depth | integer | nil | Per-field cap on population depth |
Legacy Flat Syntax (Deprecated)
A flat syntax is still supported but deprecated — a warning is logged at startup when it’s used:
-- Deprecated: triggers a warning
crap.fields.relationship({
name = "author",
relation_to = "users",
has_many = false,
})
-- Preferred: use the relationship table
crap.fields.relationship({
name = "author",
relationship = { collection = "users" },
})
The flat syntax does not support max_depth or polymorphic collections. Migrate to the relationship = { ... } table form.
Junction Table Schema
For a has-many field tags on collection posts, the junction table is:
CREATE TABLE posts_tags (
parent_id TEXT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
related_id TEXT NOT NULL,
_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (parent_id, related_id)
);
Admin Rendering
Has-one renders as a searchable input. Has-many renders as a multi-select with chips for selected items.
Drawer Picker
Add admin.picker = "drawer" to enable a browse button next to the search input. Clicking it opens a slide-in drawer panel with a searchable list for browsing documents.
crap.fields.relationship({
name = "author",
relationship = { collection = "users" },
admin = { picker = "drawer" },
})
- Without
picker: inline search autocomplete only (default behavior) - With
picker = "drawer": inline search + browse button that opens a drawer with a scrollable list
Population Depth
See Population Depth for details on controlling how deeply relationships are resolved.
Array
Repeatable group of sub-fields. Each array item is a row in a join table.
Storage
Array fields use a dedicated join table: {collection}_{field}.
The join table has columns:
| Column | Type | Description |
|---|---|---|
id | TEXT PRIMARY KEY | Nanoid for each row |
parent_id | TEXT NOT NULL | Foreign key to the parent document |
_order | INTEGER NOT NULL | Sort order (0-indexed) |
| sub-fields | varies | One column per sub-field |
Definition
crap.fields.array({
name = "slides",
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.text({ name = "image_url" }),
crap.fields.textarea({ name = "caption" }),
},
admin = {
description = "Image slides for the gallery",
},
})
Sub-Fields
Sub-fields support the same properties as regular fields (name, type, required, default_value, admin, etc.). Has-one relationships are supported (stored as a TEXT column in the join table). Nested arrays (array inside array) are not supported.
Layout Wrappers in Sub-Fields
Array sub-fields can be organized with Row, Collapsible, and Tabs layout wrappers. These are transparent — their children become flat columns in the join table, exactly as if they were listed directly in fields.
crap.fields.array({
name = "items",
fields = {
crap.fields.tabs({
name = "item_tabs",
tabs = {
{
label = "Content",
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.textarea({ name = "description" }),
},
},
{
label = "Appearance",
fields = {
crap.fields.select({ name = "color", options = { ... } }),
},
},
},
}),
},
})
The join table gets columns title, description, and color — the Tabs wrapper is invisible at the data layer. Nesting is supported at arbitrary depth (e.g., Row inside Tabs inside Array). See Layout Wrappers for details.
API Representation
In API responses, array fields appear as a JSON array of objects:
{
"slides": [
{ "id": "abc123", "title": "Slide 1", "image_url": "/img/1.jpg", "caption": "First" },
{ "id": "def456", "title": "Slide 2", "image_url": "/img/2.jpg", "caption": "Second" }
]
}
Writing Array Data
Via gRPC, pass an array of objects:
{
"slides": [
{ "title": "Slide 1", "image_url": "/img/1.jpg" },
{ "title": "Slide 2", "image_url": "/img/2.jpg" }
]
}
On write, all existing rows for the parent are deleted and replaced with the new data. This is a full replacement, not a merge.
Row Labels
By default, array rows in the admin UI are labeled with the field label and row index (e.g., “Slides 0”, “Slides 1”). You can customize this with label_field and row_label.
label_field
Set admin.label_field to the name of a sub-field. Its value is used as the row title, and updates live as you type.
crap.fields.array({
name = "slides",
admin = {
label_field = "title",
},
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.text({ name = "image_url" }),
crap.fields.textarea({ name = "caption" }),
},
})
With this configuration, each row shows the title value instead of “Slides 0”.
row_label (Lua function)
For computed labels, set admin.row_label to a Lua function reference. The function receives the row data as a table and returns a display string (or nil to fall back to label_field or the default).
-- collections/products.lua
crap.fields.array({
name = "variants",
admin = {
row_label = "labels.variant_row",
label_field = "name", -- fallback if row_label returns nil
},
fields = {
crap.fields.text({ name = "name", required = true }),
crap.fields.text({ name = "sku" }),
crap.fields.number({ name = "price" }),
},
})
-- hooks/labels.lua
local M = {}
function M.variant_row(row)
local name = row.name or "Untitled"
if row.sku and row.sku ~= "" then
return name .. " (" .. row.sku .. ")"
end
return name
end
return M
Priority
row_labelLua function (if set and returns a non-empty string)label_fieldsub-field value (if set and the field has a value)- Default: field label + row index (e.g., “Slides 0”)
Note:
row_labelis only evaluated server-side. Rows added via JavaScript in the browser fall back tolabel_field(live-updated) or the default until the form is saved and reloaded.
Row Limits (min_rows / max_rows)
Enforce minimum and maximum row counts. These are validation constraints (like required), not just UI hints.
crap.fields.array({
name = "slides",
min_rows = 1,
max_rows = 10,
fields = { ... },
})
min_rows: Minimum number of items. Validated on create/update (skipped for draft saves).max_rows: Maximum number of items. Validated on create/update. The admin UI disables the “Add” button when the limit is reached.
Validation runs in validate_fields(), shared by admin handlers, gRPC, and Lua crap.collections.create()/update().
Default Collapsed State (collapsed)
Existing rows render collapsed by default on page load (admin.collapsed = true). Set admin.collapsed = false to start rows expanded. New rows added via the “Add” button are always expanded.
crap.fields.array({
name = "slides",
admin = {
collapsed = false, -- start rows expanded (default is true)
},
fields = { ... },
})
Custom Labels (labels)
Customize the “Add Row” button text and field header with singular/plural labels.
crap.fields.array({
name = "slides",
admin = {
labels = { singular = "Slide", plural = "Slides" },
},
fields = { ... },
})
With this config, the add button reads “Add Slide” instead of “Add Row”.
Admin Rendering
Renders as a repeatable fieldset with:
- Drag handle for drag-and-drop reordering
- Row count badge showing the number of items
- Toggle collapse/expand all button
- Each row has expand/collapse toggle, move up/down, duplicate, and remove buttons
- “No items yet” empty state when no rows exist
- “Add Row” button (or custom label) to append new rows
- Add button disabled when
max_rowsis reached
Group
Visual grouping of sub-fields. Sub-fields become prefixed columns on the parent table (no join table).
Storage
Group fields do not create their own column. Instead, each sub-field becomes a column with a double-underscore prefix: {group}__{sub}.
For example, a group named seo with sub-fields title and description creates columns:
seo__title TEXTseo__description TEXT
Definition
crap.fields.group({
name = "seo",
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.textarea({ name = "description" }),
crap.fields.checkbox({ name = "no_index" }),
},
admin = {
description = "Search engine optimization settings",
},
})
Sub-Fields
Sub-fields support the same properties as regular fields (name, type, required, default_value, admin, etc.), including nested groups, arrays, blocks, and relationships.
- Nested groups use stacked prefixes:
outer__inner__field. - Arrays/Blocks inside groups create prefixed join tables:
{collection}_{group}__{field}. - Relationships inside groups create prefixed junction tables (for has-many) or prefixed columns (for has-one).
API Representation
In API responses (after hydration), group fields appear as a nested object:
{
"seo": {
"title": "My Page Title",
"description": "A page about...",
"no_index": 0
}
}
Writing Group Data
Via gRPC, pass the flat prefixed keys:
{
"seo__title": "My Page Title",
"seo__description": "A page about..."
}
The double-underscore separator is used in all write operations (forms, gRPC). On read, the prefixed columns are reconstructed into a nested object.
Filtering on Group Sub-Fields
Use dot notation to filter on group sub-fields. The dot syntax is converted to the double-underscore column name internally.
crap.collections.pages.find({
where = {
["seo.title"] = { contains = "SEO" },
["seo.no_index"] = "0",
},
})
The equivalent double-underscore syntax also works: seo__title.
See Query & Filters for filtering on other nested field types (arrays, blocks, relationships).
Admin Rendering
Renders as a <fieldset> with a legend. Each sub-field is rendered using its own field type template (text, checkbox, select, etc.).
Row
Layout-only grouping of sub-fields. Unlike Group, sub-fields are promoted as top-level columns with no prefix.
Storage
Row fields do not create their own column. Each sub-field becomes a top-level column using its plain name — no prefix is added.
For example, a row with sub-fields firstname and lastname creates columns:
firstname TEXTlastname TEXT
This is different from Group, which prefixes sub-field columns (seo__title).
Definition
crap.fields.row({
name = "name_row",
fields = {
crap.fields.text({ name = "firstname", required = true }),
crap.fields.text({ name = "lastname", required = true }),
},
})
API Representation
In API responses, row sub-fields appear as flat top-level fields (not nested):
{
"firstname": "Jane",
"lastname": "Doe"
}
Writing Row Data
Use the plain sub-field names directly — no prefix needed:
{
"firstname": "Jane",
"lastname": "Doe"
}
Nesting
Row can be nested inside other layout wrappers (Tabs, Collapsible) and inside Array/Blocks sub-fields at arbitrary depth. All nesting combinations work — see the Layout Wrappers section for details and examples.
Depth limit: The admin UI caps layout nesting at 5 levels. The data layer has no limit.
Admin Rendering
Sub-fields are rendered in a horizontal row layout. The row itself has no fieldset, legend, or collapsible wrapper — it is purely a layout mechanism for placing related fields side by side.
Collapsible
Layout-only collapsible container for sub-fields. Like Row, sub-fields are promoted as top-level columns with no prefix. Unlike Group, which creates prefixed columns (group__subfield), Collapsible is purely a UI container.
Storage
Collapsible fields do not create their own column. Each sub-field becomes a top-level column using its plain name — no prefix is added. This is identical to Row storage.
For example, a collapsible with sub-fields meta_title and meta_description creates columns:
meta_title TEXTmeta_description TEXT
Definition
crap.fields.collapsible({
name = "seo_section",
admin = {
label = "SEO Settings",
-- collapsed defaults to true; set false to start expanded
-- collapsed = false,
},
fields = {
crap.fields.text({ name = "meta_title" }),
crap.fields.textarea({ name = "meta_description" }),
},
})
API Representation
In API responses, collapsible sub-fields appear as flat top-level fields (not nested):
{
"meta_title": "My Page Title",
"meta_description": "A description for search engines"
}
Writing Data
Use the plain sub-field names directly — no prefix needed:
{
"meta_title": "My Page Title",
"meta_description": "A description for search engines"
}
Nesting
Collapsible can be nested inside other layout wrappers (Tabs, Row) and inside Array/Blocks sub-fields at arbitrary depth. All nesting combinations work — see the Layout Wrappers section for details and examples.
Depth limit: The admin UI caps layout nesting at 5 levels. The data layer has no limit.
Admin Rendering
Sub-fields are rendered inside a collapsible section with a toggle header. The section starts collapsed by default (admin.collapsed = true). Set admin.collapsed = false to start expanded. Clicking the header toggles visibility. This is useful for grouping related fields that don’t need to be visible at all times (e.g., SEO settings, advanced options).
Comparison with Group and Row
| Feature | Group | Row | Collapsible |
|---|---|---|---|
| Column prefix | group__subfield | none | none |
| API nesting | nested object | flat | flat |
| Admin layout | collapsible fieldset | horizontal row | collapsible section |
| Use case | Namespaced fields | Side-by-side fields | Toggleable sections |
Tabs
Layout-only tabbed container for sub-fields. Like Row and Collapsible, sub-fields across all tabs are promoted as top-level columns with no prefix.
Storage
Tabs fields do not create their own column. Each sub-field across all tabs becomes a top-level column using its plain name — no prefix is added. This is identical to Row storage.
For example, tabs with sub-fields title, body, meta_title, and meta_description creates columns:
title TEXTbody TEXTmeta_title TEXTmeta_description TEXT
Definition
crap.fields.tabs({
name = "content_tabs",
tabs = {
{
label = "Content",
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.richtext({ name = "body" }),
},
},
{
label = "SEO",
description = "Search engine optimization settings",
fields = {
crap.fields.text({ name = "meta_title" }),
crap.fields.textarea({ name = "meta_description" }),
},
},
},
})
Each tab has:
label(required) — the tab button textdescription(optional) — help text shown inside the tab panelfields— array of field definitions (same syntax as any other field list)
API Representation
In API responses, all tab sub-fields appear as flat top-level fields (not nested by tab):
{
"title": "My Post",
"body": "<p>Content here</p>",
"meta_title": "My Post | Blog",
"meta_description": "Read about my post"
}
Writing Data
Use the plain sub-field names directly — tabs are invisible at the data layer:
{
"title": "My Post",
"body": "<p>Content here</p>",
"meta_title": "My Post | Blog",
"meta_description": "Read about my post"
}
Nesting
Tabs can be nested inside other layout wrappers (Row, Collapsible) and inside Array/Blocks sub-fields at arbitrary depth. Tab fields can themselves contain Row, Collapsible, or nested Tabs. All nesting combinations work — see the Layout Wrappers section for details and examples.
Depth limit: The admin UI caps layout nesting at 5 levels. The data layer has no limit.
Admin Rendering
Sub-fields are organized into tabs with a tab bar at the top. The first tab is active by default. Clicking a tab button switches the visible panel. Each tab can have its own description text.
Comparison with Other Layout Types
| Feature | Group | Row | Collapsible | Tabs |
|---|---|---|---|---|
| Column prefix | group__subfield | none | none | none |
| API nesting | nested object | flat | flat | flat |
| Admin layout | collapsible fieldset | horizontal row | collapsible section | tabbed panels |
| Use case | Namespaced fields | Side-by-side fields | Toggleable sections | Organized sections |
Code
Code editor field stored as a plain text string. Renders a CodeMirror 6 editor in the admin UI with syntax highlighting and language-aware features.
SQLite Storage
TEXT column containing the raw code string. When the optional editor-time
language picker is enabled (see below), a companion <name>_lang TEXT column
stores the editor’s per-document language pick.
Definition
crap.fields.code({
name = "metadata",
admin = {
language = "json", -- "json", "javascript", "html", "css", "python", or "plain"
},
})
Admin Options
| Property | Type | Default | Description |
|---|---|---|---|
admin.language | string | "json" | Default language mode for syntax highlighting. |
admin.languages | string[] | [] | Optional allow-list. When non-empty, the form renders a language picker next to the editor and persists the choice per document in a <name>_lang companion column. |
Supported Languages
| Value | Language |
|---|---|
json | JSON |
javascript or js | JavaScript |
html | HTML |
css | CSS |
python or py | Python |
plain | No syntax highlighting |
Per-document language picker
When the document being edited may contain code in different languages
(e.g. an “examples” collection with one block holding JS and the next
holding Python), set admin.languages to the allow-list of choices.
The form then renders a small <select> next to the editor; changing it
swaps the editor’s syntax highlighting and stores the pick in the
companion column so it persists across edits.
crap.fields.code({
name = "snippet",
admin = {
language = "javascript", -- initial / fallback
languages = { "javascript", "python", "html" }, -- editor-pickable list
},
})
The companion column is named <field>_lang (e.g. snippet_lang) and is
created automatically on the next migration. For code fields nested inside
groups, the prefixed naming applies — meta__snippet gets a sibling
meta__snippet_lang.
When admin.languages is empty or absent, the language is fixed to
admin.language and no picker, hidden input, or companion column is
emitted.
Admin Rendering
Renders as a CodeMirror 6 editor with line numbers, bracket matching, code folding, auto-completion, and search. Falls back to a plain <textarea> if the CodeMirror bundle is not loaded.
Notes
- Content is stored as a raw string (not parsed or validated for syntax)
- Supports
min_lengthandmax_lengthvalidation (applied to the raw string) - The CodeMirror bundle (
static/codemirror.js) is loaded via<script defer>in the admin layout - To rebuild the bundle:
bash scripts/bundle-codemirror.sh - The language picker (when enabled) is rendered inside the
<crap-code>shadow root and styled by the same input tokens as the rest of the admin (--input-bg,--input-border,--text-primary).
Join
A virtual, read-only field that displays documents from another collection that reference the current document. No data is stored — results are computed at read time by querying the target collection.
Lua Definition
crap.fields.join({ name = "posts", collection = "posts", on = "author" })
This reads as: “Show me all documents in the posts collection where posts.author equals this document’s ID.”
Properties
| Property | Type | Required | Description |
|---|---|---|---|
name | string | yes | Field name (display only, no column created) |
type | "join" | yes | Must be "join" |
collection | string | yes | Target collection slug to query |
on | string | yes | Field name on the target collection that holds the reference |
Behavior
- No database column — join fields are virtual. No migration, no storage.
- Read-only — displayed in the admin UI but not editable. No form input is rendered.
- No validation — since no data is submitted, validation is skipped entirely.
- Admin UI — shows a list of linked documents with clickable links to edit each one. Displays “No related items” when empty.
- API responses — at
depth >= 1, join fields return an array of document objects from the target collection. Atdepth = 0, join fields are omitted (no stored value).
Example
Given an authors collection and a posts collection where each post has a relationship field called author:
-- collections/authors.lua
return {
slug = "authors",
fields = {
crap.fields.text({ name = "name", required = true }),
crap.fields.join({ name = "posts", collection = "posts", on = "author" }),
},
}
When editing an author, the “posts” join field displays all posts where posts.author equals the current author’s ID.
Upload
File reference field. Stores a relationship to an upload collection. Supports both single-file (has-one) and multi-file (has-many) modes.
Storage
- Has-one (default): stores the referenced media document’s ID in a TEXT column on the parent table.
- Has-many (
has_many = true): stores references in a junction table{collection}_{field}, same as has-many relationships.
Definition
Single file (has-one):
crap.fields.upload({
name = "featured_image",
relationship = {
collection = "media",
max_depth = 1,
},
})
Multi-file (has-many):
crap.fields.upload({
name = "gallery",
relationship = {
collection = "media",
has_many = true,
},
})
Note: The flat
relation_tosyntax is deprecated for upload fields too. Userelationship = { collection = "..." }instead.
The target collection should be an upload collection (defined with upload = true).
API Representation
Has-one
At depth=0, returns the media document ID as a string:
{
"featured_image": "abc123"
}
At depth=1+, the ID is populated with the full media document (same as relationship population):
{
"featured_image": {
"id": "abc123",
"collection": "media",
"filename": "hero.jpg",
"mime_type": "image/jpeg",
"url": "/uploads/media/hero.jpg",
"sizes": { ... }
}
}
Has-many
At depth=0, returns an array of media document IDs:
{
"gallery": ["abc123", "def456"]
}
At depth=1+, each ID is populated with the full media document:
{
"gallery": [
{ "id": "abc123", "collection": "media", "filename": "hero.jpg", ... },
{ "id": "def456", "collection": "media", "filename": "banner.png", ... }
]
}
Admin Rendering
- Has-one: renders as a searchable input with filename as the display label and image preview above.
- Has-many: renders as a searchable multi-select widget (same as has-many relationships) with chips for selected files.
Drawer Picker
Upload fields default to picker = "drawer", which shows a browse button next to the search input. Clicking it opens a slide-in drawer panel with a thumbnail grid for visually browsing upload documents.
-- drawer is the default for upload fields — no need to set it explicitly
crap.fields.upload({
name = "featured_image",
relationship = {
collection = "media",
},
})
- Default (
picker = "drawer"): inline search + browse button that opens a drawer with thumbnail grid picker = "none": inline search autocomplete only (no browse button)
Blocks
Flexible content field with multiple block types. Each block type has its own schema. Stored in a join table with JSON data.
Storage
Blocks fields use a dedicated join table: {collection}_{field}.
The join table has columns:
| Column | Type | Description |
|---|---|---|
id | TEXT PRIMARY KEY | Nanoid for each row |
parent_id | TEXT NOT NULL | Foreign key to the parent document |
_order | INTEGER NOT NULL | Sort order (0-indexed) |
_block_type | TEXT NOT NULL | Block type identifier |
data | TEXT NOT NULL | JSON object containing the block’s field values |
Unlike arrays (which have typed columns per sub-field), blocks use a single JSON data column because each block type can have a different schema.
Definition
crap.fields.blocks({
name = "content",
blocks = {
{
type = "hero",
label = "Hero Section",
fields = {
crap.fields.text({ name = "heading", required = true }),
crap.fields.text({ name = "subheading" }),
crap.fields.text({ name = "image_url" }),
},
},
{
type = "richtext",
label = "Rich Text",
fields = {
crap.fields.richtext({ name = "body" }),
},
},
{
type = "cta",
label = "Call to Action",
fields = {
crap.fields.text({ name = "text", required = true }),
crap.fields.text({ name = "url", required = true }),
crap.fields.select({ name = "style", options = {
{ label = "Primary", value = "primary" },
{ label = "Secondary", value = "secondary" },
}}),
},
},
},
})
Layout Wrappers in Block Fields
Block sub-fields can be organized with Row, Collapsible, and Tabs layout wrappers. Since blocks store data as JSON, wrappers are transparent at the data layer — their children appear as flat keys in the JSON object.
blocks = {
{
type = "feature_card",
label = "Feature Card",
fields = {
crap.fields.tabs({
name = "card_tabs",
tabs = {
{
label = "Content",
fields = {
crap.fields.text({ name = "heading", required = true }),
crap.fields.textarea({ name = "body" }),
},
},
{
label = "Style",
fields = {
crap.fields.select({ name = "variant", options = { ... } }),
},
},
},
}),
},
},
}
The JSON data contains heading, body, and variant as flat keys — the Tabs wrapper is invisible. Nesting is supported at arbitrary depth. See Layout Wrappers for details.
Block Definitions
Each block definition has:
| Property | Type | Description |
|---|---|---|
type | string | Required. Block type identifier. |
label | string | Display label (defaults to type name). |
label_field | string | Sub-field name to use as row label for this block type. |
group | string | Group name for organizing blocks in the picker dropdown. |
image_url | string | Image URL for icon/thumbnail in the block picker. |
fields | FieldDefinition[] | Fields within this block type. |
API Representation
In API responses, blocks fields appear as a JSON array of objects, each with _block_type and the block’s field values:
{
"content": [
{
"id": "abc123",
"_block_type": "hero",
"heading": "Welcome",
"subheading": "To our site"
},
{
"id": "def456",
"_block_type": "richtext",
"body": "<p>Some content...</p>"
}
]
}
Writing Blocks Data
Via gRPC, pass an array of objects with _block_type:
{
"content": [
{ "_block_type": "hero", "heading": "Welcome", "subheading": "To our site" },
{ "_block_type": "richtext", "body": "<p>Content here</p>" }
]
}
On write, all existing block rows for the parent are deleted and replaced. This is a full replacement, not a merge.
Row Labels
By default, block rows display the block type label and row index (e.g., “Hero Section 0”). You can customize this per block type with label_field, or across all block types with row_label.
Per-Block label_field
Set label_field on each block definition to a sub-field name. The value of that field is used as the row title, and updates live as you type.
crap.fields.blocks({
name = "content",
blocks = {
{
type = "hero",
label = "Hero Section",
label_field = "heading",
fields = {
crap.fields.text({ name = "heading", required = true }),
crap.fields.text({ name = "subheading" }),
},
},
{
type = "image",
label = "Image",
label_field = "caption",
fields = {
crap.fields.upload({ name = "image", relationship = { collection = "media" } }),
crap.fields.text({ name = "caption" }),
},
},
},
})
Each block type can have a different label_field — hero blocks show the heading, image blocks show the caption.
row_label (Lua function)
For computed labels across all block types, set admin.row_label on the blocks field. The function receives the full row data (including _block_type) and returns a display string.
-- collections/posts.lua
crap.fields.blocks({
name = "content",
admin = {
row_label = "labels.content_block_row",
},
blocks = { ... },
})
-- hooks/labels.lua
local M = {}
function M.content_block_row(row)
if row._block_type == "hero" then
return "Hero: " .. (row.heading or "Untitled")
elseif row._block_type == "code" then
local lang = row.language or ""
if lang ~= "" then return "Code (" .. lang .. ")" end
return "Code"
end
return nil -- fall back to per-block label_field or default
end
return M
Priority
row_labelLua function (if set and returns a non-empty string)- Per-block
label_fieldon theBlockDefinition - Field-level
admin.label_field(shared across all block types) - Default: block type label + row index (e.g., “Hero Section 0”)
Note:
row_labelis only evaluated server-side. Rows added via JavaScript in the browser fall back tolabel_field(live-updated) or the default until the form is saved and reloaded.
Row Limits (min_rows / max_rows)
Enforce minimum and maximum block counts. These are validation constraints, not just UI hints.
crap.fields.blocks({
name = "content",
min_rows = 1,
max_rows = 20,
blocks = { ... },
})
min_rows: Minimum number of blocks. Validated on create/update (skipped for draft saves).max_rows: Maximum number of blocks. Validated on create/update. The admin UI disables the “Add Block” button when the limit is reached.
Default Collapsed State (collapsed)
Existing block rows render collapsed by default on page load (admin.collapsed = true). Set admin.collapsed = false to start rows expanded. New blocks added via the UI are always expanded.
crap.fields.blocks({
name = "content",
admin = {
collapsed = false, -- start rows expanded (default is true)
},
blocks = { ... },
})
Custom Labels (labels)
Customize the “Add Block” button text with singular/plural labels.
crap.fields.blocks({
name = "content",
admin = {
labels = { singular = "Section", plural = "Sections" },
},
blocks = { ... },
})
With this config, the add button reads “Add Section” instead of “Add Block”.
Block Groups
Organize blocks into groups in the picker dropdown using <optgroup> elements. Ungrouped blocks appear at the top.
crap.fields.blocks({
name = "content",
blocks = {
{
type = "hero",
label = "Hero Section",
group = "Layout",
fields = { ... },
},
{
type = "columns",
label = "Columns",
group = "Layout",
fields = { ... },
},
{
type = "richtext",
label = "Rich Text",
group = "Content",
fields = { ... },
},
{
type = "divider",
label = "Divider",
-- No group: appears at the top of the dropdown
fields = {},
},
},
})
Card Picker
By default, blocks use a dropdown select to choose the block type. Set admin.picker = "card" to use a visual card grid instead. This is useful when you have several block types and want a more visual picker.
crap.fields.blocks({
name = "content",
admin = {
picker = "card",
},
blocks = {
{
type = "hero",
label = "Hero Section",
fields = { ... },
},
{
type = "richtext",
label = "Rich Text",
fields = { ... },
},
},
})
Each card shows the block type label and a generic icon. To display custom icons or thumbnails, set image_url on individual block definitions:
blocks = {
{
type = "hero",
label = "Hero Section",
image_url = "/static/blocks/hero.svg",
fields = { ... },
},
{
type = "richtext",
label = "Rich Text",
image_url = "/static/blocks/text.svg",
fields = { ... },
},
}
Blocks without an image_url show a generic widget icon. Both group and image_url can be combined with the card picker.
Admin Rendering
Renders as a repeatable fieldset with:
- Drag handle for drag-and-drop reordering
- Row count badge showing the number of blocks
- Toggle collapse/expand all button
- Block type selector dropdown with “Add Block” button (or custom label)
- Each row shows the block type label (or custom label), move up/down, duplicate, and remove buttons
- “No items yet” empty state when no blocks exist
- Block-specific fields rendered within each row
- Add button disabled when
max_rowsis reached
Globals
Globals are single-document collections for site-wide settings. Each global stores exactly one row.
Definition
Define globals in globals/*.lua using crap.globals.define():
-- globals/site_settings.lua
crap.globals.define("site_settings", {
labels = {
singular = "Site Settings",
},
fields = {
crap.fields.text({ name = "site_name", required = true, default_value = "My Site" }),
crap.fields.text({ name = "tagline" }),
},
})
Config Properties
| Property | Type | Default | Description |
|---|---|---|---|
labels | table | {} | Display names |
labels.singular | string | slug | Singular name (e.g., “Site Settings”) |
labels.plural | string | slug | Plural name |
fields | FieldDefinition[] | {} | Field definitions |
hooks | table | {} | Same lifecycle hooks as collections |
access | table | {} | Same access control as collections |
versions | boolean or table | nil | Versioning config (same as collections) |
live | boolean or string | nil | Live update broadcasting (same as collections) |
mcp | table | {} | MCP tool config. { description = "..." } |
Database Table
Each global gets a table named _global_{slug} with a single row where id = 'default'. The row is auto-created on startup.
Globals always have created_at and updated_at timestamp columns.
Differences from Collections
| Feature | Collections | Globals |
|---|---|---|
| Documents | Multiple | Exactly one |
| Table name | {slug} | _global_{slug} |
| CRUD operations | find, find_by_id, create, update, delete | get, update |
| Timestamps | Optional (timestamps = true) | Always enabled |
| Auth / Upload | Supported | Not supported |
| Versions | Supported | Supported |
| Live updates | Supported | Supported |
| MCP | Supported | Supported |
Lua API
-- Get current value
local settings = crap.globals.site_settings.get()
print(settings.site_name)
-- Update
crap.globals.site_settings.update({
site_name = "New Name",
tagline = "A fresh start",
})
gRPC API
# Get
grpcurl -plaintext -d '{"slug": "site_settings"}' \
localhost:50051 crap.ContentAPI/GetGlobal
# Update
grpcurl -plaintext -d '{
"slug": "site_settings",
"data": {"site_name": "Updated Site"}
}' localhost:50051 crap.ContentAPI/UpdateGlobal
Relationships
Relationship fields reference documents in other collections. Crap CMS supports two relationship types:
Has-One
A single reference stored as a TEXT column containing the related document’s ID.
crap.fields.relationship({
name = "author",
relationship = {
collection = "users",
},
})
At depth=0 (default for Find):
{ "author": "user_abc123" }
At depth=1:
{
"author": {
"id": "user_abc123",
"collection": "users",
"name": "Admin User",
"email": "admin@example.com",
"created_at": "2024-01-01 00:00:00"
}
}
Has-Many
Multiple references stored in a junction table ({collection}_{field}).
crap.fields.relationship({
name = "tags",
relationship = {
collection = "tags",
has_many = true,
},
})
At depth=0:
{ "tags": ["tag_1", "tag_2", "tag_3"] }
At depth=1:
{
"tags": [
{ "id": "tag_1", "collection": "tags", "name": "Rust" },
{ "id": "tag_2", "collection": "tags", "name": "CMS" },
{ "id": "tag_3", "collection": "tags", "name": "Lua" }
]
}
Writing Relationships
Has-One
Set the field to the related document’s ID:
{ "author": "user_abc123" }
Has-Many
Pass an array of IDs:
{ "tags": ["tag_1", "tag_2", "tag_3"] }
Order is preserved via the _order column in the junction table.
When a has-many field is included in the update payload, all existing junction rows for the parent are deleted and replaced with the new list — a full replacement of that field’s targets.
Partial Updates
For has-many fields, if the field is absent from the update data, the junction table is not modified. This supports partial updates — only explicitly included fields are changed.
Delete Protection
Every collection table has a _ref_count column that tracks how many documents reference it. When _ref_count > 0, the document cannot be deleted — this prevents orphaned references across collections.
How It Works
When document A has a relationship field pointing to document B, B’s _ref_count is incremented. When A is updated to point elsewhere or hard-deleted, B’s _ref_count is decremented. This makes delete protection an O(1) check — no scanning required.
Reference counting covers all relationship types:
| Type | Storage | Tracked |
|---|---|---|
| Has-one relationship | Column on parent table | Yes |
| Has-many relationship | Junction table | Yes |
| Polymorphic (has-one/many) | collection/id format | Yes |
| Localized relationships | Per-locale columns | Yes |
| Upload fields | Same as relationship | Yes |
| Array sub-field refs | Column in array table | Yes |
| Block sub-field refs | JSON in blocks table | Yes |
| Global outgoing refs | Global table columns | Yes |
Scope
Delete protection applies to all collections, not just uploads. Any document referenced by another document is protected.
Soft Delete Interaction
Soft-deleting a document does not adjust ref counts. The outgoing references remain counted because:
- Soft-deleted documents can be restored, so their references should remain tracked
- Trashed documents still “own” their references in the database
Only hard deletion (permanent) decrements ref counts on the targets.
The ref count check only blocks deletion of a target: a document can always be soft-deleted regardless of how many others reference it.
When a referenced document is soft-deleted, it is omitted from relationship population on read — it does not appear as an ID string or as a populated object. Has-one fields resolve to null; has-many fields have the soft-deleted entry dropped from the array. Restore the document to make it appear again.
Admin UI
The delete confirmation page shows a warning when a document has _ref_count > 0:
This document is referenced by other content. Referenced by 3 document(s). [Show details]
Clicking Show details lazy-loads the full list of referencing documents, fields, and counts via the back-references API endpoint.
API Behavior
Admin & gRPC
Attempting to delete a document with _ref_count > 0 returns an error:
Cannot delete '<id>' from '<collection>': referenced by N document(s)
Lua API
-- Single delete: fails with error if referenced
local ok, err = pcall(crap.collections.delete, "media", "m1")
-- Bulk delete: skips referenced documents and reports the count
local result = crap.collections.media.delete_many({
where = { status = { equals = "unused" } }
})
-- result.deleted = documents actually deleted
-- result.skipped = documents skipped due to outstanding references
Force Hard Delete
The forceHardDelete option bypasses the ref count check. This is used internally for Empty Trash operations and can be used in Lua hooks:
crap.collections.media.delete("m1", {
forceHardDelete = true -- skips ref count check
})
Back-References API
To see which documents reference a target, use the back-references endpoint:
GET /admin/collections/{slug}/{id}/back-references
Returns a JSON array:
[
{
"owner_slug": "posts",
"owner_label": "Posts",
"field_name": "image",
"field_label": "Image",
"document_ids": ["p1", "p2"],
"count": 2,
"is_global": false
}
]
This endpoint performs the full back-reference scan, so it’s heavier than the ref count check. It’s designed for on-demand use (e.g., the “Show details” button).
Migration
When upgrading to a version with reference counting, the _ref_count column is automatically added to all collection and global tables. A one-time backfill migration computes the initial counts from existing relationship data. This runs automatically on first startup and is gated by a _crap_meta flag so it only runs once.
Population Depth
The depth parameter controls how deeply relationship fields are populated with full document objects.
Depth Values
| Depth | Behavior |
|---|---|
0 | IDs only. Has-one = string ID. Has-many = array of string IDs. |
1 | Populate immediate relationships. Replace IDs with full document objects. |
2+ | Recursively populate relationships within populated documents. |
Defaults
| Operation | Default Depth |
|---|---|
Find (gRPC) | 0 (avoids N+1 on list queries) |
FindByID (gRPC) | depth.default_depth from crap.toml (default: 1) |
crap.collections.find() (Lua) | 0 |
crap.collections.find_by_id() (Lua) | 0 |
Configuration
Global Config
[depth]
default_depth = 1 # Default for FindByID (default: 1)
max_depth = 10 # Hard cap for all requests (default: 10)
Per-Field Max Depth
Cap the depth for a specific relationship field, regardless of the request-level depth:
crap.fields.relationship({
name = "author",
relationship = {
collection = "users",
max_depth = 1, -- never populate deeper than 1, even if depth=5
},
})
Usage
gRPC
# Find with depth=1
grpcurl -plaintext -d '{
"collection": "posts",
"depth": 1
}' localhost:50051 crap.ContentAPI/Find
# FindByID with depth=2
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"depth": 2
}' localhost:50051 crap.ContentAPI/FindByID
Lua API
-- Find with depth
local result = crap.collections.posts.find({ depth = 1 })
-- FindByID with depth
local post = crap.collections.posts.find_by_id(id, { depth = 2 })
Circular Reference Protection
The population algorithm tracks visited (collection, id) pairs. If a document has already been visited in the current recursion path, it’s kept as a plain ID string instead of being populated again.
This prevents infinite loops when collections reference each other (e.g., posts → users → posts).
Performance
Population adds queries beyond the main find/find_by_id. How many depends on the depth and number of relationship fields.
How It Works
- Batch fetching:
Findwithdepth >= 1collects all referenced IDs across all returned documents per relationship field and fetches them in a singleIN (...)query. This means one extra query per relationship field, regardless of how many documents reference it. - Recursive batching: At
depth >= 2, the same batch strategy applies recursively — populated documents’ relationships are batch-fetched at each depth level. - Per-document fetching:
FindByIDpopulates a single document. Join fields (reverse lookups) also use per-document queries since they require aWHEREclause per parent.
Query Cost
| Scenario | Extra Queries |
|---|---|
depth=0 | 0 |
depth=1, Find returning N docs, M relationship fields | M queries (one batch per field) |
depth=1, FindByID, M relationship fields | M queries |
depth=2, Find, M fields at level 1, K fields at level 2 | M + (M × K) queries |
Join fields add one query per document per join field at each depth level.
Cache Backend
A pluggable cache backend avoids redundant population queries across requests. The default memory backend caches populated documents in-process using DashMap. For multi-server deployments, use redis for a shared cache. The cache is automatically cleared on any write operation (create, update, delete).
[cache]
backend = "memory" # "memory" (default), "redis", "none", "custom"
max_entries = 10000 # Soft cap for memory backend
max_age_secs = 60 # Optional: periodic full cache clear (default: 0 = off)
Backends:
"memory"— In-process DashMap with soft entry cap. Default. Good for single-server."redis"— Shared Redis cache. Requires--features redis. Good for multi-server."none"— Cache disabled. Each request creates its own temporary cache (no cross-request sharing)."custom"— Lua-delegated (planned, not yet implemented).
Trade-off: If the database is modified outside the API (e.g., direct SQL, external tools), cached data can become stale. Set max_age_secs to limit staleness, or use backend = "none" to disable.
Recommendations
- Use
depth=0for list endpoints.Finddefaults todepth=0for this reason. Fetch related data when displaying a single document instead. - Use
selectto limit populated fields. Non-selected relationship fields are skipped entirely during population. - Set per-field
max_depthon relationship fields that don’t need deep population. - If you need related data in a list, use
depth=1withselectto populate only the specific relationship fields you need.
Query & Filters
Unified reference for querying documents across both the Lua API and gRPC API.
Note on soft-deleted rows: collections with
soft_delete = trueautomatically exclude rows where_deleted_at IS NOT NULLfromFind,Count, and populate. Filters on system columns (names starting with_) are rejected. Use the request-leveltrash = true/draft = trueflags to reach internally-scoped data.
Filter Operators
| Operator | Lua | gRPC (where) | SQL |
|---|---|---|---|
| Equals | status = "published" or { equals = "val" } | {"equals": "val"} | field = ? |
| Not equals | { not_equals = "val" } | {"not_equals": "val"} | field != ? |
| Like | { like = "pattern%" } | {"like": "pattern%"} | field LIKE ? |
| Contains | { contains = "text" } | {"contains": "text"} | field LIKE '%text%' ESCAPE '\' (wildcards % and _ in the search text are escaped) |
| Greater than | { greater_than = "10" } | {"greater_than": "10"} | field > ? |
| Less than | { less_than = "10" } | {"less_than": "10"} | field < ? |
| Greater/equal | { greater_than_or_equal = "10" } | {"greater_than_or_equal": "10"} | field >= ? |
| Less/equal | { less_than_or_equal = "10" } | {"less_than_or_equal": "10"} | field <= ? |
| In | { ["in"] = { "a", "b" } } | {"in": ["a", "b"]} | field IN (?, ?) |
| Not in | { not_in = { "a", "b" } } | {"not_in": ["a", "b"]} | field NOT IN (?, ?) |
| Exists | { exists = true } | {"exists": true} | field IS NOT NULL |
| Not exists | { not_exists = true } | {"not_exists": true} | field IS NULL |
Note: For
exists/not_exists, the value is ignored — only the key matters. Usenot_existsfor IS NULL (not{ exists = false }).gRPC shorthand limitation: In Lua, bare values like
{ count = 42 }or{ active = true }are coerced to string equals. The gRPCwhereJSON only accepts string or operator object values — numeric/boolean shorthand is not supported.
Sorting
Prefix a field name with - for descending order. When order_by is omitted, results are sorted by created_at DESC (newest first) for collections with timestamps, or id ASC otherwise. When sorting by a non-id field, an id tiebreaker is always appended for stable ordering.
Lua:
crap.collections.posts.find({ order_by = "-created_at" })
gRPC:
grpcurl -plaintext -d '{
"collection": "posts",
"order_by": "-created_at"
}' localhost:50051 crap.ContentAPI/Find
Pagination
Use limit and page for pagination. The response includes a nested pagination object with total count and page info.
Lua:
local result = crap.collections.posts.find({
limit = 10,
page = 3,
})
-- result.pagination.totalDocs = 150 (total matching documents)
-- result.pagination.limit = 10
-- result.pagination.totalPages = 15
-- result.pagination.page = 3 (1-based)
-- result.pagination.pageStart = 21 (1-based index of first doc on this page)
-- result.pagination.hasNextPage = true
-- result.pagination.hasPrevPage = true
-- result.pagination.prevPage = 2
-- result.pagination.nextPage = 4
-- #result.documents = 10 (this page)
gRPC:
grpcurl -plaintext -d '{
"collection": "posts",
"limit": "10",
"page": "3"
}' localhost:50051 crap.ContentAPI/Find
Cursor-Based Pagination
Cursor-based pagination is opt-in via [pagination] mode = "cursor" in crap.toml. When enabled, the pagination object includes opaque startCursor and endCursor tokens instead of page/totalPages. These represent the cursors of the first and last documents in the result set. Pass after_cursor (forward) or before_cursor (backward) on the next request to navigate from any cursor position.
after_cursor/before_cursor and page are mutually exclusive. after_cursor and before_cursor are also mutually exclusive with each other.
Lua:
-- First page
local result = crap.collections.posts.find({
order_by = "-created_at",
limit = 10,
})
-- result.pagination.hasNextPage = true
-- result.pagination.hasPrevPage = false
-- result.pagination.startCursor = "eyJpZCI6ImFiYzEyMyJ9" (cursor of first doc)
-- result.pagination.endCursor = "eyJpZCI6Inh5ejc4OSJ9" (cursor of last doc)
-- Next page (forward)
local page2 = crap.collections.posts.find({
order_by = "-created_at",
limit = 10,
after_cursor = result.pagination.endCursor,
})
-- Previous page (backward)
local page1_again = crap.collections.posts.find({
order_by = "-created_at",
limit = 10,
before_cursor = page2.pagination.startCursor,
})
gRPC:
# First page
grpcurl -plaintext -d '{
"collection": "posts",
"order_by": "-created_at",
"limit": "10"
}' localhost:50051 crap.ContentAPI/Find
# Response pagination includes start_cursor / end_cursor when cursor mode is active
# Next page (forward)
grpcurl -plaintext -d '{
"collection": "posts",
"order_by": "-created_at",
"limit": "10",
"after_cursor": "eyJpZCI6Inh5ejc4OSJ9"
}' localhost:50051 crap.ContentAPI/Find
# Previous page (backward)
grpcurl -plaintext -d '{
"collection": "posts",
"order_by": "-created_at",
"limit": "10",
"before_cursor": "eyJpZCI6ImFiYzEyMyJ9"
}' localhost:50051 crap.ContentAPI/Find
Cursors encode the position of a document in the sorted result set. They are opaque — do not parse or construct them manually. startCursor and endCursor are always present when the result set is non-empty.
Combining Filters
Multiple filters are combined with AND:
Lua:
crap.collections.posts.find({
where = {
status = "published",
created_at = { greater_than = "2024-01-01" },
title = { contains = "update" },
},
order_by = "-created_at",
limit = 10,
})
gRPC:
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":\"published\",\"created_at\":{\"greater_than\":\"2024-01-01\"},\"title\":{\"contains\":\"update\"}}",
"order_by": "-created_at",
"limit": "10"
}' localhost:50051 crap.ContentAPI/Find
OR Filters
Use the or key to combine groups of conditions with OR logic. Each element in the or array is an object whose fields are AND-ed together. Multiple or groups are joined with OR.
Lua:
-- title contains "hello" OR category = "news"
crap.collections.posts.find({
where = {
["or"] = {
{ title = { contains = "hello" } },
{ category = "news" },
},
},
})
-- status = "published" AND (title contains "hello" OR title contains "world")
crap.collections.posts.find({
where = {
status = "published",
["or"] = {
{ title = { contains = "hello" } },
{ title = { contains = "world" } },
},
},
})
-- Multi-condition groups: (status = "published" AND title contains "hello") OR (status = "draft")
crap.collections.posts.find({
where = {
["or"] = {
{ status = "published", title = { contains = "hello" } },
{ status = "draft" },
},
},
})
gRPC:
# title contains "hello" OR category = "news"
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"or\":[{\"title\":{\"contains\":\"hello\"}},{\"category\":\"news\"}]}"
}' localhost:50051 crap.ContentAPI/Find
# status = "published" AND (title contains "hello" OR title contains "world")
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":\"published\",\"or\":[{\"title\":{\"contains\":\"hello\"}},{\"title\":{\"contains\":\"world\"}}]}"
}' localhost:50051 crap.ContentAPI/Find
Top-level filters and or groups are combined with AND. Each object inside the or array can have multiple fields which are AND-ed together within that group.
Field Selection (select)
Use select to specify which fields to return. Reduces data transfer and skips relationship hydration/population for non-selected fields. The id, created_at, and updated_at fields are always included.
Lua:
-- Return only title and status
crap.collections.posts.find({
select = { "title", "status" },
})
-- Works with find_by_id too
crap.collections.posts.find_by_id(id, {
select = { "title", "status" },
})
gRPC:
# Return only title and status fields
grpcurl -plaintext -d '{
"collection": "posts",
"select": ["title", "status"]
}' localhost:50051 crap.ContentAPI/Find
# FindByID with select
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"select": ["title", "status"]
}' localhost:50051 crap.ContentAPI/FindByID
Behavior:
selectis optional. When omitted or empty, all fields are returned (backward compatible).- System fields (
id,created_at,updated_at) are always included. - Selecting a group field name (e.g.,
"seo") includes all its sub-fields. - Relationship fields not in
selectare skipped during population (saves N+1 queries).
Field Validation
All filter field names and order_by fields are validated against the collection’s field definitions. Invalid field names return an error. This prevents SQL injection via field names.
Draft Parameter (Versioned Collections)
Collections with versions = { drafts = true } automatically filter by _status = 'published' on Find queries. Use the draft parameter to change this behavior.
Lua:
-- Default: only published documents
local published = crap.collections.articles.find({})
-- Include drafts
local all = crap.collections.articles.find({ draft = true })
-- FindByID: get the latest version (may be a draft)
local latest = crap.collections.articles.find_by_id(id, { draft = true })
gRPC:
# Default: only published
grpcurl -plaintext -d '{"collection": "articles"}' \
localhost:50051 crap.ContentAPI/Find
# Include drafts
grpcurl -plaintext -d '{"collection": "articles", "draft": true}' \
localhost:50051 crap.ContentAPI/Find
# FindByID: get latest version snapshot
grpcurl -plaintext -d '{"collection": "articles", "id": "abc123", "draft": true}' \
localhost:50051 crap.ContentAPI/FindByID
Filters on system columns (field paths starting with _, e.g. _status, _deleted_at) are rejected. Use the draft = true request flag to include drafts, and trash = true to reach soft-deleted rows — these are the supported entry points.
See Versions & Drafts for the full workflow.
Nested Field Filters (Dot Notation)
You can filter on sub-fields of group, array, blocks, and has-many relationship fields using dot notation.
Group Fields
Group sub-fields can be filtered using dot notation. Internally, seo.meta_title is converted to seo__meta_title (the flat column name). The double-underscore syntax also continues to work.
Lua:
crap.collections.pages.find({
where = {
["seo.meta_title"] = { contains = "SEO" },
},
})
gRPC:
grpcurl -plaintext -d '{
"collection": "pages",
"where": "{\"seo.meta_title\":{\"contains\":\"SEO\"}}"
}' localhost:50051 crap.ContentAPI/Find
Array Sub-Fields
Filter by sub-field values in array rows. Uses an EXISTS subquery against the array join table. Returns parent documents that have at least one array row matching the condition.
Lua:
-- Find products where any variant has color "red"
crap.collections.products.find({
where = {
["variants.color"] = "red",
},
})
-- Group-in-array: filter by a group sub-field within array rows
-- (uses json_extract on the JSON column in the join table)
crap.collections.products.find({
where = {
["variants.dimensions.width"] = "10",
},
})
Block Sub-Fields
Filter by field values inside block rows. Uses json_extract on the block data column. Returns parent documents that have at least one block row matching.
Lua:
-- Find posts where any content block has body containing "hello"
crap.collections.posts.find({
where = {
["content.body"] = { contains = "hello" },
},
})
-- Filter by block type
crap.collections.posts.find({
where = {
["content._block_type"] = "image",
},
})
-- Group-in-block: filter by a group sub-field within block data
crap.collections.posts.find({
where = {
["content.meta.author"] = "Alice",
},
})
Has-Many Relationships
Filter by related document IDs. Uses an EXISTS subquery against the relationship join table.
Lua:
-- Find posts that have tag "tag-123"
crap.collections.posts.find({
where = {
["tags.id"] = "tag-123",
},
})
Combining Nested and Regular Filters
Nested field filters can be freely combined with regular column filters and OR groups:
Lua:
crap.collections.products.find({
where = {
status = "published",
["variants.color"] = "red",
["or"] = {
{ ["content._block_type"] = "image" },
{ ["tags.id"] = "tag-featured" },
},
},
})
All filter operators (equals, contains, like, in, greater_than, etc.) work with nested field filters.
Full-Text Search
Use the search parameter for fast full-text search powered by SQLite FTS5. This searches across all text-like fields (text, textarea, richtext, email, code) or the fields specified in list_searchable_fields in the collection’s admin config.
Lua:
local result = crap.collections.posts.find({
search = "hello world",
limit = 10,
})
gRPC:
grpcurl -plaintext -d '{
"collection": "posts",
"search": "hello world",
"limit": "10"
}' localhost:50051 crap.ContentAPI/Find
Behavior:
- Each whitespace-separated word is treated as a literal search term (implicit AND).
- Results are ranked by relevance (FTS5
rank). searchcan be combined withwherefilters, pagination, sorting, and all other query parameters.- Collections without text fields silently ignore the
searchparameter. - The
searchparameter also works withCountto get the total number of matching documents.
Indexed fields are determined by:
admin.list_searchable_fieldsif configured on the collection.- Otherwise, all parent-level fields with types: text, textarea, richtext, email, code.
The FTS index is automatically created and rebuilt on server startup for every collection with text fields.
Valid Filter Fields
You can filter on any column in the collection table:
- User-defined fields (that have parent columns)
idcreated_at(if timestamps enabled)updated_at(if timestamps enabled)
System columns (names starting with _, such as _status, _deleted_at, _ref_count, _locked, _password_hash) are engine-internal and cannot be filtered on directly. Reach their data via typed request flags (draft = true, trash = true) instead.
Additionally, you can filter on sub-fields using dot notation:
- Group sub-fields:
group_name.sub_field(syntactic sugar forgroup_name__sub_field) - Array sub-fields:
array_name.sub_fieldorarray_name.group.sub_field(group-in-array) - Block sub-fields:
blocks_name.field,blocks_name._block_type, orblocks_name.group.sub_field - Has-many relationships:
relationship_name.id
Hooks
Hooks let you intercept and modify data at every stage of a document’s lifecycle. They’re the primary extension mechanism in Crap CMS.
Three Levels of Hooks
- Field-level hooks — per-field value transformers. Defined on individual
FieldDefinitionentries. - Collection-level hooks — per-collection lifecycle hooks. Defined on
CollectionDefinitionorGlobalDefinition. - Globally registered hooks — fire for all collections. Registered via
crap.hooks.register()ininit.lua.
All hooks at all levels run in this order for each lifecycle event:
field-level → collection-level → globally registered
Hook References
Collection-level and field-level hooks are string references in module.function format:
hooks = {
before_change = { "hooks.posts.auto_slug" },
}
This resolves to require("hooks.posts").auto_slug via Lua’s module system. The config directory is on the package path, so hooks/posts.lua should return a module table:
-- hooks/posts.lua
local M = {}
function M.auto_slug(ctx)
if ctx.data.slug == nil or ctx.data.slug == "" then
ctx.data.slug = crap.util.slugify(ctx.data.title or "")
end
return ctx
end
return M
No Closures
Hook references are always strings, never Lua functions. This keeps collection definitions serializable (important for the future visual builder).
The one exception is crap.hooks.register(), which takes a function directly — but it’s called in init.lua, not in collection definitions.
CRUD Access in Hooks
Before-event hooks (before_validate, before_change, before_delete) have full CRUD access via the crap.collections.* and crap.globals.* APIs. They share the parent operation’s database transaction.
After-write hooks (after_change, after_delete) also have CRUD access and run inside the same transaction. Errors roll back the entire operation.
After-read hooks (after_read) do NOT have CRUD access.
See Transaction Access for details.
Concurrency
Hooks execute in a pool of Lua VMs, allowing concurrent hook execution across requests. The pool size is configurable:
[hooks]
vm_pool_size = 8 # default: number of CPU cores
Each VM is fully initialized at startup with the same configuration (package paths, API registration, CRUD functions, init.lua execution). When a request needs to execute a hook, it acquires a VM from the pool and returns it when done. This prevents hook execution from serializing under concurrent load.
Resource Limits
Lua VMs have configurable instruction, memory, and recursion limits to prevent runaway hooks:
[hooks]
max_depth = 3 # max hook recursion depth (hook → CRUD → hook; 0 = no hooks from Lua CRUD)
max_instructions = 10000000 # per hook invocation (0 = unlimited)
max_memory = 52428800 # per VM in bytes, 50 MB (0 = unlimited)
allow_private_networks = false # block HTTP to internal IPs
http_max_response_bytes = 10485760 # 10 MB (increase for large file downloads)
- Instruction limit — a hook that exceeds the instruction count is terminated with an error. The default (10M) is generous for complex hooks.
- Memory limit — caps total Lua memory per VM. Exceeding it raises a memory error.
- Private network blocking —
crap.http.requestresolves hostnames and rejects private/loopback/link-local IPs unlessallow_private_networks = true. crap.crypto.random_bytes— capped at 1 MB per call.
State & Module Caching
Lua’s require function caches modules in package.loaded. This means module-level variables persist across requests on the same VM:
-- hooks/posts.lua
local M = {}
local counter = 0 -- persists across requests!
function M.before_change(ctx)
counter = counter + 1 -- increments forever on this VM
return ctx
end
return M
To avoid cross-request state leaks, keep hook functions stateless — use the ctx table for input/output, and crap.collections.* for persistent storage. If you need request-scoped state, store it in ctx.context (the request-scoped shared table — see Hook Context), not module-level locals.
Module-level constants and utility functions are fine — only mutable state is the concern.
Important: VM pool behavior. Since HookRunner uses a pool of Lua VMs, global state in Lua modules persists across requests within the same VM but is not shared across VMs. Each VM in the pool has its own independent copy of module-level variables. This means:
- Module-level variables can act as in-memory caches, but different requests may hit different VMs and see different cached values.
- Cached state is not consistent across the pool — one VM’s counter may be at 5 while another is at 12.
- All cached state is lost on server restart (VMs are re-initialized from scratch).
If you need shared, consistent state, use
crap.collections.*orcrap.globals.*to persist to the database.
Lifecycle Events
Nine lifecycle events fire during CRUD operations and admin page rendering.
Event Reference
| Event | Fires On | Mutable Data | CRUD Access | Notes |
|---|---|---|---|---|
before_validate | create, update, update_many | Yes | Yes | Normalize inputs before validation |
before_change | create, update, update_many | Yes | Yes | Transform data after validation passes |
after_change | create, update, update_many | Yes | Yes | Runs inside the transaction. Audit logs, counters, side-effects. Errors roll back the entire operation. |
before_read | find, find_by_id | No | No* | Can abort the read by returning an error |
after_read | find, find_by_id | Yes | No | Transform data before it reaches the client |
before_delete | delete, delete_many | No | Yes | Can abort the delete. CRUD access for cascading deletes. |
after_delete | delete, delete_many | No | Yes | Runs inside the transaction. Cleanup, cascading deletes. Errors roll back the entire operation. |
before_broadcast | create, update, delete | Yes (data) | No | Can suppress or transform live update events. See Live Updates. |
before_render | admin page render | Yes (context) | No | Runs before rendering admin pages. Receives the full template context and can modify it. Global-only (no collection-level refs). Useful for injecting global template data. |
* before_read hooks have no CRUD access when called from the gRPC API or admin UI. However, when triggered from a Lua CRUD call inside a hook (e.g., crap.collections.find() inside before_change), before_read hooks inherit the parent’s transaction context and DO have CRUD access.
Document ID in Hook Context
In after_change and after_delete hooks, context.data.id contains the document ID. This is useful for queuing jobs or looking up the document after it’s been written. In before_delete hooks, context.data.id is also available.
Write Lifecycle (create/update)
1. field before_validate hooks (CRUD access)
2. collection before_validate hooks (CRUD access)
3. global registered before_validate hooks (CRUD access)
4. field validation (required, unique, custom validate)
5. field before_change hooks (CRUD access)
6. collection before_change hooks (CRUD access)
7. global registered before_change hooks (CRUD access)
8. database write (INSERT or UPDATE)
9. join table write (has-many relationships, arrays)
10. field after_change hooks (CRUD access, same transaction)
11. collection after_change hooks (CRUD access, same transaction)
12. global registered after_change hooks (CRUD access, same transaction)
13. transaction commit
14. live setting check (background)
15. before_broadcast hooks (background, no CRUD)
16. EventBus publish (if not suppressed)
Bulk Operations (update_many/delete_many)
update_many and delete_many run the same per-document lifecycle as their single-document counterparts. Each matched document goes through the full hook pipeline individually, all within a single transaction (all-or-nothing).
update_many runs steps 1–12 above for each document. Key differences from single-document update:
- Only provided fields are written (partial update). Absent fields — including checkboxes — are left unchanged.
- Password updates are rejected. Use single-document
Updateinstead. - Hook-modified data is captured and written (hooks can transform the data).
- Set
hooks = falseto skip all hooks and validation for performance.
delete_many runs the delete lifecycle (steps 1–5 below) for each document.
Read Lifecycle (find/find_by_id)
1. collection before_read hooks
2. global registered before_read hooks
3. database query
4. field after_read hooks
5. collection after_read hooks
6. global registered after_read hooks
Delete Lifecycle
1. collection before_delete hooks (CRUD access)
2. global registered before_delete hooks (CRUD access)
3. database delete
4. collection after_delete hooks (CRUD access, same transaction)
5. global registered after_delete hooks (CRUD access, same transaction)
6. transaction commit
7. live setting check (background)
8. before_broadcast hooks (background, no CRUD)
9. EventBus publish (if not suppressed)
before_broadcast
Fires after a create, update, or delete has been committed and the live setting
check has passed, but before the event is dispatched on the EventBus to live
subscribers (SSE, gRPC Subscribe). Runs in a background spawn_blocking task — never
blocks the response to the originating request.
No CRUD access (the transaction is already closed).
The hook receives a context table with collection, operation ("create",
"update", or "delete"), and data (the document payload that would be broadcast).
Return values:
- A table — broadcast continues with the (possibly mutated)
data. nilorfalse— the broadcast is suppressed for this subscriber wave; no event is dispatched.
crap.hooks.register("before_broadcast", function(ctx)
-- Don't broadcast drafts
if ctx.data.status == "draft" then
return nil
end
-- Strip a sensitive field from the broadcast payload only
ctx.data.internal_notes = nil
return ctx
end)
Collection-level before_broadcast hook refs run before global registered hooks. A
suppression at any stage stops the rest of the chain.
before_render
Fires before an admin page template is rendered. The hook receives the full template context (the JSON object passed to the template engine) as a Lua table, and may return a modified table to inject globals, sidebar items, or additional template variables.
No CRUD access, global hooks only (no collection-level refs). Errors, non-table returns, and conversion failures log a warning and fall back to the unmodified context.
Return values:
- A table — the new template context.
nil— the original context is preserved (no-op).- Anything else — logged as a warning, ignored.
crap.hooks.register("before_render", function(ctx)
-- Inject a banner shown in the admin layout
ctx.banner_message = "Maintenance window 02:00 UTC tonight"
return ctx
end)
Fires from every admin page handler (dashboard, list, edit, delete confirm, version
list/restore, login, forgot/reset password, etc.). Inspect ctx to branch on the page
being rendered.
Execution Order
At each lifecycle stage, hooks run in this order:
1. Field-level hooks (per-field, in field definition order)
2. Collection-level hooks (string refs from collection definition, in array order)
3. Globally registered hooks (from crap.hooks.register(), in registration order)
Example: before_change on create
Given this setup:
-- collections/posts.lua
crap.collections.define("posts", {
fields = {
crap.fields.text({
name = "title",
hooks = { before_change = { "hooks.fields.uppercase" } },
}),
crap.fields.text({
name = "slug",
hooks = { before_change = { "hooks.fields.normalize_slug" } },
}),
},
hooks = {
before_change = { "hooks.posts.set_defaults", "hooks.posts.validate_business_rules" },
},
})
-- init.lua
crap.hooks.register("before_change", function(ctx)
crap.log.info("audit: " .. ctx.operation .. " on " .. ctx.collection)
return ctx
end)
Execution order for a create operation:
hooks.fields.uppercase(field: title)hooks.fields.normalize_slug(field: slug)hooks.posts.set_defaults(collection)hooks.posts.validate_business_rules(collection)- Registered audit function (global)
Multiple Hooks per Event
Both field-level and collection-level hooks accept arrays. Hooks in the same array run sequentially, each receiving the output of the previous one.
hooks = {
before_change = { "hooks.posts.first", "hooks.posts.second" },
}
first runs, its returned context is passed to second.
Field Hooks
Field-level hooks operate on individual field values rather than the full document context.
Signature
function hook(value, context)
-- transform value
return new_value
end
| Parameter | Type | Description |
|---|---|---|
value | any | Current field value |
context | table | See context fields below |
Return value: The new field value. This replaces the existing value in the data.
Context Table
| Field | Type | Description |
|---|---|---|
field_name | string | Name of the field being processed |
collection | string | Collection slug |
operation | string | "create", "update", "find", "find_by_id" |
data | table | Full document data (read-only snapshot) |
user | table/nil | Authenticated user document (nil if unauthenticated) |
ui_locale | string/nil | Admin UI locale code (e.g., "en", "de") |
Typed Contexts
The type generator (crap-cms typegen) emits per-collection field hook contexts
with typed data fields:
- Collections:
crap.field_hook.{PascalCase}— e.g.,crap.field_hook.Postshasdata: crap.data.Posts - Globals:
crap.field_hook.global_{slug}— e.g.,crap.field_hook.global_site_settingshasdata: crap.global_data.SiteSettings
Use the typed context when a hook is specific to one collection:
---@param value number|nil
---@param context crap.field_hook.Inquiries
---@return number|nil
return function(value, context)
-- context.data is typed as crap.data.Inquiries
-- IDE autocompletes context.data.name, context.data.email, etc.
return value
end
For shared hooks that work across multiple collections, use the generic
crap.FieldHookContext (where data is table<string, any>).
Events
| Event | CRUD Access | Use Case |
|---|---|---|
before_validate | Yes | Normalize values before validation (trim, lowercase, etc.) |
before_change | Yes | Transform values after validation (compute derived fields) |
after_change | Yes | Side effects after write with CRUD access (logging, cascades) |
after_read | No | Transform values before response (formatting, computed fields) |
Definition
crap.fields.text({
name = "title",
hooks = {
before_validate = { "hooks.fields.trim" },
before_change = { "hooks.fields.sanitize_html" },
after_read = { "hooks.fields.add_word_count" },
},
})
Example
-- hooks/fields.lua
local M = {}
function M.trim(value, ctx)
if type(value) == "string" then
return value:match("^%s*(.-)%s*$")
end
return value
end
function M.slugify(value, ctx)
-- Auto-generate slug from title if empty
if (value == nil or value == "") and ctx.data.title then
return crap.util.slugify(ctx.data.title)
end
return value
end
return M
Registered Hooks
Registered hooks fire for all collections at a given lifecycle event. Register them in init.lua using crap.hooks.register().
Registration
-- init.lua
crap.hooks.register("before_change", function(ctx)
crap.log.info("[audit] " .. ctx.operation .. " on " .. ctx.collection)
return ctx
end)
Unlike collection-level hooks (which are string references), registered hooks are Lua functions passed directly.
API
crap.hooks.register(event, fn)
Register a hook function for a lifecycle event.
| Parameter | Type | Description |
|---|---|---|
event | string | One of the lifecycle events |
fn | function | Hook function receiving a context table |
crap.hooks.remove(event, fn)
Remove a previously registered hook. Uses rawequal for identity-based matching — you must pass the exact same function reference.
local my_hook = function(ctx)
-- ...
return ctx
end
crap.hooks.register("before_change", my_hook)
-- Later:
crap.hooks.remove("before_change", my_hook)
CRUD Access
Registered hooks follow the same rules as collection-level hooks:
- Before-event hooks (
before_validate,before_change,before_delete) have CRUD access via the shared transaction - Write after-event hooks (
after_change,after_delete) have CRUD access — they run inside the same transaction viarun_hooks_with_conn - Read after-event hooks (
after_read) do NOT have CRUD access — they run without a transaction
Execution Order
Registered hooks run after field-level and collection-level hooks at each lifecycle stage.
Example: Audit Log
-- init.lua
crap.hooks.register("before_change", function(ctx)
crap.log.info(string.format(
"[audit] %s %s: %s",
ctx.operation,
ctx.collection,
ctx.data.id or "(new)"
))
return ctx
end)
Example: Auto-Set Created By
-- init.lua (requires auth + access context in hooks)
crap.hooks.register("before_change", function(ctx)
if ctx.operation == "create" then
-- Set created_by to current user ID if field exists
-- (requires the collection to have a created_by field)
end
return ctx
end)
Hook Context
Collection-level hooks receive a context table and must return a (potentially modified) context table.
Context Shape
{
collection = "posts", -- Collection slug
operation = "create", -- "create", "update", "delete", "find", "find_by_id", or "init"
data = { -- Document data (mutable in before-write hooks)
title = "Hello World",
slug = "hello-world",
status = "draft",
id = "abc123", -- Present on update/delete, absent on create
created_at = "...", -- Present on read/update
updated_at = "...",
},
locale = "en", -- Locale for this operation (nil if not locale-specific)
draft = true, -- Whether this is a draft save (versioned collections only)
hook_depth = 0, -- Current recursion depth (0 = top-level, 1+ = from Lua CRUD in hooks)
context = { -- Request-scoped shared table (persists across all hooks in the same request)
-- Hooks can read and write arbitrary keys here to share data
},
user = { -- Authenticated user document (nil if unauthenticated)
id = "user_123",
email = "admin@example.com",
role = "admin",
-- ... all fields from the auth collection
},
ui_locale = "en", -- Admin UI locale (nil if not set)
}
Typed Contexts
The type generator (crap-cms typegen) emits per-collection context types with typed
data fields for IDE autocomplete:
- Collections:
crap.hook.{PascalCase}— e.g.,crap.hook.Postshasdata: crap.data.Postsandcollection: "posts"(literal) - Globals:
crap.hook.global_{slug}— e.g.,crap.hook.global_site_settingshasdata: crap.global_data.SiteSettings
Use the typed context for hooks that target a specific collection:
---@param context crap.hook.Posts
---@return crap.hook.Posts
return function(context)
-- context.data.title, context.data.slug, etc. autocomplete
return context
end
Delete hooks receive only { id = "..." } in data (not full document fields),
so they use the generic crap.HookContext:
---@param context crap.HookContext
---@return crap.HookContext
return function(context)
local id = context.data.id
return context
end
For shared hooks that fire across multiple collections (e.g., via
crap.hooks.register()), use the generic crap.HookContext.
Data Mutation
In before-write hooks (before_validate, before_change), you can modify ctx.data and return the modified context. The changes flow through to the database write.
function M.auto_slug(ctx)
if not ctx.data.slug or ctx.data.slug == "" then
ctx.data.slug = crap.util.slugify(ctx.data.title or "")
end
return ctx
end
In after-read hooks, you can also modify ctx.data to transform the response before it reaches the client.
Return Value
Hooks must return the context table (or a new table with data). If a hook returns:
- A table with a
datakey — the data is replaced - A table without a
datakey — the original data is kept - A non-table value — the original context is kept
System Fields in Data
| Field | Present When | Description |
|---|---|---|
id | update, delete, read | Document ID |
created_at | read, update | ISO 8601 timestamp |
updated_at | read, update | ISO 8601 timestamp |
user | write hooks, after_read (nil if unauthenticated) | Authenticated user document |
ui_locale | write hooks, after_read (nil if not set) | Admin UI locale code |
On create, id is not yet assigned (it’s generated by the database write).
Draft Field
For versioned collections with drafts = true, the context includes a draft field:
| Value | Meaning |
|---|---|
true | This is a draft save (required field validation is skipped) |
false | This is a publish save (full validation applied) |
nil | Collection does not have versioning enabled |
You can use this in hooks to customize behavior based on publish state:
function M.before_change(ctx)
if ctx.draft then
-- Draft save: skip expensive operations
return ctx
end
-- Publishing: run full processing
ctx.data.published_at = os.date("!%Y-%m-%d %H:%M:%S")
return ctx
end
User
The user field contains the full authenticated user document from the auth collection, or nil if the request is unauthenticated (or no auth collection exists). This is the same user document used by access control functions.
function M.before_change(ctx)
if ctx.user then
ctx.data.last_edited_by = ctx.user.email
end
return ctx
end
UI Locale
The ui_locale field contains the admin UI locale code (e.g., "en", "de"), or nil if not set. This is useful for returning user-facing messages (e.g., validation errors) in the correct language.
function M.validate_title(value, ctx)
if not value or value == "" then
if ctx.ui_locale == "de" then
return "Titel ist erforderlich"
end
return "Title is required"
end
return true
end
Hook Depth
The hook_depth field tracks how deep in the hook→CRUD→hook chain the current execution is:
| Value | Meaning |
|---|---|
0 | Top-level call from gRPC API or admin UI |
1 | Called from Lua CRUD inside a hook |
2+ | Deeper recursion (hook called CRUD which triggered another hook) |
When hook_depth reaches hooks.max_depth (default: 3, configurable in crap.toml),
hooks are automatically skipped but the DB operation still executes. This prevents infinite
recursion when hooks create/update documents in the same collection.
function M.audit_hook(ctx)
-- Only audit at the top level, not from recursive hook calls
if ctx.hook_depth >= 1 then
return ctx
end
crap.collections.audit_log.create({
action = ctx.operation,
collection = ctx.collection,
})
return ctx
end
Context (Request-Scoped Shared Table)
The context field is a request-scoped table that persists across all hooks in the same request. It allows hooks to share data with each other without relying on module-level state.
Each hook in the chain receives the same context table, and any modifications made by one hook are visible to all subsequent hooks in the same request. The table starts empty at the beginning of each request.
This is useful for:
- Passing computed values from
before_validatetobefore_changewithout recomputing - Sharing request metadata between hooks
- Accumulating data across multiple hooks for use in
after_change
-- In before_validate hook: compute and share a value
function M.before_validate(ctx)
ctx.context.original_title = ctx.data.title
return ctx
end
-- In after_change hook: use the shared value
function M.after_change(ctx)
if ctx.context.original_title ~= ctx.data.title then
crap.log.info("Title changed from: " .. (ctx.context.original_title or "nil"))
end
return ctx
end
Note: The
contexttable is not the same as module-level variables. Module-level variables persist across requests on the same VM (see Hooks Overview), whilecontextis scoped to a single request and automatically cleaned up.
Transaction Access
Hooks can call back into the Crap CMS CRUD API. Whether a hook has CRUD access depends on the lifecycle event.
Which Hooks Get CRUD Access?
| Event | CRUD Access | Reason |
|---|---|---|
before_validate | Yes | Runs inside the write transaction |
before_change | Yes | Runs inside the write transaction |
after_change | Yes | Runs inside the write transaction, after the DB operation |
before_read | No | Read operations don’t open a write transaction |
after_read | No | Fire-and-forget, no transaction |
before_delete | Yes | Runs inside the delete transaction |
after_delete | Yes | Runs inside the delete transaction, after the DB delete |
This applies to all three hook levels (field, collection, registered).
Available Functions
Inside hooks with CRUD access:
-- Collections
crap.collections.posts.find({ where = { status = "published" } })
crap.collections.posts.find_by_id("abc123")
crap.collections.audit_log.create({ action = "update", target = ctx.data.id })
crap.collections.posts.update(id, { view_count = views + 1 })
crap.collections.drafts.delete(old_id)
-- Globals
crap.globals.site_settings.get()
crap.globals.counters.update({ total_posts = count + 1 })
Transaction Sharing
CRUD calls inside hooks share the same database transaction as the parent operation. This means:
- If the hook creates a document and the parent operation later fails, the created document is rolled back
- If the hook fails, the entire parent operation rolls back
- All changes are atomic — either everything commits or nothing does
This applies to all write hooks: before_validate, before_change, after_change, before_delete, and after_delete.
Error Handling
If any hook (before or after) returns an error or throws a Lua error, the entire transaction is rolled back and the operation fails with an error message. This includes after-hooks — an after_change error will roll back the main DB operation too.
Calling CRUD Outside Hooks
Calling crap.collections.find() etc. outside a hook context (no active transaction) results in an error:
crap.collections CRUD functions are only available inside hooks
with transaction context (before_change, before_delete, etc.)
on_init Hooks
The [hooks] on_init list in crap.toml runs at startup with CRUD access. All on_init hooks share a single database transaction — if any hook fails, all changes are rolled back. This makes seeding and startup migrations atomic:
[hooks]
on_init = ["hooks.seed.run"]
-- hooks/seed.lua
local M = {}
function M.run(ctx)
local result = crap.collections.posts.find()
if result.pagination.totalDocs == 0 then
crap.collections.posts.create({
title = "Welcome",
slug = "welcome",
status = "published",
content = "Welcome to your new site!",
})
crap.log.info("Seeded initial post")
end
return ctx
end
return M
If an on_init hook fails, the server aborts startup.
Access Control Functions
Access control functions (access.read, access.create, access.update, access.delete on collections/globals and access.read, access.create, access.update on fields) run with CRUD access inside their own transaction. Each access check gets a dedicated transaction that commits on success or rolls back on error.
Auth Strategies
Custom auth strategy authenticate functions run with CRUD access inside a transaction. All strategies for a given request share a single transaction — if a strategy authenticates successfully, the transaction commits. If all strategies fail, the transaction rolls back.
Jobs
Background job system for scheduled and queued tasks.
Overview
Crap CMS includes a built-in job scheduler for running background tasks. Jobs are defined in Lua, can be triggered manually or on a cron schedule, and execute with full CRUD access to all collections.
Use cases:
- Scheduled cleanup (e.g., delete expired posts nightly)
- Async processing triggered from hooks (e.g., send welcome email after user creation)
- Periodic data sync or aggregation
Defining Jobs
Jobs are defined via crap.jobs.define() in init.lua or files under jobs/:
-- jobs/cleanup_expired.lua
crap.jobs.define("cleanup_expired", {
handler = "jobs.cleanup_expired.run",
schedule = "0 3 * * *", -- daily at 3am
queue = "maintenance",
retries = 3,
timeout = 300,
concurrency = 1,
skip_if_running = true,
labels = { singular = "Cleanup Expired Posts" },
access = "hooks.check_admin", -- optional access control
})
local M = {}
function M.run(ctx)
-- ctx.data = input data from queue() or {} for cron
-- ctx.job = { slug, attempt, max_attempts }
-- Full CRUD access available
local expired = crap.collections.posts.find({
where = { expires_at = { less_than = os.date("!%Y-%m-%dT%H:%M:%SZ") } }
})
for _, doc in ipairs(expired.documents) do
crap.collections.posts.delete(doc.id)
end
return { deleted = #expired.documents }
end
return M
Configuration Options
| Field | Type | Default | Description |
|---|---|---|---|
handler | string | (required) | Lua function ref (e.g., "jobs.cleanup.run") |
schedule | string | nil | Cron expression for automatic scheduling |
queue | string | "default" | Queue name for grouping |
retries | integer | inherits queue, else 0 | Max retry attempts on failure (see Retry Backoff below). Omit to inherit [jobs.queues.<queue>] retries from crap.toml; set explicitly (including 0) to override the queue default. |
timeout | integer | 60 | Seconds before job is marked failed |
concurrency | integer | 1 | Max concurrent runs of this job (cluster-wide) |
priority | integer | 0 | Default scheduling priority; higher = sooner. Per-enqueue value overrides this. |
skip_if_running | boolean | true | Skip cron trigger if previous run still active |
labels | table | nil | Display labels ({ singular = "..." }) |
access | string | nil | Lua function ref for trigger access control |
Queuing from Hooks
Jobs can be queued programmatically from hooks:
-- Basic enqueue:
crap.jobs.queue("send_welcome_email", { user_id = ctx.data.id, email = ctx.data.email })
-- With per-enqueue options:
crap.jobs.queue("send_password_reset", { user_id = id }, {
priority = 10, -- jump the queue
delay = "5m", -- defer claim by 5 minutes
unique = "reset:" .. id, -- dedup against active jobs with this key
})
queue() inserts a pending job and returns its id immediately. The scheduler
picks it up on its next poll cycle. When unique matches an existing
pending/running job, queue() returns that job’s id instead of inserting a
duplicate. See crap.jobs.queue reference
for full opts.
Handler Context
The handler function receives a context table:
function M.run(ctx)
ctx.data -- table: input data from queue() or {} for cron
ctx.job.slug -- string: job definition slug
ctx.job.attempt -- integer: current attempt (1-based)
ctx.job.max_attempts -- integer: total attempts allowed
end
The handler has full CRUD access (crap.collections.find(), .create(), etc.).
Each CRUD op opens its own short-lived BEGIN IMMEDIATE transaction
(pool-mode), so a find followed by an update are two separate atomic
writes. If you need multi-step atomicity (read-modify-write, multi-write
all-or-nothing), wrap the block in
crap.transaction(fn).
If the handler returns a table, it’s stored as the job result (JSON). If it errors, the job is marked failed (and retried if attempts remain).
Back Pressure
Concurrency caps stack, strictest wins (all cluster-wide via the shared DB):
- Global:
[jobs] max_concurrentincrap.toml(default: 10) - Per-queue:
[jobs.queues.<name>]for queue-level defaults —concurrency = N(aggregate cap),timeout = "5m"(per-job wall-clock timeout for system jobs in this queue),retries = N(defaultmax_attempts - 1for system jobs in this queue). Partial overrides keep framework defaults intact. Framework shipsimages = { concurrency = 2, timeout = "5m", retries = 2 }. - Per-job:
concurrencyfield on the definition (default: 1) - Timeout: Jobs running longer than
timeoutare marked failed - Skip-if-running: Cron-triggered jobs skip if a previous run is still active
For aging-based promotion of low-priority jobs in busy queues, set
[jobs] priority_decay = "1m" — see
Concurrency model for the
full picture.
Error Handling
Job execution is fully isolated. If a job handler panics, the panic is caught and logged — it does not crash the server or affect other jobs. The job is marked as failed and retried if attempts remain.
Retry Backoff
Failed jobs with remaining retries are re-queued with an exponential backoff before the next attempt:
delay = min(2^(attempt - 1) * 5, 300) // seconds, capped at 5 minutes
| Attempt (1-based) | Delay before retry |
|---|---|
| 1 (first failure) | 5 s |
| 2 | 10 s |
| 3 | 20 s |
| 4 | 40 s |
| 5 | 80 s |
| 6 | 160 s |
| 7 or later | 300 s (cap) |
This is fixed and not currently configurable per-job. Plan your retries budget knowing that attempt 6+ is at least ~5 minutes out, not a handful of seconds.
Crash Recovery
On startup, the scheduler marks any previously-running jobs as stale (the server was restarted while they were executing). Jobs with remaining retry attempts are re-queued.
Running jobs update a heartbeat timestamp periodically so stale detection works even during normal operation.
Configuration (crap.toml)
[jobs]
max_concurrent = 10 # global concurrency limit
poll_interval = 1 # seconds between pending job polls
cron_interval = 60 # seconds between cron schedule checks
heartbeat_interval = 10 # seconds between heartbeat updates
auto_purge = "7d" # auto-delete completed jobs older than this
CLI Commands
crap-cms -C <config_dir> jobs list # list defined jobs
crap-cms -C <config_dir> jobs trigger <slug> # manually queue a job
crap-cms -C <config_dir> jobs status [--id <id>] # show recent job runs
crap-cms -C <config_dir> jobs purge [--older-than 7d] # clean up old runs
gRPC API
Four RPCs for job management:
ListJobs— list all defined jobsTriggerJob(slug, data_json?)— queue a job, returns the run IDGetJobRun(id)— get details of a specific runListJobRuns(slug?, status?, limit?, offset?)— list job runs with filters
All require authentication. TriggerJob also checks the job’s access function if defined.
Plugins
Crap CMS doesn’t have a formal plugin system. It doesn’t need one — Lua’s open module system provides everything required. A plugin is just a Lua module that modifies collections, globals, registers hooks, or any combination.
How It Works
- Collection and global definition files (
collections/*.lua,globals/*.lua) are auto-loaded first. init.luaruns after all definitions are registered.- Plugins are
require()-d frominit.luaand can read, modify, or extend any registered collection or global.
This works because crap.collections.define() and crap.globals.define() overwrite —
calling either twice for the same slug replaces the first definition with the second.
All crap.*.define calls are init-only. They must run while the
VM is in init phase: definition files, init.lua, and any file
loaded by require from those. Calling define from a runtime hook
(during a request) is rejected with a clear error pointing back to
init.lua. The plugin pattern below works because plugins are
require-d from init.lua and run with the init-phase marker still
set — the strict guard never fires for legitimate plugin code.
Load Order
Files are loaded in this fixed order at server start:
collections/*.lua— alphabetical by filenameglobals/*.lua— alphabeticaljobs/*.lua— alphabeticalinit.lua— last
Plugins live outside these three directories and are picked up only when init.lua
calls require("plugin_name"). The order of those require() calls controls
plugin execution order — there is no automatic dependency resolution.
If plugin A depends on collections, fields, or hooks added by plugin B, require B first:
-- init.lua
require("my_plugins.base").install() -- adds audit fields to all collections
require("my_plugins.workflow").install() -- reads those audit fields
Getting the order wrong produces silent runtime failures — the earlier plugin sees
collections without the later plugin’s fields, and any hook that depends on those
fields fires on incomplete data without warning. Keep the require() block in
init.lua explicit and well-commented.
Two plugins that register the same collection slug silently overwrite each other
(last call wins). Log output includes a debug! message but no warning. Pick slugs
carefully and review any plugin you adopt from a third party.
Writing a Plugin
A plugin is a Lua module that returns a table with an install() function:
-- plugins/audit_log.lua
local M = {}
function M.install()
-- Register a global hook that runs for all collections
crap.hooks.register("before_change", function(ctx)
if ctx.operation == "create" then
ctx.data.created_by = ctx.user and ctx.user.email or "system"
end
end)
end
return M
Modifying Collections
Use crap.collections.config.get() to retrieve a single collection, or
crap.collections.config.list() to iterate all collections:
-- plugins/alt_text.lua
-- Adds an alt_text field to every upload collection.
local M = {}
function M.install()
for slug, def in pairs(crap.collections.config.list()) do
if def.upload then
def.fields[#def.fields + 1] = crap.fields.text({
name = "alt_text",
admin = { description = "Describe this image for accessibility" },
})
crap.collections.define(slug, def)
end
end
end
return M
Patching a Single Collection
-- plugins/post_reading_time.lua
local M = {}
function M.install()
local def = crap.collections.config.get("posts")
if not def then return end
def.fields[#def.fields + 1] = crap.fields.number({
name = "reading_time",
admin = { readonly = true, description = "Estimated reading time (minutes)" },
})
-- Add a hook to calculate it
def.hooks.before_change = def.hooks.before_change or {}
def.hooks.before_change[#def.hooks.before_change + 1] = "plugins.post_reading_time.calculate"
crap.collections.define("posts", def)
end
function M.calculate(ctx)
local body = ctx.data.body or ""
local words = select(2, body:gsub("%S+", ""))
ctx.data.reading_time = math.ceil(words / 200)
return ctx
end
return M
Modifying Globals
The same pattern works for globals:
-- plugins/global_meta.lua
-- Adds a "last_updated_by" field to every global.
local M = {}
function M.install()
for slug, def in pairs(crap.globals.config.list()) do
def.fields[#def.fields + 1] = crap.fields.text({
name = "last_updated_by",
admin = { readonly = true },
})
crap.globals.define(slug, def)
end
end
return M
Patching a Single Global
local def = crap.globals.config.get("site_settings")
if def then
def.fields[#def.fields + 1] = crap.fields.richtext({ name = "footer_html" })
crap.globals.define("site_settings", def)
end
Installing a Plugin
-- init.lua
require("plugins.alt_text").install()
require("plugins.post_reading_time").install()
A plugin is a file in your config directory (typically plugins/). Install it by copying
or cloning into that directory and adding a require line.
Collection-Level Override
When a plugin adds fields to all collections but you want a custom version for one collection, just define the field directly in that collection’s Lua file. The plugin should check for existing fields before adding:
-- Plugin checks before adding
for _, field in ipairs(def.fields) do
if field.name == "seo" then
has_seo = true
break
end
end
if not has_seo then
def.fields[#def.fields + 1] = seo_fields
crap.collections.define(slug, def)
end
This way, posts.lua can define its own custom SEO group (e.g., with an extra og_image
field) and the plugin will skip it.
API Reference
| Function | Description |
|---|---|
crap.collections.config.get(slug) | Get a collection’s full config as a Lua table. Returns nil if not found. |
crap.collections.config.list() | Get all collections as a { slug = config } table. Iterate with pairs(). |
crap.collections.define(slug, config) | Define or redefine a collection. |
crap.globals.config.get(slug) | Get a global’s full config as a Lua table. Returns nil if not found. |
crap.globals.config.list() | Get all globals as a { slug = config } table. Iterate with pairs(). |
crap.globals.define(slug, config) | Define or redefine a global. |
crap.hooks.register(event, fn) | Register a global hook for all collections. |
Plugin Execution Order
Since init.lua runs sequentially, plugins install in the order you require them.
If plugin B depends on fields added by plugin A, require A first:
require("plugins.seo").install() -- adds seo fields
require("plugins.seo_defaults").install() -- sets default values on seo fields
Authentication
Crap CMS provides built-in authentication via auth-enabled collections. Any collection can serve as an auth collection by setting auth = true.
Key Concepts
- Auth collection — a collection with
auth = true. Users are regular documents in this collection. - Two auth surfaces — Admin UI uses an HttpOnly cookie (
crap_session). gRPC API uses Bearer tokens. - JWT — all tokens are JWT signed with the configured secret (or an auto-generated one persisted to
data/.jwt_secret). - Argon2id — passwords are hashed with Argon2id before storage.
- Rate limiting — login endpoints enforce per-email rate limiting (configurable max attempts and lockout window).
- Timing-safe — login always performs a password hash comparison, even when the user doesn’t exist, to prevent timing-based email enumeration.
- CSRF protection — admin UI forms and HTMX requests are protected with double-submit cookie tokens.
- Secure cookies — the
crap_sessioncookie includes theSecureflag in production (whendev_mode = false). The cookie’sSameSiteattribute defaults toLax; set[auth] session_cookie_samesite = "strict"incrap.tomlfor stricter CSRF protection at the cost of breaking cross-site navigation (clicks from emails, external links, etc. will require re-login). _password_hash— a hidden column added to auth collection tables. Never exposed in API responses, hooks, or admin forms._locked— when set to a truthy value, the user is denied access on every request (JWT validation, Me, admin session). Takes effect immediately, even for valid unexpired tokens. See Auth Collections.- Token/Password providers —
TokenProvider(JWT) andPasswordProvider(Argon2id) traits abstract token and password primitives. Rarely swapped. - Strategy chain —
local(email+password) is the built-in strategy. Per-collection Lua strategies are tried as fallback. OAuth2, Cloudflare Access, AD, and API key auth are implemented as Lua strategies. - Email MFA — built-in multi-factor authentication. Enable
mfa = "email"on an auth collection to send a 6-digit code after password verification. - Auth callbacks —
/admin/auth/callback/{name}catch-all route dispatches to Lua hooks for OAuth2/OIDC redirect flows. - Password reset — token-based forgot/reset password flow via admin UI and gRPC. Requires email configuration.
- Email verification — optional per-collection. When enabled, users must verify their email before logging in.
Activation
Auth middleware activates when at least one auth collection exists or when admin.require_auth is true (the default). This means:
require_auth = true(default): If no auth collections are defined, the admin shows a “Setup Required” page. Create an auth collection and bootstrap a user to proceed.require_auth = false: If no auth collections are defined, the admin is fully open (dev/prototyping mode).- Auth collection exists: Standard authentication applies. Optionally,
admin.accesscan further restrict which authenticated users can access the admin panel.
Quick Setup
- Define an auth collection:
-- collections/users.lua
crap.collections.define("users", {
auth = true,
fields = {
crap.fields.text({ name = "name", required = true }),
crap.fields.select({ name = "role", options = {
{ label = "Admin", value = "admin" },
{ label = "Editor", value = "editor" },
}}),
},
})
- Bootstrap the first user:
crap-cms -C ./my-project user create -e admin@example.com
- (Optional) Set a JWT secret explicitly, or let it auto-generate and persist to
data/.jwt_secret:
[auth]
secret = "your-random-secret-here" # omit to auto-generate (persisted across restarts)
- (Optional) Configure email for password reset and verification:
[email]
smtp_host = "smtp.example.com"
smtp_port = 587
smtp_user = "noreply@example.com"
smtp_pass = "your-smtp-password"
from_address = "noreply@example.com"
from_name = "My App"
- (Optional) Enable email verification:
crap.collections.define("users", {
auth = {
verify_email = true,
},
fields = { ... },
})
Password Reset
When email is configured, a “Forgot password?” link appears on the admin login page. The flow:
- User clicks “Forgot password?” and enters their email
- Server generates a single-use reset token (nanoid, stored in DB with 1-hour expiry). Forgot-password rate limiting applies — after
max_forgot_password_attemptsrequests withinforgot_password_window_seconds, further requests are silently accepted without sending email. - Reset email is sent with a link to
/admin/reset-password?token=xxx - User sets a new password via the form
- Token is consumed (single-use) and user is redirected to login
Available via gRPC as ForgotPassword and ResetPassword RPCs.
Security: The forgot password endpoint always returns success regardless of whether the email exists, to prevent user enumeration.
Email Verification
When verify_email: true is set on an auth collection:
- A verification email is automatically sent when a user is created (admin UI or gRPC)
- The email contains a link to
/admin/verify-email?token=xxx - Verification tokens expire after 24 hours
- Until verified, the user cannot log in (returns “Please verify your email” error)
- Clicking the verification link marks the user as verified (if token hasn’t expired)
Available via gRPC as VerifyEmail RPC.
The verification endpoint is rate-limited by IP (using the forgot-password rate limiter). Only actual token validation failures (invalid or expired tokens) count toward the rate limit — transient system errors do not penalize the user’s IP.
Note: Email verification requires SMTP to be configured. If SMTP is not configured, verification emails won’t be sent (logged as warnings) and unverified users will be unable to log in.
Auth Collections
Any collection can be an auth collection. Set auth = true for defaults, or provide a configuration table.
Simple Auth
crap.collections.define("users", {
auth = true,
-- ...
})
Auth Config Table
crap.collections.define("users", {
auth = {
token_expiry = 3600, -- 1 hour (default: 7200 = 2 hours)
disable_local = false, -- set true to disable password login
strategies = {
{
name = "api-key",
authenticate = "hooks.auth.api_key_check",
},
},
},
-- ...
})
Config Properties
| Property | Type | Default | Description |
|---|---|---|---|
token_expiry | integer | 7200 | JWT token lifetime in seconds. Overrides the global [auth] token_expiry. |
disable_local | boolean | false | When true, the password login form is hidden. Only custom strategies can authenticate. |
verify_email | boolean | false | When true, new users must verify their email before logging in. Requires email configuration. |
forgot_password | boolean | true | When true, enables the “Forgot password?” flow. Requires email configuration. |
strategies | AuthStrategy[] | {} | Custom auth strategies. See Custom Strategies. |
Email Auto-Injection
When auth = true and no email field exists in the field definitions, one is automatically injected:
crap.fields.email({
name = "email",
required = true,
unique = true,
admin = { placeholder = "user@example.com" },
})
If you define your own email field, it’s used as-is.
Password Storage
Auth collections get a hidden _password_hash TEXT column during schema migration. This column:
- Is not a regular field — it doesn’t appear in
def.fields - Is never returned in API responses
- Is never included in hook contexts
- Is never shown in admin forms
- Is only accessed by dedicated auth functions (
update_password,get_password_hash)
Password Policy
All password-setting paths (create, update, reset, CLI) enforce the password policy configured in [auth.password_policy] in crap.toml. Defaults: min 8 Unicode characters, max 128 bytes. min_length counts Unicode codepoints (so multi-byte characters count as 1). max_length counts bytes (to bound Argon2 hashing cost). See crap.toml reference for all options.
Password in Create/Update
When creating or updating a user, the password field (if present in the data) is:
- Extracted from the data before hooks run
- Hashed with Argon2id after the document is written
- Stored in the
_password_hashcolumn
In the admin UI:
- Create form — password is required
- Edit form — password is optional (“leave blank to keep current”)
Account Locking
Auth collections support a _locked system field. When a user’s _locked field is set to a truthy value (e.g., 1), that user is immediately denied access:
- JWT validation — every authenticated request checks
_lockedafter resolving the user from the token. A locked user’s token is effectively revoked, even if it hasn’t expired. MeRPC — returns anunauthenticatederror for locked users.- Admin UI — the session is rejected and the user is redirected to the login page.
Locking takes effect immediately — no token refresh or logout is needed. Use the CLI to lock/unlock users:
crap-cms -C ./my-project user lock -e admin@example.com
crap-cms -C ./my-project user unlock -e admin@example.com
JWT Claims
Tokens contain:
| Claim | Description |
|---|---|
sub | User document ID |
collection | Auth collection slug (e.g., “users”) |
email | User email |
exp | Expiration timestamp (Unix) |
iat | Issued-at timestamp (Unix) |
Auth Methods
Each auth collection declares an ordered list of methods that say how a request can prove identity for that collection. The four method types compose to express anything from “standard password user” to “machine-to-machine with API keys only”.
crap.collections.define("users", {
auth = {
enabled = true,
methods = crap.auth.default_methods(), -- password_login + bearer + session_cookie
},
})
The four method types
| Type | Purpose | Default surfaces | Notes |
|---|---|---|---|
password_login | Enables the Login RPC; issues JWTs. Owns the password-only knobs (mfa, verify_email, forgot_password). | n/a (Login is one RPC) | At most one per collection. |
bearer | Accept JWTs in Authorization: Bearer … (HTTP) / gRPC metadata. | {"grpc", "admin"} | At most one per collection. |
session_cookie | Accept the crap_session cookie. | {"admin"} | Admin-HTTP only in practice. |
strategy | Custom Lua authenticator (API keys, SSO headers, mTLS). Declares its own activates_on discriminator. | {"admin"} | Any number per collection. |
Surface scoping
Every non-password_login method takes a surfaces array listing the host transports it applies to. Today’s surfaces are "admin" and "grpc". A method whose surfaces doesn’t include the current request’s surface is skipped.
This lets you express:
-- Bearer JWT works on both surfaces, cookie only on admin:
{ type = "bearer", surfaces = { "grpc", "admin" } },
{ type = "session_cookie", surfaces = { "admin" } },
-- API-key strategy only for gRPC clients:
{ type = "strategy",
name = "svc-key",
authenticate = "hooks.auth.svc_key",
activates_on = { header = "x-service-key" },
surfaces = { "grpc" } },
Activation discriminators (strategy only)
A strategy method MUST declare when it fires. Two forms:
activates_on = { header = "x-api-key" }
The strategy is invoked only when the named header (lowercase) is present on the request. Strategy returns nil if it can’t authenticate; the evaluator moves on.
This is the safe, common case. Each strategy is bound to its own header, so two collections both listing API-key strategies on different headers cannot accidentally authenticate each other’s principals.
activates_on = { always = true }
The strategy is invoked on every request that passes the surface filter. The strategy itself decides per-request whether to authenticate. This is the escape hatch for:
- mTLS / TLS client cert — the credential isn’t a header, it’s on the connection.
- Multi-signal strategies — strategy looks at several headers + a query param and composes.
- External IdP introspection — strategy sends the request to an IdP and lets it decide.
Always-active strategies emit a startup warning since accidental always-on patterns run on every request. Use a header discriminator unless you specifically need the catch-all.
activates_on = { always = false } is rejected at config-load time — it has no useful meaning. To disable a method, remove it from methods.
Default and helper methods
crap.auth.default_methods() returns the standard set:
{
{ type = "password_login" },
{ type = "bearer", surfaces = { "grpc", "admin" } },
{ type = "session_cookie", surfaces = { "admin" } },
}
crap.auth.with_defaults(extras) returns default_methods() with the extras list appended — the usual shape for “standard auth plus my strategy”:
auth = {
enabled = true,
methods = crap.auth.with_defaults({
{ type = "strategy",
name = "api-key",
authenticate = "hooks.auth.api_key",
activates_on = { header = "x-api-key" },
surfaces = { "grpc" } },
}),
}
Evaluation order
For each incoming request:
- The evaluator walks every auth collection’s
methodsin declaration order. - For each method, it checks (a) the surface filter matches and (b) the activation discriminator matches the request.
- The first method that matches and produces a principal wins; the request proceeds authenticated as that principal.
- If no method matches, the request is anonymous.
Bearer JWTs unambiguously identify their issuing collection (claims include the collection slug), so JWTs from collection A never authenticate as collection B even if both have bearer in their methods.
Common patterns
Password user collection
auth = {
enabled = true,
methods = crap.auth.default_methods(),
}
Password user + API key for gRPC clients
auth = {
enabled = true,
methods = crap.auth.with_defaults({
{ type = "strategy", name = "api-key",
authenticate = "hooks.auth.api_key",
activates_on = { header = "x-api-key" },
surfaces = { "grpc" } },
}),
}
Machine-to-machine — API key only, no password login, no JWT
auth = {
enabled = true,
methods = {
{ type = "strategy", name = "svc-key",
authenticate = "hooks.auth.svc_key",
activates_on = { header = "x-service-key" },
surfaces = { "grpc" } },
},
}
With no password_login, the Login RPC for this collection returns INVALID_ARGUMENT. With no bearer, JWTs aren’t accepted (and aren’t issued — there’s no password_login to issue them). The API key is the only path in.
Admin-only-with-MFA, gRPC clients use Bearer
auth = {
enabled = true,
methods = {
{ type = "password_login", mfa = "email", verify_email = true },
{ type = "bearer", surfaces = { "grpc", "admin" } },
{ type = "session_cookie", surfaces = { "admin" } },
},
}
Validation rules (enforced at startup)
enabled = truewithmethods = {}→ error.- More than one
password_login→ error. - More than one
bearer→ error. strategywithoutactivates_on→ error (auto-defaults toalways = truein the parser, but the startup warning fires).- Any
strategywithactivates_on = { always = true }→ warning in the logs. - Multiple always-active strategies on the same surface → louder warning (auth depends on registration order).
See also
- Custom Strategies — the Lua function contract,
ctx.headers, returning a user document. - Auth Collections — the collection-level schema concerns.
- Login Flow — what the
LoginRPC actually does, MFA, password verification.
Login Flow
Admin UI Flow
- User visits any
/admin/*route - Gate 1:
require_authcheck — if no auth collections exist andrequire_authistrue(default), returns a “Setup Required” page (HTTP 503). Setrequire_auth = falsein[admin]for open dev mode. - Auth middleware checks for
crap_sessionHttpOnly cookie (includesSecureflag whendev_mode = false) - If no valid cookie, tries custom auth strategies, then redirects to
/admin/login - Gate 2:
admin.accesscheck — if anaccessLua function is configured in[admin], it runs after successful authentication. If the function returnsfalse/nil, the user sees an “Access Denied” page (HTTP 403) with a logout button. - User submits email + password (protected by CSRF double-submit cookie)
- Server checks rate limiting — too many failed attempts for this email triggers a temporary lockout
- Server verifies credentials against the auth collection (constant-time, even for non-existent users)
- On success: clears rate limit counter, sets
crap_sessioncookie with JWT, redirects to/admin - On failure: records failed attempt, re-renders login page with error
Public admin routes (no auth required):
/admin/login/admin/logout/admin/forgot-password/admin/reset-password/admin/verify-email/static/*
Custom strategy flow: If custom strategies are configured, the middleware checks them before redirecting to login:
- JWT cookie check (fast path)
- Custom strategies in definition order
- Redirect to login (if all fail)
Security
Rate Limiting
Login and forgot-password endpoints enforce dual rate limiting — per-email and per-IP:
- Per-email: After
max_login_attempts(default: 5) failed attempts, further login attempts for that email are blocked forlogin_lockout_seconds(default: 300s). - Per-IP: After
max_ip_login_attempts(default: 20) failed attempts from the same IP, all login attempts from that IP are blocked. The higher threshold tolerates shared IPs (offices, NAT).
Forgot-password requests are similarly limited per-email (max_forgot_password_attempts) and per-IP (max_ip_login_attempts with forgot_password_window_seconds).
[auth]
max_login_attempts = 5 # per-email threshold
max_ip_login_attempts = 20 # per-IP threshold (login + forgot-password)
login_lockout_seconds = "5m" # lockout window for login
max_forgot_password_attempts = 3
forgot_password_window_seconds = "15m"
Rate limiting applies to the admin UI login, admin forgot-password, and the gRPC Login and ForgotPassword RPCs. Behind a reverse proxy, the admin UI reads the client IP from X-Forwarded-For.
CSRF Protection
All admin UI form submissions and HTMX requests are protected by a double-submit cookie pattern:
- A
crap_csrfcookie (SameSite=Strict, not HttpOnly) is set when absent (persists with a 24-hour Max-Age) - POST, PUT, PATCH, and DELETE requests must include a matching token via either:
X-CSRF-Tokenheader (used by HTMX requests)_csrfform field (used by plain form submissions)
- Mismatched or missing tokens return 403 Forbidden
This is handled automatically by JavaScript included in the admin templates.
Timing Safety
Login always performs a full Argon2id hash comparison, even when the requested email doesn’t exist. This prevents timing-based user enumeration attacks.
gRPC Flow
Login
grpcurl -plaintext -d '{
"collection": "users",
"email": "admin@example.com",
"password": "secret123"
}' localhost:50051 crap.ContentAPI/Login
Response:
{
"token": "eyJhbGciOi...",
"user": {
"id": "abc123",
"collection": "users",
"fields": { "name": "Admin", "email": "admin@example.com", "role": "admin" }
}
}
Authenticated Requests
Pass the token via authorization metadata:
grpcurl -plaintext \
-H "authorization: Bearer eyJhbGciOi..." \
-d '{"collection": "posts"}' \
localhost:50051 crap.ContentAPI/Find
Get Current User
grpcurl -plaintext -d '{
"token": "eyJhbGciOi..."
}' localhost:50051 crap.ContentAPI/Me
Multiple Auth Collections
You can have multiple auth collections (e.g., users and admins). The Login RPC takes a collection parameter to specify which one to authenticate against.
The admin UI login always tries all auth collections.
Password Reset Flow
When email is configured ([email] section in crap.toml):
Admin UI
- User clicks “Forgot password?” on the login page
- Enters their email address and selects the auth collection
- Server generates a nanoid reset token with 1-hour expiry
- Reset email is sent with a link to
/admin/reset-password?token=xxx - User clicks the link, enters a new password
- Server validates the token, updates the password, and redirects to login
gRPC
# Step 1: Request password reset
grpcurl -plaintext -d '{
"collection": "users",
"email": "admin@example.com"
}' localhost:50051 crap.ContentAPI/ForgotPassword
# Step 2: Reset password with token from email
grpcurl -plaintext -d '{
"collection": "users",
"token": "the-token-from-email",
"new_password": "newsecret123"
}' localhost:50051 crap.ContentAPI/ResetPassword
Note: ForgotPassword always returns success to prevent user enumeration.
Email Verification Flow
When verify_email: true is set on an auth collection:
Admin UI
- User is created (via admin form or gRPC)
- Verification email is sent automatically with a link to
/admin/verify-email?token=xxx - Verification tokens expire after 24 hours
- User clicks the verification link (expired tokens show an error)
- Login attempts before verification return “Please verify your email”
gRPC
grpcurl -plaintext -d '{
"collection": "users",
"token": "the-token-from-email"
}' localhost:50051 crap.ContentAPI/VerifyEmail
Custom Strategies
Custom auth strategies let you authenticate users via mechanisms other than password login — API keys, LDAP, SSO headers, etc. They are one variant of the auth.methods list (see Auth Methods for the overall model).
Configuration
crap.collections.define("users", {
auth = {
enabled = true,
methods = crap.auth.with_defaults({
-- API-key strategy: only fires when `x-api-key` header is present.
{ type = "strategy",
name = "api-key",
authenticate = "hooks.auth.api_key_check",
activates_on = { header = "x-api-key" },
surfaces = { "grpc", "admin" } },
-- SSO strategy: only fires when the SSO assertion header is present.
{ type = "strategy",
name = "sso",
authenticate = "hooks.auth.sso_check",
activates_on = { header = "x-sso-assertion" },
surfaces = { "admin" } },
}),
},
-- ...
})
To disable password login entirely (machine-to-machine collection), omit password_login from the methods list:
auth = {
enabled = true,
methods = {
{ type = "strategy",
name = "svc-key",
authenticate = "hooks.auth.svc_key",
activates_on = { header = "x-service-key" },
surfaces = { "grpc" } },
},
}
Strategy Properties
| Property | Type | Description |
|---|---|---|
type | "strategy" | Discriminator. Required. |
name | string | Strategy name for logging and identification. |
authenticate | string | Lua function ref in module.function format. |
activates_on | table | When the strategy fires: { header = "x-..." } or { always = true }. Required. |
surfaces | string[] | Host transports the strategy is allowed on (default: {"admin"}). |
Authenticate Function
The function receives a context table and returns a user document (table) or nil/false.
-- hooks/auth.lua
local M = {}
function M.api_key_check(ctx)
-- ctx.headers = table of request headers (lowercase keys)
-- ctx.collection = auth collection slug ("users")
local key = ctx.headers["x-api-key"]
if key == nil then return nil end
-- Look up user by API key
local result = crap.collections.find(ctx.collection, {
where = { api_key = key },
limit = 1,
})
if result.total > 0 then
return result.documents[1] -- return user document
end
return nil -- strategy didn't match
end
return M
Context Table
| Field | Type | Description |
|---|---|---|
headers | table | HTTP request headers (lowercase keys, string values) |
collection | string | Auth collection slug |
CRUD Access
Strategy functions have full CRUD access (via the same TxContext pattern as hooks). They can query the database to look up users.
Execution Order
For every request (admin or gRPC):
- The evaluator walks every registered auth collection’s
methodsin declaration order. - For each method, it checks: (a) the surface filter includes the current request’s surface, and (b) the activation discriminator matches (for
strategy: the named header is present, oralways = true). - The first method that matches and produces a principal wins.
- If no method matches, the request is anonymous.
Each strategy is bound to its own activation signal — cross-collection accidental authentication is structurally impossible.
Disabling Password Login
Omit password_login from the methods list:
auth = {
enabled = true,
methods = {
{ type = "strategy", name = "sso",
authenticate = "hooks.auth.sso_check",
activates_on = { header = "x-sso-assertion" },
surfaces = { "admin" } },
},
}
When password_login is absent:
- The login form shows a message instead of email/password inputs.
- Only the listed strategy methods can authenticate users.
- The
LogingRPC RPC for this collection returnsINVALID_ARGUMENT.
Omit bearer similarly to refuse JWT authentication (rarely useful — usually paired with omitting password_login since the JWT can’t be issued without it).
Performance + safety notes
- No per-call timeout. Strategy hooks run synchronously inside a
spawn-blocking pool. mlua doesn’t expose a clean interruption API,
and abandoning the worker would leak the blocking thread. A hostile
or buggy strategy can hang the request indefinitely. Keep strategies
fast (a DB lookup or two, no network calls), and prefer
header-discriminated activation over
always = trueso slow code only runs when the activating header is present. - Strategy returns are sanity-checked. The evaluator refuses any
returned document with an empty
id(would silently break session- version lookups downstream) and re-runsis_locked/verify_emailagainst the returned doc (so a strategy can’t authenticate a locked or unverified user even if the strategy code overlooks the check). - No session-version on strategy auth. Bearer / cookie paths
reject a JWT whose
session_versiondoesn’t match the user’s current version; strategies don’t issue a JWT to the client (the Claims object is internal-only), so there’s nothing to compare against. Lock the user (crap-cms user lock -e ...) to revoke strategy access —is_lockedis the cross-method kill switch.
Auth Callbacks (OAuth2 / OIDC)
For redirect-based auth flows (OAuth2, OIDC, SAML), use the built-in callback route:
GET/POST /admin/auth/callback/{name}
This dispatches to a Lua hook auth_callback.{name} which receives request headers and query parameters. The hook returns a user document to create a session.
-- hooks/auth_callback/google.lua
local M = {}
function M.google(ctx)
-- ctx.headers._query_code contains the OAuth authorization code
local code = ctx.headers["_query_code"]
if not code then return nil end
-- Exchange code for tokens
local res = crap.http.request({
method = "POST",
url = "https://oauth2.googleapis.com/token",
json = {
code = code,
client_id = crap.env.get("GOOGLE_CLIENT_ID"),
client_secret = crap.env.get("GOOGLE_CLIENT_SECRET"),
redirect_uri = crap.env.get("GOOGLE_REDIRECT_URI"),
grant_type = "authorization_code",
},
})
if res.status ~= 200 then return nil end
local tokens = crap.json.decode(res.body)
-- Get user info
local info_res = crap.http.request({
url = "https://www.googleapis.com/oauth2/v2/userinfo",
headers = { Authorization = "Bearer " .. tokens.access_token },
})
local userinfo = crap.json.decode(info_res.body)
-- Find or create user
local users = crap.find("users", { where = { email = userinfo.email } })
if #users.documents > 0 then return users.documents[1] end
return crap.create("users", {
email = userinfo.email,
name = userinfo.name,
})
end
return M
To initiate the OAuth flow, add a link on your login page pointing to the provider’s authorize URL with your redirect_uri set to /admin/auth/callback/google.
Email MFA
Auth collections can require a second factor after password verification:
auth = {
mfa = "email", -- "email" or false (default)
}
When enabled, after successful password/strategy authentication, a 6-digit code is emailed to the user. They must enter the code to complete login. Codes expire after 5 minutes and are single-use.
CLI User Creation
The user create command bootstraps users without the admin UI or gRPC API. Useful for creating the first admin user.
Interactive Mode
Prompts for password with hidden input and confirmation:
crap-cms user create -e admin@example.com
Output:
Password: ********
Confirm password: ********
Created user abc123 in 'users'
If required fields have no default value, you’ll be prompted for those too.
Non-Interactive Mode
For CI/scripting. The -p flag skips the prompt:
crap-cms user create \
-e admin@example.com \
-p secret123 \
-f role=admin \
-f name="Admin User"
Warning: The password may be visible in shell history. Use interactive mode for production bootstrapping.
Flags
| Flag | Short | Description |
|---|---|---|
--collection | -c | Auth collection to create the user in (default: users) |
--email | -e | User email (prompted if omitted) |
--password | -p | User password (prompted if omitted) |
--field | -f | Extra field values as key=value (repeatable) |
Behavior
- Runs after Lua definitions are loaded and database schema is synced
- No hooks are fired (this is a bootstrap/admin tool)
- Creates the user in a single transaction
- Hashes the password with Argon2id
- Exits after creating the user (does not start the server)
Field Handling
- Required fields with
default_value— uses the default, prompts with[default]if interactive - Required fields without defaults — prompts for input, fails if empty
- Optional fields — skipped unless provided via
-f - Checkbox fields — skipped (absent = false)
- Email field — always required (handled separately from
-f)
Examples
# Minimal (will prompt for everything else)
crap-cms user create
# Different collection
crap-cms user create -c admins \
-e boss@example.com
# Full non-interactive
crap-cms user create \
-e editor@example.com \
-p pass123 \
-f name="Jane Editor" \
-f role=editor
Other User Commands
# Show detailed info for a user
crap-cms user info -e admin@example.com
# List all users
crap-cms user list
# Lock/unlock a user
crap-cms user lock -e user@example.com
crap-cms user unlock -e user@example.com
# Verify/unverify a user (requires verify_email: true on collection)
crap-cms user verify -e user@example.com
crap-cms user unverify -e user@example.com
# Change password
crap-cms user change-password -e user@example.com
# Delete a user (with confirmation skip)
crap-cms user delete -e user@example.com -y
Access Control
Crap CMS provides opt-in access control at both collection and field levels. Access functions are Lua function refs that return one of three values:
true— allowedfalseornil— denied- A filter table (read only) — allowed with query constraints
Opt-In
By default, collections and globals without explicit access functions deny all operations (default_deny = true). Every collection must explicitly declare its access rules.
To allow all operations on collections without access functions (e.g., during development), set default_deny = false in [access] in crap.toml.
Three Levels
- Admin panel-level —
admin.accessincrap.toml. A Lua function that gates access to the entire admin UI, checked after login. See Admin UI. - Collection-level — controls who can read, create, update, or delete documents in a collection. See Collection-Level.
- Field-level — controls which fields are visible or writable per-user. See Field-Level.
Access Function Context
All access functions receive a context table:
function M.check(ctx)
-- ctx.user = full user document (or nil if anonymous)
-- ctx.id = document ID (for update/delete/find_by_id)
-- ctx.data = incoming data (for create/update)
return true -- or false, or a filter table
end
| Field | Type | Present When | Description |
|---|---|---|---|
user | table or nil | Always | Full user document from the auth collection. nil if no auth or anonymous. |
id | string or nil | update, delete, find_by_id | Document ID |
data | table or nil | create, update | Incoming data |
CRUD Access in Access Functions
Access functions run with transaction context — they can call crap.collections.find() etc. to make decisions based on data in other collections.
Note: Lua CRUD functions enforce access control by default (
overrideAccess = false). If your access function calls CRUD internally, passoverrideAccess = trueto avoid recursive access checks:function M.check(ctx) local count = crap.collections.items.count({ overrideAccess = true }) return count < 100 -- allow if under limit end
Collection-Level Access Control
Collection-level access controls who can perform CRUD operations on a collection.
Configuration
crap.collections.define("posts", {
access = {
read = "hooks.access.public_read",
create = "hooks.access.authenticated",
update = "hooks.access.authenticated",
trash = "hooks.access.authenticated",
delete = "hooks.access.admin_only",
},
-- ...
})
Each property is a Lua function ref (string) or nil (no restriction).
| Property | Controls | Fallback |
|---|---|---|
read | Find and FindByID operations | — |
create | Create operation | — |
update | Update operation | — |
trash | Soft-delete (move to trash) and restore. Only relevant when soft_delete = true. | update |
delete | Permanent deletion, empty trash. For collections without soft_delete, this is the only delete permission. | — |
Note: When
soft_delete = true,trashanddeleteare separate permissions.trashcontrols the reversible action (low privilege),deletecontrols the destructive action (high privilege). Iftrashis not set, it falls back toupdate. Ifdeleteis not set, permanent deletion is restricted to the auto-purge scheduler. See Soft Deletes.
Writing Access Functions
Access functions live in Lua modules under the config directory:
-- hooks/access.lua
local M = {}
-- Allow anyone (including anonymous)
function M.public_read(ctx)
return true
end
-- Require any authenticated user
function M.authenticated(ctx)
return ctx.user ~= nil
end
-- Require admin role
function M.admin_only(ctx)
return ctx.user ~= nil and ctx.user.role == "admin"
end
-- Allow users to only read their own documents
function M.own_only(ctx)
if ctx.user == nil then return false end
if ctx.user.role == "admin" then return true end
return { created_by = ctx.user.id } -- filter constraint
end
return M
Return Values
| Return Value | Effect |
|---|---|
true | Operation is allowed |
false or nil | Operation is denied (403/permission error) |
| table | Read operation is allowed with additional WHERE filters (see Filter Constraints) |
Filter table returns are only meaningful for read access. For create, update, and delete, a table return is treated as Allowed.
Enforcement Points
- Admin UI — middleware checks access before rendering pages
- gRPC API — service checks access before executing operations
- Access is checked once, before the operation begins
Field-Level Access Control
Field-level access controls which fields are visible or writable per-user.
Configuration
crap.fields.select({
name = "status",
access = {
read = "hooks.access.everyone",
create = "hooks.access.admin_only",
update = "hooks.access.admin_only",
},
-- ...
})
| Property | Controls |
|---|---|
read | Whether the field appears in API responses |
create | Whether the field can be set on create |
update | Whether the field can be changed on update |
Omitted properties default to allowed (no restriction).
How It Works
Write Access (create/update)
Before a write operation, denied fields are stripped from the input data. The operation proceeds with the remaining fields. This means:
- On create: denied fields get their default value (or NULL)
- On update: denied fields keep their current value
This is silent. Stripping happens before validation and before any hook sees the data — the client gets no error or warning that fields were dropped, and the returned document reflects the stored state. If a client reports “I set field X but it didn’t save”, check whether field-level access is denying their role for that field.
Read Access
After a query, denied fields are stripped from the response. The field still exists in the database, but the user doesn’t see it.
Fields with admin.hidden = true are also stripped from all API responses, regardless of access rules.
Example
-- hooks/access.lua
local M = {}
-- Only admins can see the internal_notes field
function M.admin_read(ctx)
return ctx.user ~= nil and ctx.user.role == "admin"
end
-- Only admins can change the status field
function M.admin_write(ctx)
return ctx.user ~= nil and ctx.user.role == "admin"
end
return M
-- In collection definition
crap.fields.textarea({
name = "internal_notes",
access = {
read = "hooks.access.admin_read",
},
}),
crap.fields.select({
name = "status",
access = {
update = "hooks.access.admin_write",
},
-- ...
}),
Error Behavior
If a field access function throws an error, the field is treated as denied (fail-closed) and a warning is logged.
Filter Constraints
Read access functions can return a filter table instead of a boolean. The filters are merged as AND clauses into the query, restricting which documents the user can see.
Basic Usage
function M.own_posts(ctx)
if ctx.user == nil then return false end
if ctx.user.role == "admin" then return true end
-- Regular users can only see their own posts
return { author = ctx.user.id }
end
When this function returns { author = ctx.user.id }, the query gets an additional WHERE author = ? clause. The user only sees documents where author matches their ID.
Filter Format
The returned table uses the same format as crap.collections.find() filters:
-- Simple equality
return { status = "published" }
-- Operator-based filter
return { status = { not_equals = "archived" } }
-- Multiple constraints (AND)
return {
status = "published",
department = ctx.user.department,
}
How Constraints Are Merged
Constraints from access functions are merged with any existing query filters using AND:
Final WHERE = (user's filters) AND (access constraints)
This means constraints can only narrow results, never expand them.
Example: Multi-Tenant Access
function M.tenant_read(ctx)
if ctx.user == nil then return false end
-- Users can only see documents in their tenant
return { tenant_id = ctx.user.tenant_id }
end
Example: Published-Only for Anonymous
function M.public_or_own(ctx)
if ctx.user == nil then
return { status = "published" }
end
if ctx.user.role == "admin" then
return true -- admins see everything
end
-- Authors see their own + published
-- (Note: complex OR logic isn't supported in filter returns)
return { author = ctx.user.id }
end
Uploads
Upload collections handle file storage with automatic metadata tracking. Enable uploads by setting upload = true or providing a config table.
Configuration
crap.collections.define("media", {
labels = { singular = "Media", plural = "Media" },
upload = {
mime_types = { "image/*" },
max_file_size = "10MB", -- accepts bytes or "10MB", "1GB", etc.
image_sizes = {
{ name = "thumbnail", width = 300, height = 300, fit = "cover" },
{ name = "card", width = 640, height = 480, fit = "cover" },
},
admin_thumbnail = "thumbnail",
format_options = {
webp = { quality = 80 },
avif = { quality = 60 },
},
},
fields = {
crap.fields.text({ name = "alt", admin = { description = "Alt text" } }),
},
})
Upload Config Properties
| Property | Type | Default | Description |
|---|---|---|---|
mime_types | string[] | {} (any) | MIME type allowlist. Supports glob patterns ("image/*"). Empty = allow all. |
max_file_size | integer/string | global default | Max file size. Accepts bytes (integer) or human-readable ("10MB", "1GB"). Overrides [upload] max_file_size in crap.toml. |
image_sizes | ImageSize[] | {} | Resize definitions for image uploads. See Image Processing. |
admin_thumbnail | string | nil | Name of an image_sizes entry to use as thumbnail in admin lists. |
format_options | table | {} | Auto-generate format variants. See Image Processing. |
Auto-Injected Fields
When uploads are enabled, these fields are automatically injected before your custom fields:
| Field | Type | Admin form | Description |
|---|---|---|---|
filename | text | Visible (readonly) | Sanitized filename with unique prefix |
mime_type | text | Hidden | MIME type of the uploaded file |
filesize | number | Hidden | File size in bytes |
width | number | Hidden | Image width (images only) |
height | number | Hidden | Image height (images only) |
url | text | Hidden | URL path to the original file |
focal_x | number | Hidden | Focal point X coordinate (0.0–1.0, default center) |
focal_y | number | Hidden | Focal point Y coordinate (0.0–1.0, default center) |
All auto-injected fields are always returned in API responses (gRPC, Lua, MCP, REST, admin JSON). They use
admin.hidden = trueonly — that flag suppresses standard form rendering because the upload preview widget and focal-point selector render these values directly. Consumers (and the admin’s own preview widget) need them to display thumbnails, focal crops, and image variants.
For each image size, additional fields are injected:
| Field Pattern | Type | Description |
|---|---|---|
{size}_url | text | URL to the resized image |
{size}_width | number | Actual width after resize |
{size}_height | number | Actual height after resize |
{size}_webp_url | text | URL to WebP variant (if enabled) |
{size}_avif_url | text | URL to AVIF variant (if enabled) |
File Storage
By default, files are stored on the local filesystem at <config_dir>/uploads/<collection_slug>/:
uploads/
└── media/
├── a1b2c3_my-photo.jpg # original
├── a1b2c3_my-photo_thumbnail.jpg # resized
├── a1b2c3_my-photo_thumbnail.webp
├── a1b2c3_my-photo_thumbnail.avif
├── a1b2c3_my-photo_card.jpg
├── a1b2c3_my-photo_card.webp
└── a1b2c3_my-photo_card.avif
Filenames are sanitized (lowercase, characters that are not alphanumeric, hyphens, or underscores are replaced with hyphens) and prefixed with a random 10-character nanoid.
Storage Backends
The storage backend is configurable via [upload] storage in crap.toml. Local filesystem is the default and recommended for most deployments.
Local (default)
[upload]
storage = "local" # or omit — local is the default
No additional configuration needed. Files stored at {config_dir}/uploads/.
S3-Compatible (optional)
For multi-server deployments where multiple instances need to share uploaded files. Works with AWS S3, MinIO, Cloudflare R2, Backblaze B2, and DigitalOcean Spaces. Requires --features s3-storage at build time.
[upload]
storage = "s3"
[upload.s3]
bucket = "my-uploads"
region = "us-east-1"
endpoint = "https://s3.amazonaws.com" # or MinIO/R2 URL
access_key = "${AWS_ACCESS_KEY}"
secret_key = "${AWS_SECRET_KEY}"
prefix = "" # optional key prefix
public_url_base = "" # CDN URL (empty = S3 URLs)
path_style = false # true for MinIO
| Field | Required | Description |
|---|---|---|
bucket | Yes | S3 bucket name |
region | No | AWS region (default: us-east-1) |
endpoint | No | Custom endpoint for non-AWS providers |
access_key | Yes | AWS access key ID |
secret_key | Yes | AWS secret access key |
prefix | No | Key prefix prepended to all storage keys |
public_url_base | No | Base URL for public file links (e.g., CDN) |
path_style | No | Use path-style URLs (required for MinIO) |
Files are served through the CMS via /uploads/... (proxied from S3) so access control and content negotiation work identically to local storage.
Tip: Use
queue: trueon image format options (WebP, AVIF) when using S3. Deferred processing avoids upload latency from the extra S3 round trips.
Custom (Lua)
For exotic storage providers, register custom functions in init.lua:
crap.storage.register({
put = function(key, data, content_type)
crap.http.request({
method = "PUT",
url = "https://storage.example.com/" .. key,
body = data,
headers = { ["Content-Type"] = content_type },
})
end,
get = function(key)
local resp = crap.http.request({
url = "https://storage.example.com/" .. key,
})
return resp.body
end,
delete = function(key)
crap.http.request({
method = "DELETE",
url = "https://storage.example.com/" .. key,
})
end,
url = function(key)
return "https://cdn.example.com/" .. key
end,
})
[upload]
storage = "custom"
Binary data is passed natively between Rust and Lua (no base64 encoding). The crap.http.request function handles binary request/response bodies.
URL Structure
Files are served at /uploads/<collection>/<filename>:
/uploads/media/a1b2c3_my-photo.jpg
/uploads/media/a1b2c3_my-photo_thumbnail.webp
API Response
The sizes field in API responses is a structured object assembled from the per-size columns:
{
"url": "/uploads/media/a1b2c3_my-photo.jpg",
"filename": "a1b2c3_my-photo.jpg",
"sizes": {
"thumbnail": {
"url": "/uploads/media/a1b2c3_my-photo_thumbnail.jpg",
"width": 300,
"height": 300,
"formats": {
"webp": { "url": "/uploads/media/a1b2c3_my-photo_thumbnail.webp" },
"avif": { "url": "/uploads/media/a1b2c3_my-photo_thumbnail.avif" }
}
}
}
}
MIME Type Patterns
| Pattern | Matches |
|---|---|
"image/*" | All image types (png, jpeg, gif, webp, etc.) |
"application/pdf" | Only PDF files |
"*/*" or "*" | Any file type |
Empty mime_types array also accepts any file.
Error Cleanup
If an error occurs during upload processing (e.g., image resize fails partway through), all files written so far are automatically cleaned up. This prevents orphaned files from accumulating on disk.
Content Negotiation
When serving image files, the upload handler performs automatic content negotiation based on the browser’s Accept header. If a modern format variant exists on disk, it is served instead of the original:
- AVIF — served if the client sends
Accept: image/avifand a.avifvariant exists - WebP — served if the client sends
Accept: image/webpand a.webpvariant exists - Original — served if no matching variant exists
AVIF is preferred over WebP when both are accepted. The response includes a Vary: Accept header so caches store format-specific versions correctly.
This works for all image URLs (/uploads/...) including originals and resized variants. Non-image files (PDFs, etc.) are always served as-is.
Focal Point
Upload collections include focal_x and focal_y fields that store the subject/focus coordinates of an image as floats in the 0.0–1.0 range. Center is (0.5, 0.5).
Setting in Admin UI: On the upload collection edit page, click anywhere on the image preview to set the focal point. A crosshair marker shows the current position. The values are saved with the form.
Frontend usage: Use the coordinates with CSS object-position to keep the subject in frame when cropping at different aspect ratios:
.responsive-image {
object-fit: cover;
object-position: calc(var(--focal-x) * 100%) calc(var(--focal-y) * 100%);
}
Or inline from template data:
<img src="/uploads/media/photo.jpg"
style="object-fit: cover; object-position: 50% 30%;" />
The values are available in API responses as focal_x and focal_y number fields.
File Deletion
When a document in an upload collection is deleted, all associated files (original + resized + format variants) are deleted from disk.
Image Processing
When an upload collection has image_sizes configured, uploaded images are automatically resized and optionally converted to modern formats.
Image Sizes
Each size definition creates a resized variant of the uploaded image:
image_sizes = {
{ name = "thumbnail", width = 300, height = 300, fit = "cover" },
{ name = "card", width = 640, height = 480, fit = "contain" },
{ name = "hero", width = 1920, height = 1080, fit = "inside" },
}
Size Properties
| Property | Type | Default | Description |
|---|---|---|---|
name | string | required | Size identifier. Used in URLs and field names. |
width | integer | required | Target width in pixels |
height | integer | required | Target height in pixels |
fit | string | "cover" | Resize fit mode |
Fit Modes
| Mode | Behavior |
|---|---|
cover | Resize to fill the target dimensions, then center-crop. No empty space. Aspect ratio preserved. |
contain | Resize to fit within the target dimensions. May be smaller than target. Aspect ratio preserved. |
inside | Same as contain — resize to fit within bounds, preserving aspect ratio. |
fill | Stretch to exact target dimensions. Aspect ratio may change. |
Format Options
Generate modern format variants for each image size:
format_options = {
webp = { quality = 80 }, -- WebP at 80% quality
avif = { quality = 60 }, -- AVIF at 60% quality
}
| Format | Quality Range | Notes |
|---|---|---|
webp | 1-100 | Lossy WebP via libwebp |
avif | 1-100 | AVIF via the image crate’s AVIF encoder (speed=8) |
Format variants are generated for each image size, not for the original. This keeps original files untouched.
Background Queue
By default, format conversion happens synchronously during upload. For large images or slow formats like AVIF, you can defer conversion to a background queue:
format_options = {
webp = { quality = 80 },
avif = { quality = 60, queue = true }, -- processed in background
}
When queue = true:
- The upload completes immediately without generating that format variant
- A queue entry is inserted into the
_crap_image_queuetable - The scheduler picks up pending entries and processes them in the background
- Once complete, the document’s URL column is updated with the new file path
This is useful for AVIF which is significantly slower to encode than WebP. The queue option is per-format — you can queue AVIF while keeping WebP synchronous.
Use the images CLI command to inspect and manage the queue:
crap-cms -C ./my-project images stats # counts by status
crap-cms -C ./my-project images list # list recent entries
crap-cms -C ./my-project images list -s failed # show only failed
crap-cms -C ./my-project images retry --all -y # retry all failed
crap-cms -C ./my-project images purge --older-than 7d # clean up old entries
Processing Pipeline
For each uploaded image:
- Original — saved as-is to
uploads/<collection>/<id>_<filename> - Image dimensions — read from the decoded image
- Per-size variants — resized according to fit mode, saved in the original format
- Format variants — each sized image is also saved as WebP and/or AVIF (if configured)
Non-image files (PDFs, etc.) skip steps 2-4.
Decompression Bomb Protection
Before any resizing or format conversion, image dimensions are checked against a hard
limit of 100 megapixels total (width × height). Images exceeding this limit are
rejected with an error like Image too large: 12000x9000 exceeds pixel limit.
This protects the server from “decompression bomb” inputs — small, highly compressed files that decode into enormous bitmaps (e.g. a 50 KB PNG decoding to a 50,000 × 50,000 canvas), which would otherwise consume gigabytes of RAM during resizing.
The limit is fixed at 100 megapixels and is not configurable. For reference: a 12,000 × 8,000 pixel image (96 MP) is accepted; a 12,000 × 9,000 image (108 MP) is rejected. File-size and MIME-type checks are independent and run alongside this check.
Admin Thumbnail
Set admin_thumbnail to the name of an image size to display it in admin list views:
upload = {
image_sizes = {
{ name = "thumbnail", width = 300, height = 300, fit = "cover" },
},
admin_thumbnail = "thumbnail",
}
Example: Full Media Collection
crap.collections.define("media", {
labels = { singular = "Media", plural = "Media" },
upload = {
mime_types = { "image/*" },
max_file_size = 10485760,
image_sizes = {
{ name = "thumbnail", width = 300, height = 300, fit = "cover" },
{ name = "card", width = 640, height = 480, fit = "cover" },
{ name = "hero", width = 1920, height = 1080, fit = "inside" },
},
admin_thumbnail = "thumbnail",
format_options = {
webp = { quality = 80 },
avif = { quality = 60 },
},
},
fields = {
crap.fields.text({ name = "alt", admin = { description = "Alt text for accessibility" } }),
crap.fields.textarea({ name = "caption" }),
},
})
Uploading from Client Apps
File uploads in Crap CMS use dedicated HTTP endpoints that accept multipart form data and return JSON. These are separate from the admin UI routes and designed for programmatic use.
Upload API Endpoints
| Method | Route | Description |
|---|---|---|
POST | /api/upload/{slug} | Upload file + create document |
PATCH | /api/upload/{slug}/{id} | Replace file on existing document |
DELETE | /api/upload/{slug}/{id} | Delete document + files |
All endpoints require authentication via Authorization: Bearer <jwt> header and return JSON responses.
Upload Flow
Uploading is a two-step process:
- Upload the file — POST a multipart form to create a document in the upload collection
- Reference it — use the upload document’s ID as a relationship field value in other collections
Creating an Upload
POST /api/upload/{slug}
Content-Type: multipart/form-data
Authorization: Bearer <jwt>
Form Fields
| Field | Type | Description |
|---|---|---|
_file | file | The file to upload (required) |
| Any other field | text | Custom fields defined on the collection (e.g., alt, caption) |
Response
201 Created
Content-Type: application/json
{
"document": {
"id": "abc123",
"filename": "a1b2c3_photo.jpg",
"mime_type": "image/jpeg",
"filesize": 245760,
"url": "/uploads/media/a1b2c3_photo.jpg",
"width": 1920,
"height": 1080,
"alt": "A beautiful sunset",
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T10:30:00Z"
}
}
Example: cURL
curl -X POST http://localhost:3000/api/upload/media \
-H "Authorization: Bearer $TOKEN" \
-F "_file=@/path/to/photo.jpg" \
-F "alt=A beautiful sunset"
Example: JavaScript (fetch)
const form = new FormData();
form.append('_file', fileInput.files[0]);
form.append('alt', 'A beautiful sunset');
const response = await fetch('/api/upload/media', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
body: form,
});
const { document } = await response.json();
console.log(document.url); // /uploads/media/a1b2c3_photo.jpg
Example: Python (requests)
import requests
files = {'_file': open('photo.jpg', 'rb')}
data = {'alt': 'A beautiful sunset'}
response = requests.post(
'http://localhost:3000/api/upload/media',
files=files,
data=data,
headers={'Authorization': f'Bearer {token}'},
)
doc = response.json()['document']
Replacing a File
Replace the file on an existing upload document. Old files are cleaned up on success.
PATCH /api/upload/{slug}/{id}
Content-Type: multipart/form-data
Authorization: Bearer <jwt>
The form fields are the same as create. The _file field is optional — if omitted, only the metadata fields are updated.
curl -X PATCH http://localhost:3000/api/upload/media/abc123 \
-H "Authorization: Bearer $TOKEN" \
-F "_file=@/path/to/new-photo.jpg" \
-F "alt=Updated caption"
Response
{
"document": {
"id": "abc123",
"filename": "x9y8z7_new-photo.jpg",
"url": "/uploads/media/x9y8z7_new-photo.jpg",
"alt": "Updated caption",
"updated_at": "2025-01-15T11:00:00Z"
}
}
Deleting an Upload
Delete an upload document and all associated files (original + resized + format variants).
DELETE /api/upload/{slug}/{id}
Authorization: Bearer <jwt>
curl -X DELETE http://localhost:3000/api/upload/media/abc123 \
-H "Authorization: Bearer $TOKEN"
Response
{
"success": true
}
Error Responses
All error responses follow the same format:
{
"error": "description of what went wrong"
}
| Status | Cause |
|---|---|
400 | Bad request (no file, invalid MIME type, file too large, validation error) |
403 | Access denied (missing or invalid token, access control denied) |
404 | Collection or document not found |
500 | Server error |
Server Processing
When the server receives an upload:
- Validates the MIME type against the collection’s
mime_typesallowlist - Checks file size against
max_file_size - Sanitizes the filename (lowercase, hyphens, unique prefix)
- Saves the original file to
uploads/{collection}/{nanoid}_{filename}(a random 10-character nanoid prefix, not the document ID) - Resizes images according to
image_sizes(if configured) - Generates WebP/AVIF variants (if
format_optionsconfigured) - Runs before-hooks within a transaction
- Creates a document with all metadata fields populated
- Fires after-hooks and publishes live events
Downloading Files
Files are served via HTTP GET:
GET /uploads/{collection}/{filename}
# Public file (no access.read configured)
curl http://localhost:3000/uploads/media/a1b2c3_photo_thumbnail.webp
# Protected file (requires auth)
curl http://localhost:3000/uploads/media/a1b2c3_photo.jpg \
-H "Authorization: Bearer ${TOKEN}"
Caching
| Access | Cache-Control |
|---|---|
Public (no access.read) | public, max-age=31536000, immutable |
Protected (access.read configured) | private, no-store |
Using Uploads in Other Collections
Reference upload documents via relationship fields:
-- collections/posts.lua
crap.collections.define("posts", {
fields = {
crap.fields.text({ name = "title", required = true }),
crap.fields.relationship({
name = "cover_image",
relationship = { collection = "media", has_many = false },
}),
},
})
Then when creating a post, pass the upload document’s ID:
# gRPC
grpcurl -plaintext -d '{
"collection": "posts",
"data": {
"title": "My Post",
"cover_image": "the_upload_id"
}
}' localhost:50051 crap.ContentAPI/Create
With depth = 1, the upload document is fully populated in the response, giving you access to all URLs and sizes.
Authentication
Upload API endpoints use Bearer token authentication:
Authorization: Bearer <jwt>
Obtain a token via the Login gRPC RPC or the admin login flow. Access control on the upload collection (access.create, access.update, access.delete) is enforced the same as for gRPC operations.
Lua API
The crap global table is the entry point for all CMS operations in Lua. It’s available in init.lua, collection definitions, and hook functions.
Namespace
| Namespace | Description |
|---|---|
crap.collections | Collection definition, CRUD operations, and per-collection typing factories (crap.collections.<slug>.{hook,field_hook,condition,access,auth_strategy,row_label}) |
crap.globals | Global definition, get/update, and per-global typing factories |
crap.any | Cross-collection typing factories — crap.any.{collection_hook,field_hook,access,auth_strategy,job_handler,row_label,display_condition} |
crap.fields | Field factory functions (crap.fields.text(), etc.) |
crap.hooks | Global hook registration |
crap.jobs | Job definition |
crap.log | Structured logging |
crap.util | Utility functions |
crap.auth | Password hashing and verification (Argon2id) |
crap.env | Read-only environment variable access |
crap.http | Outbound HTTP requests (blocking) |
crap.config | Read-only access to crap.toml values |
crap.locale | Locale configuration queries |
crap.email | Send email via configured SMTP |
crap.crypto | Cryptographic utilities (HMAC, random bytes, hashing) |
crap.schema | Runtime schema introspection |
crap.richtext | Custom rich text node registration |
Typed hook factories
Every callable a Lua user writes — collection hooks, field hooks, access functions, auth strategies, job handlers, row labels, display conditions — should be wrapped in a typing factory so the editor can infer the parameter types of the function body.
-- Per-collection: ctx narrows to crap.hook.Posts
return crap.collections.posts.hook(function(context)
-- context.data.title, context.operation, etc. all typed
return context
end)
-- Per-collection per-field: value narrows to the field's type
return crap.collections.posts.field_hook("title", function(value, context)
-- value: string (from posts.title's text field)
return value:lower()
end)
-- Cross-collection generic (hook that runs on multiple collections)
return crap.any.field_hook(function(value, context)
-- value: any, context: crap.FieldHookContext
return value
end)
-- Access function (uniform context across all collections)
return crap.any.access(function(context)
return context.user ~= nil
end)
The factories are pure pass-throughs at runtime (f(fn) = fn); they
exist solely so LuaLS can propagate the typed parameter slot into
your function body’s locals. Requires "type.inferParamType": true
in your .luarc.json — included in the init scaffold by default.
See crap.collections and crap.globals
for the full per-slug factory surface; crap.any
for the cross-collection helpers.
Two ways to address a collection
Every defined collection is reachable in two forms:
- Per-collection accessor (recommended for static slugs):
crap.collections.<slug>.find(query),crap.collections.<slug>.create(data), … Slug is bound, return values fully typed for editor autocomplete. - Slug-keyed dispatch (required for dynamic slugs):
crap.collections.find(slug, query),crap.collections.create(slug, data), … Same semantics, slug passed at call time. Use when the collection varies at runtime (auth strategies, generic plugins, migration loops).
Globals follow the same pattern: crap.globals.<slug>.{get,update}(...)
versus crap.globals.{get,update}(slug, ...).
See crap.collections and crap.globals
for the full surface of each accessor.
CRUD Availability
CRUD functions (whether called as crap.collections.<slug>.find(...) or
crap.collections.find(slug, ...), and crap.globals.<slug>.{get,update}(...)
or the slug-keyed equivalents) are only available inside hooks with
transaction context:
before_validatehooks — Yesbefore_changehooks — Yesbefore_deletehooks — Yesafter_changehooks — Yes (runs inside the same transaction viarun_hooks_with_conn)after_deletehooks — Yes (runs inside the same transaction viarun_hooks_with_conn)after_readhooks — No (no transaction)before_readhooks — No (no transaction)- Collection definition files — No
Calling CRUD functions outside of transaction context results in an error:
crap.collections CRUD functions are only available inside hooks
with transaction context (before_change, before_delete, etc.)
Lua VM Architecture
Crap CMS uses two stages of Lua execution:
- Startup VM — a single VM that loads collection/global definitions and runs
init.lua. Used only during initialization, then discarded. - HookRunner pool — a pool of Lua VMs for runtime hook execution (size configured via
hooks.vm_pool_size). Each VM gets its own copy of thecrap.*API with CRUD functions registered.
All VMs have the config directory on their package path, so require("hooks.posts") works in both stages.
crap.collections
Collection definition and runtime CRUD operations.
crap.collections.define(slug, config)
Define a new collection. Init-only: call this from
collections/*.lua, init.lua, or any file loaded by require from
those — i.e. while the InitPhase marker is set on the VM. Runtime
calls (from a hook callback firing during a request) error with:
crap.collections.define must be called from a definition file or init.lua. To change a registered collection, edit the file and restart the process.
Schema changes need the migration runner and route wiring to re-run,
which only happens at startup; runtime registration would land in the
in-memory registry without the matching table, admin route, or
scheduler enrollment, so the call is rejected outright. (Mirrors the
behaviour crap.richtext.register_node has had since inception.)
crap.collections.define("posts", {
labels = { singular = "Post", plural = "Posts" },
fields = {
crap.fields.text({ name = "title", required = true }),
},
})
See Collection Definition Schema for all config options.
crap.collections.config.get(slug)
Get a collection’s current definition as a Lua table. The returned table is round-trip
compatible with define() — you can modify it and pass it back, inside init.
Returns nil if the collection doesn’t exist.
-- inside a definition file or init.lua
local def = crap.collections.config.get("posts")
if def then
-- Add a field
def.fields[#def.fields + 1] = crap.fields.text({ name = "extra" })
crap.collections.define("posts", def)
end
crap.collections.config.list()
Get all registered collections as a slug-keyed table. Iterate with
pairs(). The realistic plugin pattern — bulk-attach a hook or field
across every collection — runs from init.lua (or a file it
requires) where the strict guard on define doesn’t fire.
-- inside init.lua / a plugin loaded by init.lua
for slug, def in pairs(crap.collections.config.list()) do
if def.upload then
-- Add alt_text to every upload collection
def.fields[#def.fields + 1] = crap.fields.text({ name = "alt_text" })
crap.collections.define(slug, def)
end
end
See Plugins for patterns using these functions.
Runtime operations — crap.collections.<slug>
Every collection registered via define() gets a typed accessor at
crap.collections.<slug> exposing the full CRUD surface. The slug
is bound; return values are typed against the per-collection
crap.doc.X / crap.find_result.X classes — full IDE narrowing
without ---@type ceremony.
All operations below are only available inside hooks with transaction context.
Dynamic-slug dispatch. For the rare case where the slug isn’t known until runtime (auth strategies handed
context.collection, a plugin iteratingcrap.collections.config.list(), the down-side of a migration), the same operations are reachable ascrap.collections.<method>(slug, ...)— identical semantics, slug as the first arg. Use the slug-keyed form only when you genuinely don’t have a string literal.Slugs that would shadow a method name on
crap.collections(e.g. a collection literally named"find") fail startup with a clear error. Rename the collection.
crap.collections.<slug>.find(query?)
Find documents matching a query. Returns a typed result with
documents (array of crap.doc.<Slug>) and pagination.
local result = crap.collections.posts.find({
where = { status = "published", title = { contains = "hello" } },
order_by = "-created_at",
limit = 10,
page = 1,
depth = 1,
})
for _, doc in ipairs(result.documents) do
print(doc.id, doc.title) -- doc: crap.doc.Posts
end
result.pagination carries totalDocs, limit, page, totalPages,
pageStart, hasNextPage, hasPrevPage, prevPage, nextPage,
startCursor, endCursor (cursor fields only when
[pagination] mode = "cursor" in crap.toml).
Query fields:
| Field | Type | Default | Description |
|---|---|---|---|
where | table | {} | Field filters. See Filter Operators. Supports ["or"] for OR groups. |
order_by | string | nil | Sort field. Prefix with - for descending. |
limit | integer | nil | Max results to return. |
page | integer | 1 | Page number (1-based). Converted to offset internally. |
offset | integer | nil | Number of results to skip (alias for page). |
after_cursor | string | nil | Forward cursor from a previous result.pagination.endCursor. Mutually exclusive with page/offset/before_cursor. Cursor-mode only. |
before_cursor | string | nil | Backward cursor from a previous result.pagination.startCursor. Mutually exclusive with page/offset/after_cursor. Cursor-mode only. |
depth | integer | 0 | Population depth for relationship fields. |
select | string[] | nil | Fields to return. nil = all fields. Always includes id. When specified, created_at/updated_at are included only if explicitly listed. |
draft | boolean | false | Include draft documents (versioned collections with drafts = true). |
locale | string | nil | Locale code for localized fields. |
overrideAccess | boolean | false | Bypass collection-level and field-level access checks. |
search | string | nil | FTS5 full-text search query. |
crap.collections.<slug>.find_by_id(id, opts?)
Find a single document by ID. Returns the typed document or nil.
local doc = crap.collections.posts.find_by_id("abc123")
if doc then
print(doc.title)
end
-- With population depth
local doc = crap.collections.posts.find_by_id("abc123", { depth = 2 })
-- With field selection
local doc = crap.collections.posts.find_by_id("abc123", { select = { "title", "status" } })
Options: depth, select, draft, locale, overrideAccess — same semantics as find.
crap.collections.<slug>.create(data, opts?)
Create a new document. Returns the created typed document.
local doc = crap.collections.posts.create({
title = "New Post",
slug = "new-post",
})
print(doc.id) -- auto-generated nanoid
-- Create as draft (versioned collections only)
local draft = crap.collections.articles.create({
title = "Work in progress",
}, { draft = true })
Options:
| Field | Type | Default | Description |
|---|---|---|---|
locale | string | nil | Locale code for localized fields. |
draft | boolean | false | Create as draft. Skips required-field validation (versioned + drafts = true). |
overrideAccess | boolean | false | Bypass collection/field access checks. |
hooks | boolean | true | Run lifecycle hooks. Set false to skip all hooks and validation; DB write still runs. |
Auth collections
For collections with auth = true, the password field is handled
automatically: on create/update it’s extracted before hooks run,
hashed with Argon2id, and stored in the hidden _password_hash
column. Hooks never see the raw password. On update, leaving
password out (or empty) keeps the current hash. Matches the
gRPC/admin behavior.
crap.collections.<slug>.update(id, data, opts?)
Update an existing document. data is a partial payload — only the
fields being changed need to be present. Returns the updated typed
document.
local doc = crap.collections.posts.update("abc123", {
title = "Updated Title",
})
-- Draft update: saves a version snapshot only, main table unchanged
crap.collections.articles.update("abc123", {
title = "Still editing...",
}, { draft = true })
Options:
| Field | Type | Default | Description |
|---|---|---|---|
locale | string | nil | Locale code for localized fields. |
draft | boolean | false | Version-only save. Creates a draft version snapshot without touching the main table. |
unpublish | boolean | false | Set status to draft and create a draft version snapshot. Ignores data when unpublishing. Versioned collections only. |
overrideAccess | boolean | false | Bypass collection/field access checks. |
hooks | boolean | true | Run lifecycle hooks. |
crap.collections.<slug>.delete(id, opts?)
Delete a document. Returns true on success. For collections with
soft_delete = true this moves the document to trash by default;
upload collections clean up their files on permanent delete (not
soft delete).
-- Soft-delete (moves to trash if the collection has soft_delete)
crap.collections.posts.delete("abc123")
-- Force permanent delete even on soft-delete collections
crap.collections.posts.delete("abc123", { forceHardDelete = true })
-- Bypass access control for internal operations
crap.collections.posts.delete("abc123", { overrideAccess = true })
Options:
| Field | Type | Default | Description |
|---|---|---|---|
overrideAccess | boolean | false | Bypass access.trash (soft) or access.delete (permanent). |
hooks | boolean | true | Run before_delete / after_delete hooks. |
forceHardDelete | boolean | false | Skip soft_delete and remove the row permanently. Still requires access.delete when overrideAccess = false. |
crap.collections.<slug>.undelete(id) (and others)
The accessor also covers unpublish(id, opts?), validate(data, opts?),
count(query?), create_many(items, opts?), update_many(query, data, opts?), delete_many(query, opts?), list_versions(id, opts?),
restore_version(id, version_id, opts?), and ref_count(id) —
same shape as the slug-keyed equivalents, slug bound.
Typing factories — crap.collections.<slug>.{hook,field_hook,condition,access,...}
Per-collection typing helpers that wrap your function literal
and let LuaLS infer the parameter types of the body. Pure
pass-throughs at runtime (f(fn) = fn); the typing comes from the
factory’s signature. See crap.any for the
cross-collection equivalents.
Prerequisite: "type.inferParamType": true in .luarc.json (set
by default in the init scaffold).
crap.collections.<slug>.hook(fn)
Collection lifecycle hook with context narrowed to
crap.hook.<Pascal>. Use for before_validate, before_change,
after_change, before_read, after_read — events where the
runtime ships a typed context.
-- hooks/inquiries/notify.lua
return crap.collections.inquiries.hook(function(context)
-- context.data is typed crap.data.Inquiries
if context.operation == "create" then
crap.jobs.queue("notify", { email = context.data.email })
end
return context
end)
For before_delete / after_delete / before_broadcast the
runtime always sends a generic crap.HookContext — use
crap.any.collection_hook(fn) instead.
crap.collections.<slug>.field_hook(field, fn) and field_hook(fn)
Field-level hook. Two forms:
-- Per-field: value narrows to the field's declared type
return crap.collections.posts.field_hook("title", function(value, context)
-- value: string (posts.title is a text field)
return value:lower()
end)
-- Any field: value is `any`, context still narrowed per-collection
return crap.collections.posts.field_hook(function(value, context)
-- context: crap.field_hook.Posts
return value
end)
The per-field form uses an ---@overload per field declared on the
collection plus a string fallback for dynamic names. value’s
type matches the field type the typegen emits — string for text /
textarea / email / date / richtext / code, number for number,
boolean for checkbox, the literal-string union for select / radio,
string or string[] for relationship / upload, etc.
crap.collections.<slug>.condition(fn)
Display condition with data narrowed to crap.data.<Pascal>.
-- hooks/posts/show_external_url.lua
return crap.collections.posts.condition(function(data)
-- data.post_type narrowed to its select union
return { field = "post_type", ["in"] = { "link", "video" } }
end)
crap.collections.<slug>.access(fn)
Access control function. Same signature as
crap.any.access(fn) — included on the
per-collection accessor for discoverability via
crap.collections.<slug>.<TAB>. No per-collection narrowing
(access context is uniform across collections).
return crap.collections.users.access(function(context)
return context.user ~= nil
end)
crap.collections.<slug>.auth_strategy(fn)
Custom auth strategy authenticate callback. Same shape as
crap.any.auth_strategy(fn); lives on the per-collection accessor
for discoverability when scaffolding a strategy specifically for
that collection.
crap.collections.<slug>.row_label(fn)
Computed row label for array/blocks fields. Receives the row table
and returns the display string (or nil to fall back to
label_field). Per-field narrowing of the row type is a future
enhancement — today the row is typed as table<string, any>.
Slug-keyed dispatch (dynamic case)
For the rare case where the slug isn’t known until runtime — auth
strategies handed context.collection, plugins iterating
crap.collections.config.list(), migration cleanup loops — use the
slug-keyed equivalents:
crap.collections.find(collection, query)
crap.collections.find_by_id(collection, id, opts)
crap.collections.create(collection, data, opts)
-- ... etc
Same semantics, slug as the first arg. Reach for these only when you genuinely don’t have a string literal — they don’t narrow.
Restore a soft-deleted document from trash. Returns true on
success. Only available on collections with soft_delete = true.
Re-syncs the FTS index after undelete.
crap.collections.posts.undelete("abc123")
Lifecycle Hooks in Lua CRUD
Lua CRUD operations run the same lifecycle hooks as the gRPC API and admin UI:
create: before_validate → validate → before_change → DB insert → after_changeupdate: before_validate → validate → before_change → DB update → after_changeupdate_many: per-document: before_validate → validate → before_change → DB update → after_changedelete: before_delete → DB delete → upload file cleanup → after_deletedelete_many: per-document: before_delete → DB delete → upload file cleanup → after_deletefind/find_by_id: before_read → DB query → after_read
All hooks have full CRUD access within the same transaction.
Hook Depth & Recursion Protection
When hooks call CRUD functions that trigger more hooks, the system tracks recursion depth
via ctx.hook_depth. This prevents infinite loops:
- Depth starts at 0 for gRPC/admin operations, 1 for Lua CRUD within hooks
- When depth reaches
hooks.max_depth(default: 3, configurable incrap.toml), hooks are automatically skipped but the DB operation still executes - Use
ctx.hook_depthin hooks for manual recursion decisions
# crap.toml
[hooks]
max_depth = 3 # 0 = never run hooks from Lua CRUD
function M.my_hook(ctx)
if ctx.hook_depth >= 2 then
return ctx -- bail early to avoid deep recursion
end
crap.collections.audit.create({ action = ctx.operation })
return ctx
end
Skipping Hooks
Pass hooks = false to any write CRUD call to skip all lifecycle hooks:
-- Create without triggering any hooks
crap.collections.logs.create({ message = "raw insert" }, { hooks = false })
Access Control in Hooks
By default, all Lua CRUD functions enforce access control (overrideAccess = false). This follows the principle of least privilege — if your hook needs to bypass access checks, it must explicitly opt in with overrideAccess = true.
Breaking change (0.1.0-alpha.3): The default was changed from
truetofalse. If you have hooks that call CRUD functions without specifyingoverrideAccess, they now enforce access control. AddoverrideAccess = trueto restore the old behavior.
When overrideAccess is false (the default), the function enforces the same access rules as the external API:
- Collection-level access — the relevant access function (
read,create,update,delete) is called with the authenticated user from the original request. - Field-level access — for
find/find_by_id, fields the user can’t read are stripped from results. Forcreate/update, fields the user can’t write are silently removed from the input data. - Constrained read access — if a read access function returns a filter table instead of
true, those filters are merged into the query (same as the gRPC/admin behavior).
-- Default: access control is enforced (only shows posts the user can see)
local result = crap.collections.posts.find({
where = { status = "published" },
})
-- Bypass access control for internal/admin operations
local all = crap.collections.posts.find({
overrideAccess = true,
})
crap.collections.count(collection, query?)
Count documents matching a query. Returns an integer count.
Only available inside hooks with transaction context.
local n = crap.collections.posts.count()
local published = crap.collections.posts.count({
where = { status = "published" },
})
Query Parameters
| Field | Type | Default | Description |
|---|---|---|---|
where | table | {} | Field filters. Same syntax as find. |
locale | string | nil | Locale code for localized fields. |
overrideAccess | boolean | false | Bypass access control checks. |
draft | boolean | false | Include draft documents. |
search | string | nil | FTS5 full-text search query (same as find). |
crap.collections.update_many(collection, query, data, opts?)
Update multiple documents matching a query. Returns { modified = N }.
All-or-nothing semantics: finds all matching documents, checks update access for each (if overrideAccess = false), and only proceeds if all pass. If any document fails access, an error is returned and nothing is modified.
Runs the full per-document lifecycle by default: before_validate → field validation → before_change → DB update → after_change — the same pipeline as single-document update. Set hooks = false in opts to skip hooks and validation for performance on large batch operations.
Only provided fields are written (partial update). Absent fields are left unchanged — including checkbox fields, which are not reset to 0 as they would be in a full single-document update.
Only available inside hooks with transaction context.
local result = crap.collections.posts.update_many({
where = { status = "draft" },
}, {
status = "published",
})
print(result.modified) -- number of updated documents
-- Skip hooks and validation for performance
local result = crap.collections.posts.update_many({
where = { status = "draft" },
}, {
status = "published",
}, { hooks = false })
Query Parameters (2nd argument)
| Field | Type | Default | Description |
|---|---|---|---|
where | table | {} | Field filters to match documents. |
Options (4th argument)
| Field | Type | Default | Description |
|---|---|---|---|
locale | string | nil | Locale code for localized fields. |
overrideAccess | boolean | false | Bypass access control checks. |
draft | boolean | false | Include draft documents. |
hooks | boolean | true | Run per-document lifecycle hooks. Set to false to skip all hooks (before_validate, before_change, after_change) and field validation. |
Data (3rd argument)
The data table contains fields to update on all matched documents (partial update).
crap.collections.list_versions(collection, id, opts?)
List version snapshots for a document, newest first. Returns a table with docs (an array of version summaries) and pagination metadata matching the standard pagination shape. Only available on collections with versions enabled.
Only available inside hooks with transaction context.
-- List the 10 most recent versions for a document
local result = crap.collections.posts.list_versions("abc123", { limit = 10 })
for _, v in ipairs(result.docs) do
print(v.version, v.status, v.created_at, v.latest)
end
-- Paginate
local page2 = crap.collections.posts.list_versions("abc123", { limit = 10, offset = 10 })
-- Internal listing that must ignore collection-level read access (e.g. a migration)
local all = crap.collections.posts.list_versions("abc123", { overrideAccess = true })
Options
| Field | Type | Default | Description |
|---|---|---|---|
limit | integer | nil | Maximum number of versions to return. Nil = all remaining. |
offset | integer | 0 | Number of versions to skip (offset pagination). |
overrideAccess | boolean | false | Bypass access control checks. Set to true in trusted internal code (jobs, migrations) to bypass collection-level access checks. This was previously hardcoded to true — it is now opt-in. |
Version summary shape
Each entry in result.docs has:
| Field | Type | Description |
|---|---|---|
id | string | Version row ID (not the parent document ID). |
version | integer | Monotonically-increasing version number, newest first. |
status | string | Version status (e.g. "published", "draft"). |
latest | boolean | true for the newest version. |
created_at | string? | ISO 8601 timestamp the snapshot was taken (nil if unset). |
crap.collections.restore_version(collection, id, version_id, opts?)
Restore a previous version: copies the snapshot data back onto the parent document and writes a new version row. Returns the restored document. Only available on collections with versions enabled.
Only available inside hooks with transaction context.
-- Restore version "v2-abc" of document "post-1"
local doc = crap.collections.posts.restore_version("post-1", "v2-abc")
print(doc.title)
-- Internal restore bypassing per-user access (e.g. automated rollback job)
crap.collections.posts.restore_version("post-1", "v2-abc", { overrideAccess = true })
Options
| Field | Type | Default | Description |
|---|---|---|---|
overrideAccess | boolean | false | Bypass access control checks. Set to true in trusted internal code (jobs, migrations) to bypass collection-level access checks. This was previously hardcoded to true — it is now opt-in. |
crap.collections.delete_many(collection, query, opts?)
Delete multiple documents matching a query. Returns { deleted = N, skipped = N }. For upload collections, associated files are automatically cleaned up from disk for each deleted document. Documents that are still referenced by other documents are skipped (hard delete only) and reported in skipped.
All-or-nothing semantics: finds all matching documents, checks delete access for each (if overrideAccess = false), and only proceeds if all pass.
Fires per-document lifecycle hooks (before_delete, after_delete) by default. Set hooks = false in opts to skip for performance on large batch operations.
Only available inside hooks with transaction context.
local result = crap.collections.posts.delete_many({
where = { status = "archived" },
})
print(result.deleted) -- number of deleted documents
print(result.skipped) -- number skipped due to outstanding references
-- Bypass access control for internal operations
local result = crap.collections.posts.delete_many({
where = { status = "archived" },
}, { overrideAccess = true })
-- Skip hooks for performance
local result = crap.collections.posts.delete_many({
where = { status = "archived" },
}, { hooks = false })
Query Parameters (2nd argument)
| Field | Type | Default | Description |
|---|---|---|---|
where | table | {} | Field filters to match documents. |
Options (3rd argument)
| Field | Type | Default | Description |
|---|---|---|---|
overrideAccess | boolean | false | Bypass access control checks. |
hooks | boolean | true | Run per-document lifecycle hooks. Set to false to skip before_delete and after_delete hooks. |
locale | string | nil | Locale code for localized fields. |
draft | boolean | false | Include draft documents. |
crap.globals
Global (singleton document) definition and runtime operations.
crap.globals.define(slug, config)
Define a new global. Init-only: call this from globals/*.lua,
init.lua, or any file loaded by require from those — i.e. while
the InitPhase marker is set on the VM. Runtime calls error with:
crap.globals.define must be called from a definition file or init.lua. To change a registered global, edit the file and restart the process.
crap.globals.define("site_settings", {
labels = { singular = "Site Settings" },
fields = {
crap.fields.text({ name = "site_name", required = true, default_value = "My Site" }),
crap.fields.text({ name = "tagline" }),
},
})
See Globals for the full config reference.
crap.globals.config.get(slug)
Get a global’s current definition as a Lua table. The returned table is round-trip
compatible with define() — you can modify it and pass it back, inside init.
Returns nil if the global doesn’t exist.
-- inside a definition file or init.lua
local def = crap.globals.config.get("site_settings")
if def then
def.fields[#def.fields + 1] = crap.fields.textarea({ name = "footer_text" })
crap.globals.define("site_settings", def)
end
crap.globals.config.list()
Get all registered globals as a slug-keyed table. Iterate with
pairs(). The realistic bulk-modify pattern runs from init.lua (or
a file it requires) where the strict guard on define doesn’t fire.
-- inside init.lua / a plugin loaded by init.lua
for slug, def in pairs(crap.globals.config.list()) do
-- Add a "last_updated_by" field to every global
def.fields[#def.fields + 1] = crap.fields.text({ name = "last_updated_by" })
crap.globals.define(slug, def)
end
See Plugins for patterns using these functions.
Runtime operations — crap.globals.<slug>
Every global registered via define() gets a typed accessor at
crap.globals.<slug> with get / update methods. The slug is
bound; return values are typed as the per-global document class.
Both operations are only available inside hooks with transaction context.
For the rare dynamic-slug case (you don’t know the slug until runtime — e.g. iterating
crap.globals.config.list()), call the slug-keyed dispatch:crap.globals.get(slug, opts?)/crap.globals.update(slug, data, opts?). Same semantics, slug as the first arg.
crap.globals.<slug>.get(opts?)
Get a global’s current value. Returns the typed document.
Options: locale (string) — locale code (e.g. "en", "de").
Fetches locale-specific field values; omit for default locale.
local settings = crap.globals.site_settings.get()
print(settings.site_name) -- "My Site"
print(settings.id) -- always "default"
-- Fetch German locale data
local settings_de = crap.globals.site_settings.get({ locale = "de" })
crap.globals.<slug>.update(data, opts?)
Update a global’s value. data is a partial payload — only the
fields being changed need to be present. Returns the updated typed
document.
Options:
| Key | Type | Description |
|---|---|---|
locale | string | Locale code. Updates locale-specific field values; omit for default locale. |
overrideAccess | boolean | Bypass the global’s access.update check (default false). |
hooks | boolean | Run lifecycle hooks (default true). Set false for seeding/migrations. |
local settings = crap.globals.site_settings.update({
site_name = "New Site Name",
tagline = "A new beginning",
})
-- Update German locale data
crap.globals.site_settings.update({
site_name = "Neuer Seitenname",
}, { locale = "de" })
crap.any — cross-collection typing factories
crap.any.* is the home for typing-helper factories that aren’t
scoped to a single collection. Each function is a pass-through at
runtime (f(fn) = fn); its only purpose is to give LuaLS a typed
parameter slot so Lua.type.inferParamType propagates the right
value / ctx / data types into your function body’s locals.
For per-collection narrowing (value typed per field, ctx typed
per collection) use the per-slug accessors on
crap.collections.<slug> and
crap.globals.<slug>. Reach for crap.any.* when
the hook spans multiple collections or has nothing to narrow on.
Prerequisites
Both pieces are needed for body-level type inference to fire:
Lua.type.inferParamType: truein your.luarc.json(theinitscaffold sets this by default).- Wrap the function literal in a factory call. A bare
return function(ctx) ... endwon’t propagate types — LuaLS needs the typed parameter slot from the factory’s signature.
If your callback’s ctx shows up as any in hover, one of the two
is missing.
API surface
crap.any.collection_hook(fn)
Wraps a collection lifecycle hook that takes the generic
crap.HookContext. Use for hooks that fire on multiple collections
(or for before_delete / after_delete / before_broadcast where
the runtime always passes a generic context).
-- hooks/set_published_at.lua — used by posts AND projects
return crap.any.collection_hook(function(context)
if context.data._status == "published" and not context.data.published_at then
context.data.published_at = crap.util.date_now()
end
return context
end)
For collection-specific narrowing, use
crap.collections.<slug>.hook(fn).
crap.any.field_hook(fn)
Wraps a field-level hook that takes (value, context) against the
generic crap.FieldHookContext. value is any in the body; for
typed value use the per-field overload on
crap.collections.<slug>.field_hook(field, fn).
-- hooks/auto_slug.lua — applied to many collections' "slug" field
return crap.any.field_hook(function(value, context)
if value and value ~= "" then return value end
local title = context.data and context.data.title
return title and crap.util.slugify(title) or value
end)
crap.any.access(fn)
Wraps an access control function. context: crap.AccessContext. The
context type is uniform across collections — there’s no per-collection
narrowing variant.
return crap.any.access(function(context)
return context.user ~= nil and context.user.role == "admin"
end)
context.user is typed as crap.AuthUser (crap.Document plus an
[string] any index signature, since a project may have multiple
auth collections). When you know the auth collection, cast for strict
typing:
local user = context.user --[[@as crap.doc.Users]]
crap.any.auth_strategy(fn)
Wraps a custom auth strategy’s authenticate callback.
context: crap.AuthStrategyContext — { headers, collection }.
Returns the user document or nil.
return crap.any.auth_strategy(function(context)
local key = context.headers["x-api-key"]
if not key then return nil end
return crap.collections.find_by_id(context.collection, lookup_user(key))
end)
crap.any.job_handler(fn)
Wraps a background job handler. context: crap.JobHandlerContext
({ data, job }).
M.run = crap.any.job_handler(function(context)
crap.log.info("Job attempt " .. context.job.attempt)
-- context.data is the payload passed to crap.jobs.queue(...)
end)
crap.any.row_label(fn)
Wraps a computed row label for array/blocks fields.
return crap.any.row_label(function(row)
return row.heading or row.title or "(untitled)"
end)
crap.any.display_condition(fn)
Wraps a display condition that doesn’t need per-collection data
narrowing. For typed data, use
crap.collections.<slug>.condition(fn).
return crap.any.display_condition(function(data)
return { field = "kind", equals = "premium" }
end)
When to reach for crap.any vs the per-slug accessor
| Situation | Use |
|---|---|
| Hook is specific to one collection’s field | crap.collections.<slug>.field_hook("<field>", fn) |
| Hook applies to multiple fields of one collection | crap.collections.<slug>.field_hook(fn) |
| Hook applies to multiple collections | crap.any.field_hook(fn) |
Collection hook on a specific collection (typed ctx) | crap.collections.<slug>.hook(fn) |
| Collection hook used across collections | crap.any.collection_hook(fn) |
before_delete / after_delete / before_broadcast | crap.any.collection_hook(fn) (runtime always sends generic ctx) |
| Display condition tied to a collection’s data | crap.collections.<slug>.condition(fn) |
| Access function (always uniform context) | crap.any.access(fn) or crap.collections.<slug>.access(fn) for discoverability |
| Auth strategy | crap.any.auth_strategy(fn) or crap.collections.<slug>.auth_strategy(fn) |
| Job handler | crap.any.job_handler(fn) |
crap.hooks
Global hook registration API. Register hooks in init.lua to fire for all collections.
crap.hooks.register(event, fn)
Register a hook function for a lifecycle event.
crap.hooks.register("before_change", function(ctx)
crap.log.info("[audit] " .. ctx.operation .. " on " .. ctx.collection)
return ctx
end)
Parameters
| Parameter | Type | Description |
|---|---|---|
event | string | Lifecycle event name |
fn | function | Hook function receiving a context table |
Events
| Event | Description |
|---|---|
before_validate | Before field validation on create/update |
before_change | After validation, before write on create/update |
after_change | After create/update (runs in transaction, has CRUD access) |
before_read | Before returning read results |
after_read | After read, before response (no CRUD access) |
before_delete | Before delete |
after_delete | After delete (runs in transaction, has CRUD access) |
before_broadcast | Before live event broadcast (can suppress or transform) |
before_render | Before rendering admin pages (receives full template context, can modify it; global-only, no CRUD access) |
crap.hooks.remove(event, fn)
Remove a previously registered hook. Uses rawequal for identity matching — you must pass the exact same function reference.
local my_hook = function(ctx) return ctx end
crap.hooks.register("before_change", my_hook)
crap.hooks.remove("before_change", my_hook)
Parameters
| Parameter | Type | Description |
|---|---|---|
event | string | Lifecycle event name |
fn | function | The exact function reference to remove |
crap.hooks.list(event)
Return the list of registered hook functions for an event. Useful for debugging or introspection.
local hooks = crap.hooks.list("before_change")
print(#hooks) -- number of registered before_change hooks
Parameters
| Parameter | Type | Description |
|---|---|---|
event | string | Lifecycle event name |
Returns
A Lua table (array) of the registered hook functions. Empty table if none are registered.
crap.log
Structured logging that maps to Rust’s tracing framework. Log messages appear with a [lua:<vm>] prefix, where <vm> is the VM label (e.g., init, vm-1, vm-2).
Functions
crap.log.info(msg)
Log an info-level message.
crap.log.info("Processing complete")
Output: INFO [lua:vm-1] Processing complete
crap.log.warn(msg)
Log a warning-level message.
crap.log.warn("Deprecated field used")
Output: WARN [lua:vm-1] Deprecated field used
crap.log.error(msg)
Log an error-level message.
crap.log.error("Failed to process webhook")
Output: ERROR [lua:vm-1] Failed to process webhook
Parameters
| Parameter | Type | Description |
|---|---|---|
msg | string | Log message |
Usage in Hooks
function M.before_change(ctx)
crap.log.info(string.format(
"[%s] %s on %s",
os.date("%H:%M:%S"),
ctx.operation,
ctx.collection
))
return ctx
end
crap.json
JSON encode/decode functions.
crap.json.encode(value)
Encode a Lua value (table, string, number, boolean, nil) as a JSON string.
local json = crap.json.encode({ name = "test", count = 42 })
-- '{"count":42,"name":"test"}'
| Parameter | Type | Description |
|---|---|---|
value | any | Lua value to encode |
| Returns | string | JSON string |
crap.json.decode(str)
Decode a JSON string into a Lua value.
local data = crap.json.decode('{"name":"test","count":42}')
print(data.name) -- "test"
print(data.count) -- 42
| Parameter | Type | Description |
|---|---|---|
str | string | JSON string |
| Returns | any | Decoded Lua value |
Notes
- Integer precision — JSON numbers are decoded into Lua number (
f64under the hood). Integers larger than 2^53 (~9 × 10^15) lose precision. If you need to preserve large IDs exactly, encode them as strings before serializing. - Nesting depth — encoder rejects tables nested more than 64 levels deep to guard against runaway recursion. A self-referential Lua table (
t.a = t) will exceed this limit and error rather than looping forever. - Decode of untrusted input — decoding is permissive and does not currently enforce a maximum depth on the input side. Keep that in mind when processing large attacker-controlled payloads.
Common Patterns
Webhook Payload
crap.http.request({
method = "POST",
url = webhook_url,
headers = { ["Content-Type"] = "application/json" },
body = crap.json.encode({
event = "new_inquiry",
name = inquiry.name,
email = inquiry.email,
}),
})
Parse API Response
local resp = crap.http.request({ url = "https://api.example.com/data" })
if resp.status == 200 then
local data = crap.json.decode(resp.body)
crap.log.info("Got " .. #data .. " items")
end
crap.util
Utility functions available everywhere the crap global is accessible.
crap.util.slugify(str)
Generate a URL-safe slug from a string. Lowercases, replaces non-alphanumeric characters with hyphens, and collapses consecutive hyphens.
crap.util.slugify("Hello World") -- "hello-world"
crap.util.slugify("Hello, World!") -- "hello-world"
crap.util.slugify(" multiple spaces ") -- "multiple-spaces"
| Parameter | Type | Description |
|---|---|---|
str | string | Input string |
| Returns | string | URL-safe slug |
crap.util.nanoid()
Generate a unique nanoid string (21 characters by default).
local id = crap.util.nanoid()
-- e.g., "V1StGXR8_Z5jdHi6B-myT"
| Returns | string | Random nanoid |
JSON encode/decode
See crap.json for crap.json.encode() and crap.json.decode().
Common Hook Patterns
Auto-Slug Generation
function M.auto_slug(ctx)
if not ctx.data.slug or ctx.data.slug == "" then
ctx.data.slug = crap.util.slugify(ctx.data.title or "")
end
return ctx
end
Generate Unique Identifiers
function M.set_ref_code(ctx)
if ctx.operation == "create" then
ctx.data.ref_code = "REF-" .. crap.util.nanoid()
end
return ctx
end
Serialize Complex Data
function M.store_metadata(ctx)
if type(ctx.data.metadata) == "table" then
ctx.data.metadata = crap.json.encode(ctx.data.metadata)
end
return ctx
end
Table Helpers
crap.util.deep_merge(a, b)
Deep merge two tables. b overwrites a. Returns a new table.
local merged = crap.util.deep_merge(
{ name = "old", nested = { x = 1 } },
{ name = "new", nested = { y = 2 } }
)
-- { name = "new", nested = { x = 1, y = 2 } }
crap.util.pick(tbl, keys)
Return a table with only the listed keys.
local picked = crap.util.pick({ a = 1, b = 2, c = 3 }, { "a", "c" })
-- { a = 1, c = 3 }
crap.util.omit(tbl, keys)
Return a table without the listed keys.
local result = crap.util.omit({ a = 1, b = 2, c = 3 }, { "b" })
-- { a = 1, c = 3 }
crap.util.keys(tbl) / crap.util.values(tbl)
Extract keys or values as arrays.
local k = crap.util.keys({ a = 1, b = 2 }) -- { "a", "b" }
local v = crap.util.values({ a = 1, b = 2 }) -- { 1, 2 }
crap.util.map(tbl, fn) / crap.util.filter(tbl, fn) / crap.util.find(tbl, fn)
Functional array operations.
local doubled = crap.util.map({ 1, 2, 3 }, function(v) return v * 2 end)
-- { 2, 4, 6 }
local evens = crap.util.filter({ 1, 2, 3, 4 }, function(v) return v % 2 == 0 end)
-- { 2, 4 }
local found = crap.util.find({ 1, 2, 3 }, function(v) return v > 1 end)
-- 2
crap.util.includes(tbl, value)
Check if an array contains a value.
crap.util.includes({ "a", "b", "c" }, "b") -- true
crap.util.is_empty(tbl)
Check if a table has no entries.
crap.util.is_empty({}) -- true
crap.util.is_empty({ a = 1 }) -- false
crap.util.clone(tbl)
Shallow copy a table.
local original = { a = 1 }
local copy = crap.util.clone(original)
copy.a = 2
print(original.a) -- 1 (unchanged)
String Helpers
crap.util.trim(str)
Strip leading and trailing whitespace.
crap.util.trim(" hello ") -- "hello"
crap.util.split(str, sep)
Split a string by separator. Returns an array.
crap.util.split("a,b,c", ",") -- { "a", "b", "c" }
crap.util.starts_with(str, prefix) / crap.util.ends_with(str, suffix)
crap.util.starts_with("hello world", "hello") -- true
crap.util.ends_with("hello world", "world") -- true
crap.util.truncate(str, max_len, suffix?)
Truncate a string with optional suffix (default: "...").
crap.util.truncate("Hello, World!", 8) -- "Hello..."
crap.util.truncate("Hello, World!", 8, " >>") -- "Hello >>"
Date Helpers
crap.util.date_now()
Get current UTC time as ISO 8601 string.
local now = crap.util.date_now() -- "2024-01-15T10:30:00+00:00"
crap.util.date_timestamp()
Get current Unix timestamp in seconds.
local ts = crap.util.date_timestamp() -- 1705312200
crap.util.date_parse(str)
Parse a date string to Unix timestamp. Tries RFC 3339, then %Y-%m-%d %H:%M:%S, then %Y-%m-%d.
local ts = crap.util.date_parse("2024-01-15T10:30:00Z")
local ts2 = crap.util.date_parse("2024-01-15")
crap.util.date_format(timestamp, format)
Format a Unix timestamp using chrono format syntax.
local str = crap.util.date_format(1705312200, "%Y-%m-%d") -- "2024-01-15"
crap.util.date_add(timestamp, seconds) / crap.util.date_diff(a, b)
Arithmetic on timestamps.
local tomorrow = crap.util.date_add(crap.util.date_timestamp(), 86400)
local diff = crap.util.date_diff(tomorrow, crap.util.date_timestamp()) -- 86400
crap.auth
Password hashing and verification helpers using Argon2id.
Functions
crap.auth.hash_password(password)
Hash a plaintext password using Argon2id.
Parameters:
password(string) — Plaintext password.
Returns: string — The hashed password string.
local hash = crap.auth.hash_password("secret123")
-- hash is an Argon2id hash string like "$argon2id$v=19$..."
crap.auth.verify_password(password, hash)
Verify a plaintext password against a stored hash.
Parameters:
password(string) — Plaintext password to check.hash(string) — Stored Argon2id hash.
Returns: boolean — true if the password matches.
local valid = crap.auth.verify_password("secret123", stored_hash)
if valid then
crap.log.info("Password matches")
end
crap.auth.user()
Return the currently authenticated user document for the in-flight request, or nil.
Returns: crap.Document? — The user document (a Lua table containing the user’s
fields, including id, email, and any custom fields), or nil if no user is set.
The function returns nil in any of these cases:
- Called from
init.lua(no request context). - The request is unauthenticated (anonymous public traffic).
- Called outside a hook (no
UserContextis registered on the Lua VM).
The user is populated from the request’s session/JWT and made available to all hooks
that fire for that request (CRUD lifecycle hooks, access control functions, validation
hooks, before_render, etc.).
crap.hooks.register("before_change", function(ctx)
local user = crap.auth.user()
if user then
ctx.data.last_edited_by = user.id
end
return ctx
end)
-- Skip a hook for anonymous traffic
crap.hooks.register("after_read", function(ctx)
local user = crap.auth.user()
if not user then
return ctx
end
-- ...user-specific personalization...
return ctx
end)
Notes
- Available in both init.lua and hooks.
- Uses the same Argon2id implementation as the built-in auth system.
- Useful for custom auth strategies or migrating users from external systems.
- For custom authentication logic, use auth strategies or auth callbacks.
crap.env
Read-only access to environment variables.
Functions
crap.env.get(key)
Get the value of an environment variable.
Parameters:
key(string) — Environment variable name.
Returns: string or nil — The value, or nil if the variable is not set.
local db_url = crap.env.get("CRAP_DATABASE_URL")
if db_url then
crap.log.info("DB URL: " .. db_url)
end
-- Common pattern: env with fallback
local port = crap.env.get("CRAP_PORT") or "3000"
Allowed Prefixes
For security, crap.env.get() only allows access to environment variables with specific prefixes:
| Prefix | Purpose |
|---|---|
CRAP_ | Application-specific variables (e.g., CRAP_API_KEY, CRAP_WEBHOOK_URL) |
LUA_ | Lua-specific variables (e.g., LUA_PATH, LUA_CPATH) |
All other environment variables (e.g., PATH, HOME, DATABASE_URL, AWS_SECRET_ACCESS_KEY) return nil regardless of whether they are set. This prevents hooks from accidentally or maliciously reading sensitive system or infrastructure variables.
-- These work (if set):
crap.env.get("CRAP_API_TOKEN") -- returns the value
crap.env.get("LUA_PATH") -- returns the value
-- These always return nil:
crap.env.get("PATH") -- nil
crap.env.get("HOME") -- nil
crap.env.get("DATABASE_URL") -- nil
Notes
- Available in both init.lua and hooks.
- Returns
nilfor unset variables and for variables with disallowed prefixes (never errors). - Useful for reading secrets, feature flags, or deployment-specific values without hardcoding them in Lua files.
- To pass configuration to hooks, set environment variables with the
CRAP_prefix (e.g.,CRAP_SMTP_HOST,CRAP_WEBHOOK_SECRET).
crap.http
Outbound HTTP client for making requests from Lua hooks and init.lua.
Functions
crap.http.request(opts)
Make a blocking HTTP request.
Parameters:
opts(table):url(string, required) — Request URL.method(string, optional) — HTTP method. Default:"GET". Supported:GET,POST,PUT,PATCH,DELETE,HEAD.headers(table, optional) — Request headers as key-value pairs.body(string, optional) — Request body.timeout(integer, optional) — Timeout in seconds. Default:30.
Returns: table — Response with fields:
status(integer) — HTTP status code.headers(table) — Response headers as key-value pairs.body(string) — Response body as a string.
Errors: Throws a Lua error on transport failures (DNS, connection refused, timeout).
-- Simple GET
local resp = crap.http.request({ url = "https://api.example.com/data" })
if resp.status == 200 then
local data = crap.json.decode(resp.body)
crap.log.info("Got " .. #data .. " items")
end
-- POST with JSON body
local resp = crap.http.request({
url = "https://api.example.com/webhook",
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. crap.env.get("CRAP_API_TOKEN"),
},
body = crap.json.encode({ event = "document.created", id = ctx.data.id }),
timeout = 10,
})
Notes
- Uses reqwest (blocking HTTP client). Since Lua hooks run inside
spawn_blocking, blocking I/O is correct and won’t stall the async runtime. - Non-2xx responses are not errors — they return normally with the status code. Only transport-level failures (DNS, timeout, connection refused) throw Lua errors.
- Available in both init.lua and hooks.
- TLS certificate verification is always enabled (reqwest’s default with the
rustls-tlsfeature). There is no opt-out —crap.http.requestwill not connect to servers with invalid or self-signed certificates. Use a proper CA-signed certificate on any HTTPS endpoint you call.
Security
Private network blocking
When hooks.allow_private_networks is false (the default), crap.http.request resolves the URL hostname and rejects requests targeting loopback, private (RFC 1918), link-local, and unspecified IP addresses. This prevents SSRF attacks against internal services. Set allow_private_networks = true in crap.toml only if your hooks need to reach internal services.
DNS rebinding protection
DNS is resolved once during validation, checked against the SSRF policy, and the validated IP is pinned via reqwest::ClientBuilder::resolve(). The HTTP client connects to the exact validated address — no second DNS lookup occurs. Redirects are individually resolved, validated, and pinned before following.
crap.config
Read-only access to crap.toml configuration values using dot notation.
Functions
crap.config.get(key)
Get a configuration value by dot-separated key path.
Parameters:
key(string) — Dot-separated config key (e.g.,"server.admin_port").
Returns: any — The value at that key path, or nil if the path doesn’t exist.
local port = crap.config.get("server.admin_port") -- 3000
local host = crap.config.get("server.host") -- "0.0.0.0"
local dev = crap.config.get("admin.dev_mode") -- false
local depth = crap.config.get("depth.max_depth") -- 10
local expiry = crap.config.get("auth.token_expiry") -- 7200
Available Keys
The config structure mirrors crap.toml:
| Key | Type | Default |
|---|---|---|
server.admin_port | integer | 3000 |
server.grpc_port | integer | 50051 |
server.host | string | “0.0.0.0” |
database.path | string | “data/crap.db” |
admin.dev_mode | boolean | false |
auth.secret | string | “” |
auth.token_expiry | integer | 7200 |
depth.default_depth | integer | 1 |
depth.max_depth | integer | 10 |
upload.max_file_size | integer | 52428800 |
hooks.on_init | string[] | [] |
hooks.max_depth | integer | 3 |
hooks.vm_pool_size | integer | (auto) |
hooks.max_instructions | integer | 10000000 |
hooks.max_memory | integer | 52428800 |
hooks.allow_private_networks | boolean | false |
hooks.http_max_response_bytes | integer | 10485760 |
pagination.default_limit | integer | 20 |
pagination.max_limit | integer | 1000 |
pagination.mode | string | “page” |
locale.default_locale | string | “en” |
locale.locales | string[] | [] |
locale.fallback | boolean | true |
email.smtp_host | string | “” |
live.enabled | boolean | true |
access.default_deny | boolean | true |
All sections from crap.toml are available — this table is not exhaustive. The entire CrapConfig struct is serialized to Lua.
Notes
- Values are a read-only snapshot taken at the moment each Lua VM is created. The VM pool is built at startup; once a VM is alive, its
crap.configview is frozen for its lifetime. Edits tocrap.tomlafter startup are not picked up without a restart (or VM-pool recycle, which today only happens on process restart). - Available in both init.lua and hooks.
- Returns
nilfor non-existent keys (never errors).
crap.email
Send emails via the configured email provider. Supports SMTP, webhooks (SendGrid, Mailgun, etc.), and custom Lua providers.
Configuration
[email]
provider = "smtp" # "smtp" (default), "webhook", "log", or "custom"
smtp_host = "smtp.example.com"
smtp_port = 587
smtp_user = "noreply@example.com"
smtp_pass = "your-smtp-password"
smtp_tls = "starttls" # "starttls" (default), "tls" (implicit), "none" (plain/test)
from_address = "noreply@example.com"
from_name = "My App"
# Background email delivery (queue retries / timeout / concurrency)
# lives under [jobs.queues.email] — same per-queue mechanism as image
# conversions. Framework defaults are sane for typical SMTP setups, so
# you only need this block when you want to tune it.
[jobs.queues.email]
retries = 3 # default: 3 — total attempts = retries + 1
timeout = "30s" # default: 30s — per-attempt wall-clock timeout
concurrency = 5 # default: 5 — max concurrent emails in flight
If smtp_host is empty with the default smtp provider, emails are logged instead of sent (equivalent to provider = "log").
crap.email.send(opts)
Send an email immediately (blocking). Use when you need to know if the send succeeded.
| Field | Type | Required | Description |
|---|---|---|---|
to | string | yes | Recipient email address |
subject | string | yes | Email subject line |
html | string | yes | HTML email body |
text | string | no | Plain text fallback body |
Returns: true on success.
crap.email.send({
to = "user@example.com",
subject = "Welcome!",
html = "<h1>Welcome</h1><p>Thanks for signing up.</p>",
text = "Welcome! Thanks for signing up.",
})
crap.email.queue(opts)
Queue an email for async delivery with automatic retries. Returns immediately — the email is processed by the scheduler with exponential backoff on failure (5s, 10s, 20s, …, max 300s).
Requires a transaction context (available in before_change, before_delete, and other hooks with CRUD access).
| Field | Type | Required | Description |
|---|---|---|---|
to | string | yes | Recipient email address |
subject | string | yes | Email subject line |
html | string | yes | HTML email body |
text | string | no | Plain text fallback body |
retries | integer | no | Override retry count from config (default: [jobs.queues.email] retries) |
Returns: Job run ID (string).
local job_id = crap.email.queue({
to = "user@example.com",
subject = "Your report is ready",
html = "<p>Download your report at ...</p>",
retries = 5, -- try up to 5 times
})
When to use
sendvsqueue:
- Use
sendwhen the email result matters for the current operation (e.g., inline error handling).- Use
queuefor everything else — password resets, notifications, reports. The queue handles retries automatically, and failures don’t block the request.
crap.email.register(handler)
Register a custom email provider. Only used when [email] provider = "custom" in crap.toml. Call in init.lua.
crap.email.register({
send = function(opts)
crap.http.request({
method = "POST",
url = "https://api.sendgrid.com/v3/mail/send",
headers = {
Authorization = "Bearer " .. crap.env.get("SENDGRID_KEY"),
["Content-Type"] = "application/json",
},
body = crap.json.encode({
personalizations = {{ to = {{ email = opts.to }} }},
from = { email = "noreply@example.com" },
subject = opts.subject,
content = {{ type = "text/html", value = opts.html }},
}),
})
end,
})
Providers
| Provider | Config | Description |
|---|---|---|
smtp | smtp_host, smtp_port, etc. | Default. Standard SMTP via lettre. |
webhook | webhook_url, webhook_headers | HTTP POST with JSON body. Works with SendGrid, Mailgun, Resend. |
log | (none) | Logs emails to tracing. For development/testing. |
custom | (none) | Delegates to Lua via crap.email.register(). |
Use in Hooks
Both send and queue are safe to call from hooks. send is blocking (runs within spawn_blocking). queue inserts a job row and returns immediately.
-- hooks/welcome.lua — queue a welcome email on user creation
return function(ctx)
if ctx.operation == "create" and ctx.data.email then
crap.email.queue({
to = ctx.data.email,
subject = "Welcome!",
html = "<p>Thanks for signing up.</p>",
})
end
return ctx
end
crap.locale
Read-only access to the locale configuration. Available in init.lua and all hook functions.
Functions
crap.locale.get_default()
Returns the default locale code from crap.toml.
local default = crap.locale.get_default() -- "en"
crap.locale.get_all()
Returns an array of all configured locale codes. Returns an empty table if localization is disabled.
local locales = crap.locale.get_all() -- {"en", "de", "fr"}
crap.locale.is_enabled()
Returns true if localization is enabled (at least one locale configured in crap.toml).
if crap.locale.is_enabled() then
-- localization is active
end
Example
-- In a hook: generate localized slugs
function M.before_change(ctx)
if crap.locale.is_enabled() and ctx.locale then
ctx.data.slug = crap.util.slugify(ctx.data.title) .. "-" .. ctx.locale
else
ctx.data.slug = crap.util.slugify(ctx.data.title)
end
return ctx
end
crap.crypto
Cryptographic helpers. AES-256-GCM encryption key is derived from the auth.secret in crap.toml.
crap.crypto.sha256(data)
SHA-256 hash of a string, returned as a 64-character hex string.
local hash = crap.crypto.sha256("hello world")
-- "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
crap.crypto.hmac_sha256(data, key)
HMAC-SHA256 of data with a key, returned as hex.
local mac = crap.crypto.hmac_sha256("message", "secret-key")
Security: Always compare HMACs (and any other secret-derived bytes) with
crap.crypto.constant_time_eq(...), not with==. Lua’s==on strings short-circuits on the first differing byte, which leaks information about where the mismatch occurred through response timing and lets an attacker recover the expected tag byte-by-byte. Example:local expected = crap.crypto.hmac_sha256(body, secret) if crap.crypto.constant_time_eq(expected, incoming_signature) then -- verified, safe to proceed end
crap.crypto.constant_time_eq(a, b)
Constant-time byte-string equality check. Returns true iff the two inputs
are byte-identical. Runs in time that does not depend on where (or whether)
the bytes differ, so the caller cannot learn anything about the expected
value from response timing.
Length mismatches and content mismatches are indistinguishable from the
return value — both yield false.
local ok = crap.crypto.constant_time_eq(expected_tag, provided_tag)
Use this for comparing HMAC tags, session tokens, API keys, signed cookies, webhook signatures, or any other secret-derived bytes.
crap.crypto.base64_encode(str) / crap.crypto.base64_decode(str)
Base64 encoding and decoding.
local encoded = crap.crypto.base64_encode("hello") -- "aGVsbG8="
local decoded = crap.crypto.base64_decode(encoded) -- "hello"
crap.crypto.encrypt(plaintext) / crap.crypto.decrypt(ciphertext)
AES-256-GCM encryption using the auth secret from crap.toml. The encrypted output is base64-encoded with a random nonce prepended.
local encrypted = crap.crypto.encrypt("sensitive data")
local original = crap.crypto.decrypt(encrypted) -- "sensitive data"
Note: The encryption key is derived from
auth.secretincrap.toml— the same secret used for JWT signing. Rotating the JWT secret will invalidate all previously encrypted data. If you rotate secrets, you must re-encrypt any data that was encrypted with the old secret.
crap.crypto.random_bytes(n)
Generate n random bytes, returned as a hex string of length 2*n.
local token = crap.crypto.random_bytes(16) -- 32-character hex string
crap.schema
Schema introspection API. Provides read-only access to collection and global definitions loaded from Lua files. Available everywhere the crap global is accessible.
crap.schema.get_collection(slug)
Get a collection’s full schema definition. Returns a table or nil if not found.
local schema = crap.schema.get_collection("posts")
if schema then
print(schema.slug) -- "posts"
print(schema.timestamps) -- true
print(schema.has_auth) -- false
print(#schema.fields) -- number of fields
for _, field in ipairs(schema.fields) do
print(field.name, field.type, field.required)
end
end
Return Value
| Field | Type | Description |
|---|---|---|
slug | string | Collection slug. |
labels | table | { singular?, plural? } display names. |
timestamps | boolean | Whether created_at/updated_at are enabled. |
has_auth | boolean | Whether authentication is enabled. |
has_upload | boolean | Whether file uploads are enabled. |
has_versions | boolean | Whether versioning is enabled. |
has_drafts | boolean | Whether draft/publish workflow is enabled (versioned + drafts). |
fields | table[] | Array of field definitions (see below). |
Field Schema
Each field table contains:
| Field | Type | Description |
|---|---|---|
name | string | Field name. |
type | string | Field type (text, number, relationship, etc.). |
required | boolean | Whether the field is required. |
localized | boolean | Whether the field has per-locale values. |
unique | boolean | Whether the field has a unique constraint. |
relationship | table? | { collection, has_many } for relationship fields. |
options | table[]? | { label, value } for select fields. |
fields | table[]? | Sub-fields for array/group types (recursive). |
blocks | table[]? | Block definitions for blocks type. |
crap.schema.get_global(slug)
Get a global’s schema definition. Same return shape as get_collection.
local schema = crap.schema.get_global("site_settings")
crap.schema.list_collections()
List all registered collections with their slugs and labels.
local collections = crap.schema.list_collections()
for _, c in ipairs(collections) do
print(c.slug, c.labels.singular)
end
crap.schema.list_globals()
List all registered globals with their slugs and labels.
local globals = crap.schema.list_globals()
for _, g in ipairs(globals) do
print(g.slug, g.labels.singular)
end
crap.richtext
Register custom ProseMirror node types for the rich text editor and render rich text content to HTML.
Functions
crap.richtext.register_node(name, spec)
Register a custom rich text node type. Init-only: call from
init.lua or any file loaded by require from it. Runtime calls
error because the pool of Lua VMs each holds its own node table —
registering at runtime would only land in the VM that ran the call,
fragmenting the set.
Parameters:
name(string) — Node name (alphanumeric + underscores only).spec(table) — Node specification.
Spec fields:
| Field | Type | Default | Description |
|---|---|---|---|
label | string | name | Display label in the editor toolbar |
inline | boolean | false | Whether this is an inline node (vs block) |
attrs | FieldDefinition[] | {} | Node attributes via crap.fields.* (scalar types only) |
searchable_attrs | string[] | {} | Attribute names included in full-text search |
render | function | nil | Custom HTML render function (attrs) -> string |
Node attributes use crap.fields.* factory functions (same as collection fields).
Only scalar types are allowed: text, number, textarea, select, radio,
checkbox, date, email, json, code.
Supported attribute features:
- Admin display hints:
admin.hidden,admin.readonly,admin.width,admin.step,admin.rows,admin.language,admin.placeholder,admin.description - Validation bounds:
required,validate,min/max,min_length/max_length,min_date/max_date,picker_appearance - Lifecycle hooks:
hooks.before_validate(normalize values before validation)
Features that have no effect on node attrs (unique, index, localized, has_many,
access, hooks.before_change/after_change/after_read, mcp, admin.condition) produce
a warning at registration time but do not error.
crap.richtext.register_node("callout", {
label = "Callout",
attrs = {
crap.fields.select({ name = "type", options = {
{ label = "Info", value = "info" },
{ label = "Warning", value = "warning" },
}}),
crap.fields.text({ name = "body", admin = { rows = 4 } }),
},
searchable_attrs = { "body" },
render = function(attrs)
return string.format(
'<div class="callout callout-%s">%s</div>',
attrs.type or "info",
attrs.body or ""
)
end,
})
crap.richtext.render(content)
Render a rich text JSON string to HTML, including any registered custom nodes.
Parameters:
content(string) — ProseMirror JSON content string.
Returns: string — Rendered HTML.
local html = crap.richtext.render(doc.body)
Notes
- Register nodes in
init.luaso they’re available to all VMs. - Custom nodes appear in the rich text editor toolbar for fields that include them.
- The
renderfunction is called duringcrap.richtext.render()to convert custom nodes to HTML.
Render output is NOT sanitized
The string your render function returns is inserted directly into the HTML output —
no escaping, no sanitization, no tag allowlist. Whatever you return becomes
raw markup in the rendered page.
This is by design: custom nodes exist precisely so operators can emit structured HTML. But the trust boundary is strict:
renderis trusted code. It runs server-side inside Lua you wrote.- Any user-supplied data you interpolate into the output string (node attrs, document content, etc.) must be escaped by you before concatenation.
Safe pattern — escape the parts that came from user input:
local function escape_html(s)
s = s or ""
s = s:gsub("&", "&"):gsub("<", "<"):gsub(">", ">")
s = s:gsub('"', """):gsub("'", "'")
return s
end
crap.richtext.register_node("callout", {
attrs = { crap.fields.text({ name = "body" }) },
render = function(attrs)
return '<div class="callout">' .. escape_html(attrs.body) .. '</div>'
end,
})
Unsafe pattern — concatenating a user field directly produces stored XSS:
render = function(attrs)
return '<div class="callout">' .. (attrs.body or "") .. '</div>' -- BAD
end
Server-side richtext output is NOT passed through any sanitizer — there is no fallback. Treat every interpolation as a potential injection vector.
crap.jobs
Background job definition and queuing.
crap.jobs.define(slug, config)
Define a background job. Init-only: call this from jobs/*.lua,
init.lua, or any file loaded by require from those. The scheduler
enrolls jobs once at startup; runtime registration would never reach
the cron or queue worker, so it’s rejected outright:
crap.jobs.define must be called from a definition file or init.lua. To change a registered job, edit the file and restart the process.
The common “define + handler in one file” layout (top-level
crap.jobs.define(...) plus function M.run(ctx) ... end returned
as a module) works fine: init loads each jobs/foo.lua once and
caches its return value in package.loaded["jobs.foo"]. When the
dispatcher later does require("jobs.foo") to call the handler, it
hits the cache and the top-level define does not re-run.
Parameters:
slug(string) — Unique job identifierconfig(table) — Job configuration:handler(string, required) — Lua function ref (e.g.,"jobs.cleanup.run")schedule(string, optional) — Cron expression (e.g.,"0 3 * * *")queue(string, default:"default") — Queue nameretries(integer, optional) — Max retry attempts. When omitted, inherits[jobs.queues.<queue>] retriesfromcrap.toml; if the queue has no entry either, defaults to0(one attempt). Set explicitly (includingretries = 0) to override the queue default.timeout(integer, default: 60) — Seconds before timeoutconcurrency(integer, default: 1) — Max concurrent runsskip_if_running(boolean, default: true) — Skip cron if still runninglabels(table, optional) —{ singular = "Display Name" }access(string, optional) — Lua function ref for trigger access control
Example:
crap.jobs.define("send_digest", {
handler = "jobs.digest.run",
schedule = "0 8 * * 1", -- Mondays at 8am
retries = 2,
timeout = 120,
})
crap.jobs.queue(slug, data?, opts?)
Queue a job for background execution. Only available inside hooks with transaction context.
Parameters:
slug(string) — Job slug (must be previously defined)data(table, optional) — Input data passed to the handler (default:{})opts(table, optional) — Per-enqueue options:priority(integer) — Static scheduling priority. Higher values are claimed sooner; negative values run only when the queue is otherwise idle. Same-priority jobs claim FIFO. When omitted, falls back to the job definition’spriority(or0).delay(integer seconds or duration string"5m"/"30s"/"1h"/"7d") — How long to wait before the job becomes claimable. Default0= immediate. Internally setsretry_after = now() + delay; works the same way as exponential-backoff retries.unique(string) — Dedup key. If another job with the same slug is already pending or running with thisuniquevalue, returns that job’s id instead of inserting a duplicate. Completed/failed jobs don’t block re-enqueue (only pending/running are “active”).
Returns: string — The queued job run ID (either freshly inserted
or, when unique matched, the existing one).
Example:
-- In an after_change hook
local job_id = crap.jobs.queue("send_welcome_email", {
user_id = ctx.data.id,
email = ctx.data.email,
})
crap.log.info("Queued welcome email job: " .. job_id)
-- High-priority job (e.g. password reset email) jumps the queue.
crap.jobs.queue("send_password_reset", { user_id = id }, { priority = 10 })
-- Low-priority background work (e.g. analytics rollup) runs only
-- when the queue is otherwise idle. Note: prefer setting this on
-- the definition with `priority = -5` so every enqueue site inherits it.
crap.jobs.queue("analytics_rollup", {}, { priority = -5 })
-- Delayed: send the welcome email 5 minutes after signup so a
-- newly-created user has time to land on the dashboard first.
crap.jobs.queue("send_welcome_email", { user_id = id }, { delay = "5m" })
-- Idempotent: only one "rebuild search index for collection X" job
-- pending at a time. If two writes fire in quick succession, the
-- second `queue()` returns the first job's id — no duplicate work.
crap.jobs.queue("reindex_collection", { slug = "posts" }, {
unique = "reindex:posts",
})
Defining a job with a default priority:
crap.jobs.define("analytics_rollup", {
handler = "jobs.analytics.rollup",
schedule = "0 3 * * *", -- nightly
priority = -5, -- yield to user-triggered work
timeout = 600,
})
-- Now every cron-fired run AND every manual `crap.jobs.queue("analytics_rollup")`
-- inherits priority = -5 unless the queue site explicitly overrides.
Handler Function
The handler function receives a context table and has full CRUD access:
local M = {}
function M.run(ctx)
-- ctx.data: input data from queue() or {} for cron
-- ctx.job.slug: job definition slug
-- ctx.job.attempt: current attempt (1-based)
-- ctx.job.max_attempts: total attempts allowed
-- Full CRUD access:
local result = crap.collections.posts.find({
where = { status = "expired" }
})
-- Return value is stored as the job result (optional)
return { processed = result.pagination.totalDocs }
end
return M
Transactions in job handlers
Each CRUD call inside a job handler runs in its own short-lived
BEGIN IMMEDIATE transaction (pool-mode). Different from hooks,
which share the parent operation’s write transaction.
| Context | Transaction model |
|---|---|
Hook (before_change, after_change, …) | All CRUD ops share the parent’s write tx. Atomic with the document being created/updated. |
| Job handler (default) | Each CRUD op is its own short-lived BEGIN IMMEDIATE tx (pool-mode). find then update are two distinct atomic writes. |
Inside crap.transaction(fn) (job-only) | All CRUD ops in fn share one BEGIN IMMEDIATE tx. Used for multi-step atomicity in jobs. |
Why pool-mode for jobs
Earlier releases wrapped each job handler in a single outer
BEGIN DEFERRED transaction shared across all CRUD calls. Long-running
handlers that did find followed by update (canonical pattern) could
hit SQLITE_BUSY_SNAPSHOT if any other writer (admin edits, image
queue, other jobs) committed between the read and the write — SQLite’s
deadlock-prevention error, not retried by busy_timeout. The
pool-mode model avoids this entirely: each op opens its own
IMMEDIATE tx, so there’s no snapshot window for a writer to invalidate.
crap.transaction(fn) — explicit multi-step atomicity
When a job needs multiple CRUD ops to be atomic (e.g., read a counter,
write it back incremented), wrap them in crap.transaction(fn):
local M = {}
function M.run(ctx)
-- Atomic: both ops share one IMMEDIATE tx.
crap.transaction(function()
local doc = crap.collections.posts.find_by_id(ctx.data.id)
crap.collections.posts.update(ctx.data.id, {
view_count = doc.view_count + 1,
})
end)
end
return M
- Errors raised inside
fnroll back the entire block. - The return value of
fnis the return value ofcrap.transaction. - Inside a hook (which already has a shared tx),
crap.transaction(fn)is a pass-through — useful so the same code works in both contexts. - Calling
crap.transactionfrom outside a job/hook (e.g.init.lua) errors with a clear message. - Nesting
crap.transaction(crap.transaction(...))is currently a pass-through on the inner call (noSAVEPOINTsupport yet).
Migration from earlier releases
Existing job handlers that depended on implicit cross-CRUD atomicity
(e.g., a job that does two updates and expects both to roll back on
error) need to wrap those updates in crap.transaction(fn):
-- Before (was implicitly atomic, but SQLITE_BUSY_SNAPSHOT-prone):
function M.run(ctx)
crap.collections.posts.update(id_a, { count = 1 })
crap.collections.posts.update(id_b, { count = 2 })
-- If a writer commits between the two updates, the second would
-- fail. Now both succeed independently (each is its own tx),
-- but they're no longer atomic with each other.
end
-- After (explicit atomicity):
function M.run(ctx)
crap.transaction(function()
crap.collections.posts.update(id_a, { count = 1 })
crap.collections.posts.update(id_b, { count = 2 })
end)
end
Handling rollbacks with pcall
crap.transaction follows Lua’s normal exception model: any error
inside the block triggers a rollback and the error propagates to the
caller. There is no on_rollback callback — use Lua’s built-in
pcall to react to rollbacks:
function M.run(ctx)
local ok, err = pcall(crap.transaction, function()
crap.collections.posts.update(ctx.data.id, {
balance = doc.balance - amount,
})
crap.collections.audit_log.create({
kind = "transfer",
amount = amount,
})
-- Validate post-conditions; raising here rolls back BOTH writes.
if doc.balance - amount < 0 then
error("balance would go negative")
end
end)
if not ok then
crap.log.error("transfer failed, rolled back: " .. tostring(err))
-- Re-enqueue, emit a metric, schedule a compensation job, …
crap.jobs.queue("send_failure_email", {
user_id = ctx.data.user_id,
reason = tostring(err),
}, { priority = 5 })
end
end
Common patterns:
| Goal | Idiom |
|---|---|
| Re-enqueue the work on failure | if not ok then crap.jobs.queue(ctx.slug, ctx.data) end |
| Emit a metric on every rollback | if not ok then crap.metrics.inc("tx_rollback") end |
| Compensate external side-effects | Run the side-effect inside the if not ok branch (after rollback) |
| Stop the job from being marked failed | Catch with pcall and return success from M.run; the framework will treat it as completed |
Concurrency model
Three caps stack when the scheduler decides whether to claim a job. Strictest applicable cap wins.
| Cap | Scope | Configured in | Counts |
|---|---|---|---|
[jobs] max_concurrent | Per-server | crap.toml | Total jobs in flight on this scheduler process |
[jobs.queues.<name>] concurrency | Cluster-global | crap.toml | Total jobs in queue <name> across the whole DB |
JobDefinition::concurrency | Cluster-global | crap.jobs.define({ concurrency = N }) | Total jobs of this specific slug across the whole DB |
Example: queue emails cap=4, slug send_welcome concurrency=2 →
- At most 4 jobs running in queue
emailstotal across the cluster. - Of those, at most 2 can be
send_welcomespecifically. - The remaining 2 slots can be filled by any other slug routed to
emails.
Queues without an entry in [jobs.queues] are unconstrained beyond
the global max_concurrent. The scheduler logs a warning at startup
if [jobs.queues] references a queue name that no defined job uses
(typo catcher).
[jobs.queues.<name>] also carries two non-concurrency knobs that
apply to system jobs (_system_image_convert, _system_email)
which lack their own JobDefinition:
| Field | What it sets |
|---|---|
timeout | Per-job wall-clock timeout for system jobs in this queue. User Lua jobs use the timeout on their JobDefinition instead. |
retries | Default max_attempts for jobs in this queue (max_attempts = retries + 1). Used by system jobs AND by user Lua jobs that omit retries in crap.jobs.define. Explicit JobDefinition.retries (including retries = 0) overrides the queue default. crap.email.queue{ retries = N } overrides for that one call. |
See [jobs.queues] in
the config reference for the full field table, defaults, and merging
semantics.
Multi-server semantics
The CMS supports running multiple scheduler processes against the same Postgres database (each binary runs its own scheduler tick loop). SQLite is single-process by file-locking, so this section applies to Postgres deployments.
Every concurrency cap is cluster-wide. Each server’s poll tick
reads COUNT(*) FROM _crap_jobs WHERE status = 'running' (filtered
by slug or queue as needed) from the shared DB, so all servers see
the same running totals and apply the same caps.
| Cap / knob | Mechanism |
|---|---|
[jobs] max_concurrent | SELECT COUNT(*) ... WHERE status='running' (no slug filter). |
[jobs.queues.<name>] concurrency | Per-queue COUNT(*) via count_running_per_queue. |
JobDefinition::concurrency | Per-slug COUNT(*) via count_running_per_slug. |
[jobs] priority_decay | Pure SQL ORDER BY — every server orders the same way. |
What this means in practice:
- Setting
max_concurrent = 10on every server caps total in-flight jobs at 10 across the entire cluster, not 10 × N. Adding more servers does not multiply throughput; it adds load distribution and fault tolerance, but the cluster-wide cap holds. - If servers have different
max_concurrentvalues (e.g. staggered rollout), the effective cluster cap converges to the highest value across servers. Once cluster running reaches that number, even the strictest server sees the cap as reached. - Per-queue and per-slug caps compose cleanly across servers: an
emailsqueue withconcurrency = 4will have at most 4 email jobs running cluster-wide, regardless of server count.
Operator guidance:
- Set
[jobs] max_concurrentbased on the throughput your cluster should sustain (not per-server). Tune up if backlogs grow. - Use
[jobs.queues.<name>] concurrencyfor resource-shared work (SMTP pool, image encoder pool, …) — these caps are global. - Use
JobDefinition::concurrency(crap.jobs.define({ concurrency = N })) for “at most N of this specific job type at a time” — also global. priority_decay’s ordering is stable across servers as long as their clocks are within a few seconds. Small clock drift may cause a different server to win a particular tick’s race, but the set of claimed jobs is the same.
Cap precision under concurrent ticks. Per-slug caps are enforced
inside the claim transaction (the running count is part of the
locked SQL subquery), so they’re exact. Global max_concurrent and
per-queue caps are checked before the claim transaction starts, so
two servers ticking within the same millisecond can each claim a
small batch and briefly push the cluster total over the cap. The
overshoot is bounded by the number of concurrent ticks × the batch
size and converges back as soon as one tick completes — Sidekiq, Oban,
and similar systems behave the same way. Treat these caps as soft.
If you need precise enforcement (e.g. licensing limits), use a
per-slug cap.
The shared coordination point is the database — FOR UPDATE SKIP LOCKED (Postgres) or BEGIN IMMEDIATE (SQLite) ensures no two
servers claim the same job row.
Filter Operators
Filters are used in crap.collections.find() queries and in access control constraint returns. They map to SQL WHERE clauses.
Shorthand: Simple Equality
String values are treated as equals:
{ where = { status = "published" } }
-- SQL: WHERE status = 'published'
Operator Syntax
Use a table to specify an operator:
{ where = { title = { contains = "hello" } } }
-- SQL: WHERE title LIKE '%hello%'
Operator Reference
| Operator | Lua Syntax | SQL | Description |
|---|---|---|---|
equals | { equals = "value" } | field = ? | Exact match |
not_equals | { not_equals = "value" } | field != ? | Not equal |
like | { like = "pattern%" } | field LIKE ? | SQL LIKE pattern |
contains | { contains = "text" } | field LIKE '%text%' ESCAPE '\' | Substring match (wildcards % and _ in the search text are escaped) |
greater_than | { greater_than = "10" } | field > ? | Greater than |
less_than | { less_than = "10" } | field < ? | Less than |
greater_than_or_equal | { greater_than_or_equal = "10" } | field >= ? | Greater than or equal |
less_than_or_equal | { less_than_or_equal = "10" } | field <= ? | Less than or equal |
in | { ["in"] = { "a", "b" } } | field IN (?, ?) | Value in list |
not_in | { not_in = { "a", "b" } } | field NOT IN (?, ?) | Value not in list |
exists | { exists = true } | field IS NOT NULL | Field is not null (value is ignored — only the key matters) |
not_exists | { not_exists = true } | field IS NULL | Field is null (value is ignored — use not_exists for IS NULL, not { exists = false }) |
Note:
inis a Lua keyword, so use["in"]bracket syntax.
Examples
-- Published posts containing "hello"
crap.collections.posts.find({
where = {
status = "published",
title = { contains = "hello" },
},
})
-- Posts created after a date
crap.collections.posts.find({
where = {
created_at = { greater_than = "2024-01-01" },
},
})
-- Posts with specific statuses
crap.collections.posts.find({
where = {
status = { ["in"] = { "draft", "published" } },
},
})
-- Posts without a category
crap.collections.posts.find({
where = {
category = { not_exists = true },
},
})
-- Posts with wildcard title match
crap.collections.posts.find({
where = {
title = { like = "Hello%" },
},
})
Multiple Filters
Multiple filters are combined with AND:
crap.collections.posts.find({
where = {
status = "published",
created_at = { greater_than = "2024-01-01" },
title = { contains = "update" },
},
})
-- SQL: WHERE status = ? AND created_at > ? AND title LIKE ?
OR Groups
Use the ["or"] key to combine groups of conditions with OR logic. Each element is a table of AND-ed conditions:
-- title contains "hello" OR category = "news"
crap.collections.posts.find({
where = {
["or"] = {
{ title = { contains = "hello" } },
{ category = "news" },
},
},
})
-- SQL: WHERE (title LIKE '%hello%' OR category = ?)
OR can combine with top-level AND filters:
-- status = "published" AND (title contains "hello" OR title contains "world")
crap.collections.posts.find({
where = {
status = "published",
["or"] = {
{ title = { contains = "hello" } },
{ title = { contains = "world" } },
},
},
})
-- SQL: WHERE status = ? AND (title LIKE '%hello%' OR title LIKE '%world%')
Each OR element can have multiple fields (AND-ed within the group):
-- (status = "published" AND title contains "hello") OR (status = "draft")
crap.collections.posts.find({
where = {
["or"] = {
{ status = "published", title = { contains = "hello" } },
{ status = "draft" },
},
},
})
-- SQL: WHERE ((status = ? AND title LIKE '%hello%') OR status = ?)
Note:
oris not a Lua keyword, but["or"]bracket syntax is recommended for clarity.
Nested Field Filters (Dot Notation)
Filter on sub-fields of group, array, blocks, and has-many relationship fields using dot notation:
-- Group sub-field: seo.meta_title → seo__meta_title column
crap.collections.pages.find({
where = { ["seo.meta_title"] = { contains = "SEO" } },
})
-- Array sub-field: find products with any variant color "red"
crap.collections.products.find({
where = { ["variants.color"] = "red" },
})
-- Block sub-field: find posts with any content block containing "hello"
crap.collections.posts.find({
where = { ["content.body"] = { contains = "hello" } },
})
-- Block type filter
crap.collections.posts.find({
where = { ["content._block_type"] = "image" },
})
-- Has-many relationship: find posts with a specific tag
crap.collections.posts.find({
where = { ["tags.id"] = "tag-123" },
})
Array and block filters use EXISTS subqueries — they match parent documents where at least one row matches. All filter operators work with dot notation paths.
See Query & Filters for the full reference.
Value Types
Filter values are coerced to a SQL bind type based on the field’s declared type, so
comparisons run on the right kind of column (REAL for numbers, INTEGER for booleans,
TEXT for ISO date strings, etc.). Coercion only applies to comparison operators —
text-pattern operators (like, contains, starts_with, ends_with, regex) always
bind as TEXT regardless of the field type.
| Field type | Comparison bind type | Notes |
|---|---|---|
number | REAL | Filter value is parsed as a 64-bit float. Invalid input (non-numeric, NaN, Infinity) falls back to TEXT and logs a warning — the query still runs and will typically return no rows. |
checkbox | INTEGER (0 / 1) | Accepts "true", "false", "1", "0", "yes", "no", "on", "off". Anything else falls back to TEXT with a warning. |
date | TEXT (normalized ISO) | Stored as ISO-8601 strings; the filter value is normalized via the date coercer (e.g. "2024-01-15" → "2024-01-15T00:00:00.000Z") so lexicographic comparison aligns with stored values. |
text, textarea, email, select, radio, json, code, richtext | TEXT | Bound as-is. |
| Field type unknown / not resolved | TEXT | Default fallback when the caller cannot determine the field type. |
-- Number field — bound as REAL, comparison is numeric
crap.collections.products.find({
where = { price = { greater_than = 9.99 } },
})
-- Checkbox field — bound as INTEGER 1
crap.collections.posts.find({
where = { published = true },
})
-- Text-only operator on a number field still binds as TEXT
crap.collections.products.find({
where = { sku = { contains = "42" } },
})
MCP (Model Context Protocol)
Crap CMS includes a built-in MCP server that lets AI assistants (Claude Desktop, Cursor, VS Code extensions, custom agents) interact with your CMS content and schema.
The MCP server auto-generates tool definitions from your Lua-defined collections and globals. Any CMS instance automatically gets a full MCP API matching its schema.
Configuration
Add an [mcp] section to crap.toml:
[mcp]
enabled = true # Enable MCP server (default: false)
http = false # Enable HTTP transport on /mcp (default: false)
config_tools = false # Enable config generation tools (default: false)
api_key = "" # API key for HTTP auth (required when http = true)
include_collections = [] # Whitelist (empty = all)
exclude_collections = [] # Blacklist (takes precedence over include)
Transports
stdio (default)
Run the MCP server as a subprocess that reads JSON-RPC from stdin and writes to stdout:
crap-cms mcp
Or from outside the config directory:
crap-cms mcp -C /path/to/config
For Claude Code (CLI / IDE extensions), add via the CLI:
claude mcp add-json my-cms '{"type":"stdio","command":"crap-cms","args":["-C","/path/to/config","mcp"]}' --scope local
Or create a .mcp.json in your project root (shared with team via version control):
{
"mcpServers": {
"my-cms": {
"type": "stdio",
"command": "crap-cms",
"args": ["-C", "/path/to/config", "mcp"]
}
}
}
The -C path must point to a directory containing crap.toml. Use an absolute path or a path relative to where Claude Code is launched from.
crap-cms init automatically generates a .mcp.json in the config directory, so new projects work with Claude Code out of the box.
Verify with claude mcp list.
For Claude Desktop, add to your claude_desktop_config.json:
{
"mcpServers": {
"my-cms": {
"command": "crap-cms",
"args": ["mcp", "-C", "/path/to/config"]
}
}
}
HTTP
When mcp.http = true, the admin server exposes a POST /mcp endpoint.
Send JSON-RPC 2.0 requests as the request body.
An api_key is required when HTTP transport is enabled. Requests must include
an Authorization: Bearer <key> header. If mcp.http = true and api_key is empty,
every request to POST /mcp is rejected with 401 Unauthorized — the server still
starts, but the endpoint is effectively inaccessible.
Auto-Generated Tools
Content CRUD (per collection)
For each collection (e.g., posts), five tools are generated:
| Tool | Description |
|---|---|
find_posts | Query documents with filters, ordering, pagination |
find_by_id_posts | Get a single document by ID |
create_posts | Create a new document |
update_posts | Update an existing document |
delete_posts | Delete a document |
Input schemas are generated from your field definitions. Required fields, select options, and relationship types are all reflected in the JSON Schema.
Global CRUD (per global)
For each global (e.g., settings):
| Tool | Description |
|---|---|
global_read_settings | Read the global document |
global_update_settings | Update the global document |
Schema Introspection
Always available:
| Tool | Description |
|---|---|
list_collections | List all collections with their labels and capabilities |
describe_collection | Get full field schema for a collection or global |
list_field_types | List all field types with descriptions and capabilities |
cli_reference | Get CLI command reference (all or specific command) |
Config Generation Tools (opt-in)
When config_tools = true:
| Tool | Description |
|---|---|
read_config_file | Read a file from the config directory |
write_config_file | Write a Lua file to the config directory |
list_config_files | List files in the config directory |
These are opt-in because they allow writing to the filesystem.
MCP Descriptions
Add optional mcp tables to your Lua definitions to provide context for AI assistants:
Collection level
return {
slug = "posts",
mcp = {
description = "Blog posts with title, content, and author relationship",
},
fields = { ... }
}
Field level
crap.fields.select({
name = "status",
mcp = {
description = "Publication status - controls visibility on the frontend",
},
options = { ... },
})
If no mcp.description is set, the tool falls back to admin.description
(for fields) or a generated description based on the collection label.
Collection Filtering
Use include_collections and exclude_collections to control which collections
are exposed via MCP:
[mcp]
enabled = true
exclude_collections = ["users"] # Hide sensitive collections
exclude_collections takes precedence when a collection appears in both lists.
Security & Access Model
MCP operates with full access — collection-level and field-level access control
functions are not applied. This is by design: MCP is a machine-to-machine API surface
(equivalent to Lua’s overrideAccess = true), gated by transport-level authentication:
- stdio: Access is controlled by who can run the process.
- HTTP: Access is controlled by the
api_keysetting. An API key is required whenhttp = true— set it in[mcp]incrap.tomlbefore enabling HTTP. Ifhttp = truebutapi_keyis empty, the server still starts and registers the route, but every request toPOST /mcpis rejected with401 Unauthorized. The check is per-request, not at startup; operators should verifyapi_keyis set before exposing the endpoint externally.
To restrict which collections are accessible, use include_collections /
exclude_collections. These filters are enforced both in tool listing (tools/list)
and at execution time, so knowing a collection slug is not enough to bypass the filter.
All MCP write operations (create, update, delete) are logged at info level for
audit purposes. Hooks still fire on all MCP writes (same lifecycle as admin/gRPC).
Resources
The MCP server also exposes read-only resources:
| URI | Description |
|---|---|
crap://schema/collections | Full schema of all collections as JSON |
crap://schema/globals | Full schema of all globals as JSON |
crap://config | Current configuration (secrets sanitized: auth.secret, email.smtp_pass, mcp.api_key) |
Query Parameters
The find_* tools accept these parameters:
| Parameter | Type | Description |
|---|---|---|
where | object | Filter conditions (same syntax as gRPC/Lua API) |
order_by | string | Sort field (prefix with - for descending, e.g., "-created_at") |
limit | integer | Max results per page |
page | integer | Page number, 1-indexed (page mode only) |
after_cursor | string | Forward cursor (cursor mode only, mutually exclusive with page and before_cursor) |
before_cursor | string | Backward cursor (cursor mode only, mutually exclusive with page and after_cursor) |
depth | integer | Relationship population depth |
search | string | Full-text search query |
Response Format
find_* tools return a JSON object with docs and pagination:
{
"docs": [
{ "id": "abc123", "title": "Hello World", "created_at": "2026-01-15T09:00:00Z" }
],
"pagination": {
"totalDocs": 25,
"limit": 10,
"hasNextPage": true,
"hasPrevPage": false,
"totalPages": 3,
"page": 1,
"pageStart": 1,
"nextPage": 2
}
}
In cursor mode, page/totalPages/pageStart/nextPage/prevPage are replaced by startCursor/endCursor.
Where clause example
{
"name": "find_posts",
"arguments": {
"where": {
"status": { "equals": "published" },
"created_at": { "greater_than": "2024-01-01" }
},
"order_by": "-created_at",
"limit": 10
}
}
Supported operators: equals, not_equals, greater_than, greater_than_equal,
less_than, less_than_equal, like, contains, in (array), not_in (array),
exists, not_exists.
Note: MCP uses shortened operator names (
greater_than_equal,less_than_equal) compared to the gRPC/Lua API which usesgreater_than_or_equalandless_than_or_equal.
gRPC API
Crap CMS exposes a gRPC API via Tonic for programmatic access to all content operations.
Service
service ContentAPI {
rpc Find (FindRequest) returns (FindResponse);
rpc FindByID (FindByIDRequest) returns (FindByIDResponse);
rpc Create (CreateRequest) returns (CreateResponse);
rpc Update (UpdateRequest) returns (UpdateResponse);
rpc Delete (DeleteRequest) returns (DeleteResponse);
rpc Count (CountRequest) returns (CountResponse);
rpc UpdateMany (UpdateManyRequest) returns (UpdateManyResponse);
rpc DeleteMany (DeleteManyRequest) returns (DeleteManyResponse);
rpc GetGlobal (GetGlobalRequest) returns (GetGlobalResponse);
rpc UpdateGlobal (UpdateGlobalRequest) returns (UpdateGlobalResponse);
rpc Login (LoginRequest) returns (LoginResponse);
rpc Me (MeRequest) returns (MeResponse);
rpc ForgotPassword (ForgotPasswordRequest) returns (ForgotPasswordResponse);
rpc ResetPassword (ResetPasswordRequest) returns (ResetPasswordResponse);
rpc VerifyEmail (VerifyEmailRequest) returns (VerifyEmailResponse);
rpc ListCollections (ListCollectionsRequest) returns (ListCollectionsResponse);
rpc DescribeCollection (DescribeCollectionRequest) returns (DescribeCollectionResponse);
rpc Subscribe (SubscribeRequest) returns (stream MutationEvent);
rpc ListVersions (ListVersionsRequest) returns (ListVersionsResponse);
rpc RestoreVersion (RestoreVersionRequest) returns (RestoreVersionResponse);
rpc ListJobs (ListJobsRequest) returns (ListJobsResponse);
rpc TriggerJob (TriggerJobRequest) returns (TriggerJobResponse);
rpc GetJobRun (GetJobRunRequest) returns (GetJobRunResponse);
rpc ListJobRuns (ListJobRunsRequest) returns (ListJobRunsResponse);
}
Port
Default: 50051 (configurable via [server] grpc_port in crap.toml).
Message Size Limits
The maximum gRPC message size (both request and response) defaults to 16MB — configurable via grpc_max_message_size in [server]. This is higher than Tonic’s built-in 4MB default to accommodate large Find responses with deep relationship population.
[server]
grpc_max_message_size = "32MB" # increase for very large responses
Timeouts
An optional request timeout can be set via grpc_timeout in [server]. When set, RPCs exceeding the timeout return DEADLINE_EXCEEDED.
[server]
grpc_timeout = "30s"
Bulk Operation Limits
UpdateMany and DeleteMany process at most 10,000 documents per call. This prevents unbounded memory usage when a broad filter matches a very large dataset. For larger operations, use paginated calls with a where clause to process documents in batches.
Server Reflection
When enabled (grpc_reflection = true in [server], disabled by default), the server supports gRPC reflection, so tools like grpcurl work without importing the proto file:
# List services
grpcurl -plaintext localhost:50051 list
# Describe a service
grpcurl -plaintext localhost:50051 describe crap.ContentAPI
# Describe a message type
grpcurl -plaintext localhost:50051 describe crap.FindRequest
Document Format
All documents use the same message format:
message Document {
string id = 1;
string collection = 2;
google.protobuf.Struct fields = 3;
optional string created_at = 4;
optional string updated_at = 5;
}
The fields property is a Struct (JSON object) containing all user-defined field values.
Testing with grpcurl
The repository includes tests/api.sh with grpcurl commands for every RPC:
source tests/api.sh
find_posts
create_post
find_post_by_id abc123
All commands use -plaintext (no TLS) and server reflection.
RPCs
All RPCs with request/response shapes and grpcurl examples.
Find
Find documents in a collection with filtering, sorting, and pagination.
message FindRequest {
string collection = 1;
optional string where = 2; // JSON where clause
optional string order_by = 3; // "-field" for descending
optional int64 limit = 4;
optional int64 page = 5; // page number (1-based, default: 1)
optional int32 depth = 6; // population depth (default: 0)
optional string locale = 7; // locale code for localized fields
repeated string select = 8; // fields to return (empty = all)
optional bool draft = 9; // true = include drafts (versioned collections)
optional string after_cursor = 10; // opaque forward cursor for cursor-based pagination
optional string before_cursor = 11; // opaque backward cursor for cursor-based pagination
optional string search = 12; // FTS5 full-text search query
optional bool trash = 13; // true = return only soft-deleted documents
}
message PaginationInfo {
int64 total_docs = 1; // total matching documents (before limit/page)
int64 limit = 2; // applied limit
optional int64 total_pages = 3; // total pages (page mode only)
optional int64 page = 4; // current page (page mode only, 1-based)
optional int64 page_start = 5; // 1-based index of first doc on this page (page mode only)
bool has_prev_page = 6; // whether a previous page exists
bool has_next_page = 7; // whether a next page exists
optional int64 prev_page = 8; // previous page number (nil if first page)
optional int64 next_page = 9; // next page number (nil if last page)
optional string start_cursor = 10; // opaque cursor of first doc in results (cursor mode only)
optional string end_cursor = 11; // opaque cursor of last doc in results (cursor mode only)
}
message FindResponse {
repeated Document documents = 1;
PaginationInfo pagination = 2;
}
Pagination metadata is nested in a PaginationInfo message. In page mode (default), page, total_pages, page_start, prev_page, and next_page are computed. In cursor mode, start_cursor and end_cursor are provided instead — these are the cursors of the first and last documents in the result set. has_prev_page and has_next_page work in both modes.
after_cursor/before_cursor and page are mutually exclusive. after_cursor and before_cursor are also mutually exclusive with each other. Cursors are only present in the response when [pagination] mode = "cursor" is set in crap.toml.
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\": \"published\"}",
"order_by": "-created_at",
"limit": "10",
"depth": 1
}' localhost:50051 crap.ContentAPI/Find
FindByID
Get a single document by ID.
message FindByIDRequest {
string collection = 1;
string id = 2;
optional int32 depth = 3; // default: depth.default_depth from crap.toml
optional string locale = 4; // locale code for localized fields
repeated string select = 5; // fields to return (empty = all)
optional bool draft = 6; // true = return latest version (may be draft)
optional bool trash = 7; // true = allow finding soft-deleted documents
}
message FindByIDResponse {
optional Document document = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"depth": 2
}' localhost:50051 crap.ContentAPI/FindByID
Create
Create a new document.
message CreateRequest {
string collection = 1;
google.protobuf.Struct data = 2;
optional string locale = 3; // locale code for localized fields
optional bool draft = 4; // true = create as draft (versioned collections)
}
message CreateResponse {
Document document = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"data": {
"title": "Hello World",
"slug": "hello-world",
"status": "draft"
}
}' localhost:50051 crap.ContentAPI/Create
For auth collections, include password in the data to set the user’s password.
Update
Update an existing document.
message UpdateRequest {
string collection = 1;
string id = 2;
google.protobuf.Struct data = 3;
optional string locale = 4; // locale code for localized fields
optional bool draft = 5; // true = version-only save (main table unchanged)
optional bool unpublish = 6; // true = set status to draft
}
message UpdateResponse {
Document document = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"data": { "title": "Updated Title", "status": "published" }
}' localhost:50051 crap.ContentAPI/Update
Delete
Delete a document by ID. For collections with soft_delete = true, moves to trash by default. Set force_hard_delete = true to permanently delete.
message DeleteRequest {
string collection = 1;
string id = 2;
bool force_hard_delete = 3; // permanently delete even with soft_delete
}
message DeleteResponse {
bool success = 1;
bool soft_deleted = 2; // true if moved to trash (not permanently deleted)
}
# Soft delete (moves to trash)
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123"
}' localhost:50051 crap.ContentAPI/Delete
# Force permanent delete
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123",
"force_hard_delete": true
}' localhost:50051 crap.ContentAPI/Delete
Undelete
Undelete a soft-deleted document from trash. Only works on collections with soft_delete = true.
message UndeleteRequest {
string collection = 1;
string id = 2;
}
message UndeleteResponse {
Document document = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"id": "abc123"
}' localhost:50051 crap.ContentAPI/Undelete
Count
Count documents matching an optional filter. Respects collection-level read access.
message CountRequest {
string collection = 1;
optional string where = 2; // JSON where clause
optional string locale = 3; // locale code for localized field filtering
optional bool draft = 4; // true = include drafts
optional string search = 5; // FTS5 full-text search query
}
message CountResponse {
int64 count = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\": \"published\"}"
}' localhost:50051 crap.ContentAPI/Count
UpdateMany
Bulk-update all documents matching a filter. All updates run in a single transaction (all-or-nothing). Runs the full per-document lifecycle by default: before_validate → field validation → before_change → DB update → after_change — the same pipeline as single-document Update.
Only provided fields are written (partial update). Absent fields are left unchanged — including checkbox fields, which are not reset to 0 as they would be in a full single-document update.
Password updates are rejected in bulk operations. Use single-document Update instead.
message UpdateManyRequest {
string collection = 1;
optional string where = 2; // JSON where clause (omit = all docs)
google.protobuf.Struct data = 3; // field values to apply
optional string locale = 4; // locale code for localized fields
optional bool draft = 5; // true = save as drafts
optional bool hooks = 6; // default: true. Set false to skip hooks & validation.
}
message UpdateManyResponse {
int64 modified = 1;
}
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\": \"draft\"}",
"data": { "status": "published" }
}' localhost:50051 crap.ContentAPI/UpdateMany
Limit: A single
UpdateManycall processes at most 10,000 documents. Use paginated calls (with awhereclause) for larger datasets.
DeleteMany
Bulk-delete all documents matching a filter. All deletions run in a single transaction (all-or-nothing). Fires per-document hooks by default. Respects the collection’s soft_delete setting — documents are moved to trash unless force_hard_delete is set.
message DeleteManyRequest {
string collection = 1;
optional string where = 2; // JSON where clause (omit = all docs)
optional bool hooks = 3; // default: true. Set false to skip hooks.
bool force_hard_delete = 4; // permanently delete even if soft_delete is enabled
}
message DeleteManyResponse {
int64 deleted = 1; // permanently deleted count
int64 soft_deleted = 2; // soft-deleted (trashed) count
int64 skipped = 3; // skipped because still referenced by other documents
}
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\": \"archived\"}"
}' localhost:50051 crap.ContentAPI/DeleteMany
Limit: A single
DeleteManycall processes at most 10,000 documents. Use paginated calls (with awhereclause) for larger datasets.
GetGlobal
Get a global’s current value.
message GetGlobalRequest {
string slug = 1;
optional string locale = 2; // locale code for localized fields
}
message GetGlobalResponse {
Document document = 1;
}
grpcurl -plaintext -d '{"slug": "site_settings"}' \
localhost:50051 crap.ContentAPI/GetGlobal
UpdateGlobal
Update a global’s value.
message UpdateGlobalRequest {
string slug = 1;
google.protobuf.Struct data = 2;
optional string locale = 3; // locale code for localized fields
}
message UpdateGlobalResponse {
Document document = 1;
}
grpcurl -plaintext -d '{
"slug": "site_settings",
"data": { "site_name": "Updated Name" }
}' localhost:50051 crap.ContentAPI/UpdateGlobal
Login
Authenticate with email and password. Returns a JWT token and user document.
message LoginRequest {
string collection = 1;
string email = 2;
string password = 3;
}
message LoginResponse {
string token = 1;
Document user = 2;
}
grpcurl -plaintext -d '{
"collection": "users",
"email": "admin@example.com",
"password": "secret123"
}' localhost:50051 crap.ContentAPI/Login
Me
Get the current authenticated user from a token. The token is read from the authorization metadata header first; if absent, falls back to the token field in the request body.
message MeRequest {
string token = 1;
}
message MeResponse {
Document user = 1;
}
grpcurl -plaintext -d '{
"token": "eyJhbGciOi..."
}' localhost:50051 crap.ContentAPI/Me
ForgotPassword
Initiate a password reset flow. Generates a reset token and sends a reset email. Always returns success to prevent user enumeration.
message ForgotPasswordRequest {
string collection = 1;
string email = 2;
}
message ForgotPasswordResponse {
bool success = 1; // always true
}
grpcurl -plaintext -d '{
"collection": "users",
"email": "admin@example.com"
}' localhost:50051 crap.ContentAPI/ForgotPassword
Requires email configuration ([email] in crap.toml). Without email configured, the reset token is generated and stored but never delivered — the forgot-password flow is non-functional without SMTP.
ResetPassword
Reset a user’s password using a token from the reset email.
message ResetPasswordRequest {
string collection = 1;
string token = 2;
string new_password = 3;
}
message ResetPasswordResponse {
bool success = 1;
}
grpcurl -plaintext -d '{
"collection": "users",
"token": "the-reset-token",
"new_password": "newsecret123"
}' localhost:50051 crap.ContentAPI/ResetPassword
Tokens are single-use and expire after reset_token_expiry seconds (default: 3600 = 1 hour, configurable in [auth]).
VerifyEmail
Verify a user’s email address using a token sent during account creation.
message VerifyEmailRequest {
string collection = 1;
string token = 2;
}
message VerifyEmailResponse {
bool success = 1;
}
grpcurl -plaintext -d '{
"collection": "users",
"token": "the-verification-token"
}' localhost:50051 crap.ContentAPI/VerifyEmail
Only relevant for auth collections with verify_email: true.
Validate
Check field data against collection rules without persisting. Runs field validation (required, unique, type checks, custom validators) but does not open a write transaction. Use this to preview validation errors before a Create or Update call.
message ValidateRequest {
string collection = 1;
google.protobuf.Struct data = 2;
optional bool draft = 3; // relaxes required-field checks for draft collections
optional string locale = 4; // locale code for localized field validation
optional string id = 5; // when set, exclude this ID from unique checks (update path)
}
message ValidateResponse {
bool valid = 1;
map<string, string> errors = 2; // per-field error messages; empty when valid
}
grpcurl -plaintext -d '{
"collection": "posts",
"data": { "title": "Hello", "slug": "hello" }
}' localhost:50051 crap.ContentAPI/Validate
Access: optional. If a Bearer token is present, the collection’s create/update access function is evaluated (update when id is set). Field-level write-denied fields are stripped before validation runs.
LockAccount
Prevent a user from logging in. Only valid for auth-enabled collections. Any active live-update streams owned by the locked user are torn down with PermissionDenied.
message AccountActionRequest {
string collection = 1; // auth collection slug
string id = 2; // target user's nanoid ID
}
message AccountActionResponse {
bool success = 1;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"collection": "users",
"id": "usr_abc123"
}' localhost:50051 crap.ContentAPI/LockAccount
Access: authentication required. Returns INVALID_ARGUMENT if the collection is not an auth collection, NOT_FOUND if the user ID is missing, and UNAUTHENTICATED if no valid Bearer token is provided.
UnlockAccount
Re-enable login for a previously locked account. Only valid for auth-enabled collections.
message AccountActionRequest {
string collection = 1;
string id = 2;
}
message AccountActionResponse {
bool success = 1;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"collection": "users",
"id": "usr_abc123"
}' localhost:50051 crap.ContentAPI/UnlockAccount
Access: authentication required. Same error semantics as LockAccount.
VerifyAccount
Mark a user’s email as verified without requiring the user to click the verification link. Only valid for auth-enabled collections.
message AccountActionRequest {
string collection = 1;
string id = 2;
}
message AccountActionResponse {
bool success = 1;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"collection": "users",
"id": "usr_abc123"
}' localhost:50051 crap.ContentAPI/VerifyAccount
Access: authentication required. Same error semantics as LockAccount. See VerifyEmail for the token-based flow triggered by the user.
UnverifyAccount
Mark a user’s email as unverified. Only valid for auth-enabled collections.
message AccountActionRequest {
string collection = 1;
string id = 2;
}
message AccountActionResponse {
bool success = 1;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"collection": "users",
"id": "usr_abc123"
}' localhost:50051 crap.ContentAPI/UnverifyAccount
Access: authentication required. Same error semantics as LockAccount.
ListCollections
List all collections and globals (lightweight overview).
message ListCollectionsRequest {}
message ListCollectionsResponse {
repeated CollectionInfo collections = 1;
repeated GlobalInfo globals = 2;
}
grpcurl -plaintext -d '{}' localhost:50051 crap.ContentAPI/ListCollections
DescribeCollection
Get full field schema for a collection or global.
message DescribeCollectionRequest {
string slug = 1;
bool is_global = 2;
}
message DescribeCollectionResponse {
string slug = 1;
optional string singular_label = 2;
optional string plural_label = 3;
bool timestamps = 4;
bool auth = 5;
repeated FieldInfo fields = 6;
bool upload = 7;
bool drafts = 8; // true if collection has versions with drafts enabled
}
# Describe a collection
grpcurl -plaintext -d '{"slug": "posts"}' \
localhost:50051 crap.ContentAPI/DescribeCollection
# Describe a global
grpcurl -plaintext -d '{"slug": "site_settings", "is_global": true}' \
localhost:50051 crap.ContentAPI/DescribeCollection
ListVersions
List version history for a document. Only available for versioned collections.
message ListVersionsRequest {
string collection = 1;
string id = 2;
optional int64 limit = 3;
}
message ListVersionsResponse {
repeated VersionInfo versions = 1;
}
message VersionInfo {
string id = 1;
int64 version = 2;
string status = 3; // "published" or "draft"
bool latest = 4;
string created_at = 5;
}
grpcurl -plaintext -d '{
"collection": "articles",
"id": "abc123",
"limit": "10"
}' localhost:50051 crap.ContentAPI/ListVersions
Returns versions in newest-first order. Returns an error for non-versioned collections.
RestoreVersion
Restore a previous version, writing its snapshot data back to the main table.
message RestoreVersionRequest {
string collection = 1;
string document_id = 2;
string version_id = 3;
}
message RestoreVersionResponse {
Document document = 1;
}
grpcurl -plaintext -d '{
"collection": "articles",
"document_id": "abc123",
"version_id": "v_xyz"
}' localhost:50051 crap.ContentAPI/RestoreVersion
This overwrites the main table with the version’s snapshot, sets _status to "published", and creates a new version entry for the restore. Returns an error for non-versioned collections.
Subscribe
Subscribe to real-time mutation events (server streaming). See Live Updates for full documentation.
message SubscribeRequest {
repeated string collections = 1; // empty = all accessible
repeated string globals = 2; // empty = all accessible
repeated string operations = 3; // "create","update","delete" — empty = all
string token = 4; // auth token
}
message MutationEvent {
uint64 sequence = 1;
string timestamp = 2;
string target = 3;
string operation = 4;
string collection = 5;
string document_id = 6;
google.protobuf.Struct data = 7;
}
# Subscribe to all events
grpcurl -plaintext -d '{}' \
localhost:50051 crap.ContentAPI/Subscribe
# Subscribe to specific collections with auth
grpcurl -plaintext -d '{
"collections": ["posts"],
"operations": ["create", "update"],
"token": "your-jwt-token"
}' localhost:50051 crap.ContentAPI/Subscribe
ListJobs
List all defined jobs and their configuration. Requires authentication.
message ListJobsRequest {}
message ListJobsResponse {
repeated JobDefinitionInfo jobs = 1;
}
message JobDefinitionInfo {
string slug = 1;
string handler = 2;
optional string schedule = 3;
string queue = 4;
uint32 retries = 5;
uint64 timeout = 6;
uint32 concurrency = 7;
bool skip_if_running = 8;
optional string label = 9;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{}' \
localhost:50051 crap.ContentAPI/ListJobs
TriggerJob
Queue a job for execution. Requires authentication. Checks the job’s access function if defined.
message TriggerJobRequest {
string slug = 1;
optional string data_json = 2; // JSON input data
optional int32 priority = 3; // scheduling priority (higher = sooner; default 0)
}
message TriggerJobResponse {
string job_id = 1; // the queued job run ID
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"slug": "cleanup_expired",
"data_json": "{\"force\": true}",
"priority": 10
}' localhost:50051 crap.ContentAPI/TriggerJob
GetJobRun
Get details of a specific job run. Requires authentication.
message GetJobRunRequest {
string id = 1;
}
message GetJobRunResponse {
string id = 1;
string slug = 2;
string status = 3;
string data_json = 4;
optional string result_json = 5;
optional string error = 6;
uint32 attempt = 7;
uint32 max_attempts = 8;
optional string scheduled_by = 9;
optional string created_at = 10;
optional string started_at = 11;
optional string completed_at = 12;
int32 priority = 13;
optional string unique_key = 14;
}
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"id": "job_run_id_here"
}' localhost:50051 crap.ContentAPI/GetJobRun
ListJobRuns
List job runs with optional filters. Requires authentication.
message ListJobRunsRequest {
optional string slug = 1;
optional string status = 2;
optional int64 limit = 3;
optional int64 offset = 4;
}
message ListJobRunsResponse {
repeated GetJobRunResponse runs = 1;
}
# List all recent job runs
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{}' \
localhost:50051 crap.ContentAPI/ListJobRuns
# Filter by slug and status
grpcurl -plaintext -H "authorization: Bearer $TOKEN" -d '{
"slug": "cleanup_expired",
"status": "completed",
"limit": "20"
}' localhost:50051 crap.ContentAPI/ListJobRuns
Where Clause
The Find RPC supports an advanced where parameter for operator-based filtering. This is a JSON string containing field filters with operators.
Format
The where parameter is a JSON-encoded string:
{
"field_name": { "operator": "value" },
"field_name2": { "operator": "value2" }
}
Multiple fields are combined with AND.
Operators
| Operator | JSON Syntax | SQL |
|---|---|---|
equals | {"field": {"equals": "value"}} | field = ? |
not_equals | {"field": {"not_equals": "value"}} | field != ? |
like | {"field": {"like": "pattern%"}} | field LIKE ? |
contains | {"field": {"contains": "text"}} | field LIKE '%text%' ESCAPE '\' (wildcards escaped) |
greater_than | {"field": {"greater_than": "10"}} | field > ? |
less_than | {"field": {"less_than": "10"}} | field < ? |
greater_than_or_equal | {"field": {"greater_than_or_equal": "10"}} | field >= ? |
less_than_or_equal | {"field": {"less_than_or_equal": "10"}} | field <= ? |
in | {"field": {"in": ["a", "b"]}} | field IN (?, ?) |
not_in | {"field": {"not_in": ["a", "b"]}} | field NOT IN (?, ?) |
exists | {"field": {"exists": true}} | field IS NOT NULL |
not_exists | {"field": {"not_exists": true}} | field IS NULL |
Note: For
exists/not_exists, the value is ignored — only the key matters. Field values must be strings or operator objects — numeric/boolean shorthand (e.g.,{"count": 42}) is not supported in the gRPC JSONwhereclause (use{"count": {"equals": "42"}}instead).
Field-Type-Aware Coercion
Even though filter values are always sent as JSON strings, they are coerced to the column’s SQL type before binding — so numeric comparisons are numeric, not lexicographic. Coercion is keyed off the field definition and the operator:
| Field type | Bound as | Notes |
|---|---|---|
| Number | REAL (f64) | Invalid / non-finite numbers fall back to TEXT with a runtime warning |
| Checkbox | INTEGER | Accepts "true"/"false"/"1"/"0" (and "yes"/"no"/"on"/"off"); unknown values fall back to TEXT |
| Date | TEXT | Normalized via ISO so lexicographic comparison works |
| Text-like fields | TEXT | Default for everything else |
Text-only operators (like, contains, starts_with, ends_with, regex) | TEXT | Always bound as text even on numeric columns |
See Filter Operators for the full per-operator table — the same coercion rules apply to Lua, gRPC, admin URL query params, and MCP.
Examples
# Published posts with "hello" in the title
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":{\"equals\":\"published\"},\"title\":{\"contains\":\"hello\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Posts with status in a list
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":{\"in\":[\"draft\",\"published\"]}}"
}' localhost:50051 crap.ContentAPI/Find
# Posts created after a date
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"created_at\":{\"greater_than\":\"2024-01-01\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Posts with null status
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":{\"not_exists\":true}}"
}' localhost:50051 crap.ContentAPI/Find
Nested Field Filters (Dot Notation)
Filter on sub-fields of group, array, blocks, and has-many relationship fields using dot notation:
# Group sub-field: seo.meta_title → seo__meta_title column
grpcurl -plaintext -d '{
"collection": "pages",
"where": "{\"seo.meta_title\":{\"contains\":\"SEO\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Array sub-field: products with any variant color "red"
grpcurl -plaintext -d '{
"collection": "products",
"where": "{\"variants.color\":{\"equals\":\"red\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Block sub-field: posts with content containing "hello"
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"content.body\":{\"contains\":\"hello\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Block type filter
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"content._block_type\":{\"equals\":\"image\"}}"
}' localhost:50051 crap.ContentAPI/Find
# Has-many relationship: posts with a specific tag
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"tags.id\":{\"equals\":\"tag-123\"}}"
}' localhost:50051 crap.ContentAPI/Find
Array and block filters use EXISTS subqueries — they match parent documents where at least one row matches. All filter operators work with dot notation paths.
See Query & Filters for the full reference.
OR Filters
Use the or key to combine groups of conditions with OR logic. Each element in the or array is an object whose fields are AND-ed together. Top-level filters outside or are AND-ed with the OR result.
# title contains "hello" OR category = "news"
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"or\":[{\"title\":{\"contains\":\"hello\"}},{\"category\":{\"equals\":\"news\"}}]}"
}' localhost:50051 crap.ContentAPI/Find
# status = "published" AND (title contains "hello" OR title contains "world")
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"status\":{\"equals\":\"published\"},\"or\":[{\"title\":{\"contains\":\"hello\"}},{\"title\":{\"contains\":\"world\"}}]}"
}' localhost:50051 crap.ContentAPI/Find
# Multi-condition groups: (status = "published" AND title contains "hello") OR (status = "draft")
grpcurl -plaintext -d '{
"collection": "posts",
"where": "{\"or\":[{\"status\":{\"equals\":\"published\"},\"title\":{\"contains\":\"hello\"}},{\"status\":{\"equals\":\"draft\"}}]}"
}' localhost:50051 crap.ContentAPI/Find
gRPC Authentication
Login
Authenticate with email and password to get a JWT token. Login is rate-limited — after too many failed attempts for an email, further attempts are temporarily blocked (configurable via max_login_attempts and login_lockout_seconds in crap.toml).
grpcurl -plaintext -d '{
"collection": "users",
"email": "admin@example.com",
"password": "secret123"
}' localhost:50051 crap.ContentAPI/Login
The response contains a token and the user document.
Bearer Token
Pass the token via the authorization metadata header:
grpcurl -plaintext \
-H "authorization: Bearer eyJhbGciOi..." \
-d '{"collection": "posts"}' \
localhost:50051 crap.ContentAPI/Find
The token is extracted from the authorization metadata and validated. The authenticated user is available to access control functions.
Get Current User
Use the Me RPC to validate a token and get the user:
grpcurl -plaintext -d '{
"token": "eyJhbGciOi..."
}' localhost:50051 crap.ContentAPI/Me
Token Expiry
Tokens expire after token_expiry seconds (default: 7200 = 2 hours). Configurable globally in crap.toml or per auth collection.
Security
- Rate limiting — per-email tracking. After
max_login_attempts(default: 5) failures, the email is locked out forlogin_lockout_seconds(default: 300). Per-IP rate limiting (max_ip_login_attemptsin[auth]) provides additional protection against credential stuffing across multiple accounts. - Timing safety — login always performs a full Argon2id hash comparison, even for non-existent users, preventing timing-based email enumeration.
- JWT persistence — when no
secretis set incrap.toml, an auto-generated secret is persisted todata/.jwt_secretso tokens survive server restarts. - Account locking — when a user’s
_lockedfield is truthy, all authenticated requests (includingMe) are rejected withunauthenticatedstatus. This takes effect immediately, even for valid unexpired tokens.
Creating Users via gRPC
Include password in the data field of a Create request:
grpcurl -plaintext -d '{
"collection": "users",
"data": {
"email": "new@example.com",
"password": "secret123",
"name": "New User",
"role": "editor"
}
}' localhost:50051 crap.ContentAPI/Create
The password field is extracted, hashed with Argon2id, and stored separately. It never appears in the response.
Updating Passwords
Include password in the data field of an Update request:
grpcurl -plaintext -d '{
"collection": "users",
"id": "abc123",
"data": { "password": "new-password" }
}' localhost:50051 crap.ContentAPI/Update
If password is omitted, the existing password is kept.
Type Safety
The gRPC API uses google.protobuf.Struct for document fields — a generic JSON object with no schema at the proto level. This is a deliberate design choice: Lua files define schemas, the proto stays stable, and the binary never needs recompiling when you add a field.
But Struct means your gRPC client sees fields as an untyped map. This page explains how to get type safety back.
The Two-Layer Architecture
┌──────────────────────────────────────────────────────────┐
│ Lua definitions (source of truth) │
│ collections/posts.lua → fields, types, options │
└──────────┬────────────────┬────────────────┬─────────────┘
│ │ │
┌──────▼──────┐ ┌──────▼──────────┐ ┌──▼─────────────┐
│ Describe- │ │ crap-cms typegen│ │ crap-cms typegen│
│ Collection │ │ client -l X │ │ lua │
│ (runtime, │ │ (build-time) │ │ (build-time) │
│ gRPC) │ │ │ │ │
└──────┬──────┘ └──────┬──────────┘ └──┬─────────────┘
│ │ │
┌──────▼──────┐ ┌──────▼──────────┐ ┌──▼─────────────┐
│ Generic │ │ types/client.X │ │ types/crap.lua │
│ Document │ │ (TS/Go/Py/Rs │ │ types/hooks.lua│
│ message │ │ typed shapes │ │ (IDE types for │
│ │ │ for API clients)│ │ hooks/init.lua)│
└─────────────┘ └─────────────────┘ └────────────────┘
Layer 1: Runtime schema discovery — the DescribeCollection RPC returns the full field schema. gRPC clients call it at startup or build time to generate typed wrappers.
Layer 2: Server-side Lua typegen — crap-cms typegen lua writes types/crap.lua (the crap.* API surface) and types/hooks.lua (per-collection hook/data/doc shapes) with LuaLS annotations. This gives you autocompletion and type checking inside hooks and init.lua. Under admin.dev_mode = true, crap-cms serve regenerates them on every startup.
Layer 3: Client-side consumer typegen — crap-cms typegen client -l <lang> writes types/client.<ext> with typed per-collection shapes for external API consumers (TypeScript, Go, Python, Rust).
DescribeCollection
The DescribeCollection RPC returns the full schema for any collection or global:
grpcurl -plaintext -d '{"slug": "posts"}' \
localhost:50051 crap.ContentAPI/DescribeCollection
Response:
{
"slug": "posts",
"singularLabel": "Post",
"pluralLabel": "Posts",
"timestamps": true,
"fields": [
{
"name": "title",
"type": "text",
"required": true,
"unique": true
},
{
"name": "slug",
"type": "text",
"required": true,
"unique": true
},
{
"name": "status",
"type": "select",
"required": true,
"options": [
{ "label": "Draft", "value": "draft" },
{ "label": "Published", "value": "published" },
{ "label": "Archived", "value": "archived" }
]
},
{
"name": "content",
"type": "richtext"
},
{
"name": "author",
"type": "relationship",
"relationshipCollection": "users",
"relationshipMaxDepth": 1
},
{
"name": "tags",
"type": "relationship",
"relationshipCollection": "tags",
"relationshipHasMany": true
}
]
}
FieldInfo Schema
Each field in the response has:
| Field | Type | Description |
|---|---|---|
name | string | Column name |
type | string | Field type: text, number, select, relationship, etc. |
required | bool | Whether the field is required |
unique | bool | Whether the field has a uniqueness constraint |
options | SelectOptionInfo[] | Options for select fields (label + value) |
relationship_collection | string? | Target collection slug for relationship fields |
relationship_has_many | bool? | Whether it’s a many-to-many relationship |
relationship_max_depth | int? | Per-field population depth cap |
fields | FieldInfo[] | Sub-fields for array and group types (recursive) |
Building Typed Clients
The idea: call DescribeCollection once (at build time or app startup), then generate typed wrappers for your language.
TypeScript Example
Call DescribeCollection for each collection and generate interfaces:
// Generated from DescribeCollection("posts")
interface Post {
id: string;
title: string;
slug: string;
status: "draft" | "published" | "archived";
content?: string;
author?: string; // relationship ID (depth=0)
tags?: string[]; // has_many relationship IDs
created_at?: string;
updated_at?: string;
}
interface CreatePostInput {
title: string; // required
slug: string; // required
status: string; // required
content?: string;
author?: string;
tags?: string[];
}
The mapping from FieldInfo.type to TypeScript types:
function fieldTypeToTS(field: FieldInfo): string {
switch (field.type) {
case "text":
case "textarea":
case "richtext":
case "email":
case "date":
case "slug":
return "string";
case "number":
return "number";
case "checkbox":
return "boolean";
case "json":
return "unknown";
case "select":
return field.options.map(o => `"${o.value}"`).join(" | ");
case "relationship":
return field.relationshipHasMany ? "string[]" : "string";
case "array":
// Recurse into sub-fields
return `Array<{ ${field.fields.map(f =>
`${f.name}${f.required ? '' : '?'}: ${fieldTypeToTS(f)}`
).join('; ')} }>`;
default:
return "unknown";
}
}
A typed wrapper around the gRPC client:
// Wrap the untyped gRPC client with generated types
class PostsClient {
constructor(private client: ContentAPIClient) {}
async find(query?: FindQuery): Promise<{ documents: Post[]; total: number }> {
const resp = await this.client.find({ collection: "posts", ...query });
return {
documents: resp.documents.map(d => ({ id: d.id, ...d.fields } as Post)),
total: resp.total,
};
}
async create(data: CreatePostInput): Promise<Post> {
const resp = await this.client.create({ collection: "posts", data });
return { id: resp.document.id, ...resp.document.fields } as Post;
}
}
Go Example
Same pattern — DescribeCollection at build time, generate structs:
// Generated from DescribeCollection("posts")
type Post struct {
ID string `json:"id"`
Title string `json:"title"`
Slug string `json:"slug"`
Status string `json:"status"`
Content *string `json:"content,omitempty"`
Author *string `json:"author,omitempty"`
CreatedAt *string `json:"created_at,omitempty"`
UpdatedAt *string `json:"updated_at,omitempty"`
}
// Convert a generic Document to a typed Post
func DocumentToPost(doc *crap.Document) Post {
p := Post{ID: doc.Id}
if f := doc.Fields.Fields; f != nil {
if v, ok := f["title"]; ok {
p.Title = v.GetStringValue()
}
// ...
}
return p
}
Python Example
# Generated from DescribeCollection("posts")
from dataclasses import dataclass
from typing import Optional, List
@dataclass
class Post:
id: str
title: str
slug: str
status: str # "draft" | "published" | "archived"
content: Optional[str] = None
author: Optional[str] = None
tags: Optional[List[str]] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
def document_to_post(doc) -> Post:
fields = dict(doc.fields)
return Post(
id=doc.id,
title=fields.get("title", {}).string_value,
slug=fields.get("slug", {}).string_value,
status=fields.get("status", {}).string_value,
content=fields.get("content", {}).string_value or None,
# ...
)
Lua Typegen (for Hooks)
The gRPC type safety story above is for external clients. For Lua hooks and init.lua, the built-in typegen provides IDE-level type safety.
Generate Types
Under admin.dev_mode = true, server-side Lua types are auto-regenerated on every crap-cms serve startup. In production (or to refresh after a binary upgrade), regenerate explicitly:
crap-cms typegen lua
This writes <config_dir>/types/crap.lua (the crap.* API surface, copied from the binary) and <config_dir>/types/hooks.lua (per-collection hook/data/doc shapes derived from your collection definitions) with LuaLS annotations.
For external API consumers (TypeScript, Go, Python, Rust), use the client subcommand:
crap-cms typegen client -l ts,go,py,rs
What Gets Generated
For each collection, typegen emits:
| Type | Purpose |
|---|---|
crap.data.Posts | Input fields (for Create/Update data) |
crap.doc.Posts | Full document (fields + id + timestamps) |
crap.hook.Posts | Typed hook context (collection, operation, data) |
crap.find_result.Posts | Find result (documents[] + total) |
crap.filters.Posts | Filter keys for queries |
crap.query.Posts | Query options (filters, order_by, limit, offset) |
crap.hook_fn.Posts | Hook function signature |
For globals: crap.global_data.*, crap.global_doc.*, crap.hook.global_*.
For array fields: crap.array_row.* with the sub-field types.
Select fields become union types: "draft" | "published" | "archived".
Function overloads are generated so crap.collections.posts.find(...) returns crap.find_result.Posts instead of the generic crap.FindResult.
IDE Setup
Add a .luarc.json in your config directory:
{
"runtime": { "version": "Lua 5.4" },
"workspace": { "library": ["./types"] }
}
LuaLS (used by VS Code, Neovim, etc.) will then provide:
- Autocompletion on all document fields
- Type checking for field values
- Inline errors for typos and type mismatches
- Hover documentation showing field types
- Smart overloads on
crap.collections.find()per collection
Example Generated Output
For a posts collection with title, slug, status (select), content (richtext):
---@class crap.data.Posts
---@field title string
---@field slug string
---@field status "draft" | "published" | "archived"
---@field content? string
---@class crap.doc.Posts
---@field id string
---@field title string
---@field slug string
---@field status "draft" | "published" | "archived"
---@field content? string
---@field created_at? string
---@field updated_at? string
---@class crap.hook.Posts
---@field collection "posts"
---@field operation "create" | "update"
---@field data crap.data.Posts
Why Generic Struct?
The Document.fields is google.protobuf.Struct (not per-collection messages) because:
- Single binary — the proto file is compiled into the binary. Per-collection proto messages would require recompilation when schemas change.
- Lua is the schema source — schemas live in Lua files, not proto definitions. The proto layer is a transport, not a schema system.
- Dynamic schemas — collections can be added, removed, or modified by editing Lua files without touching the binary or proto.
- DescribeCollection fills the gap — runtime schema discovery gives clients everything they need to build typed wrappers, without coupling the proto to specific schemas.
Live Updates
Crap CMS supports real-time event streaming for mutation notifications. When documents are created, updated, or deleted, events are broadcast to connected subscribers.
Technology
- gRPC Server Streaming (
SubscribeRPC) for API consumers - SSE (
GET /admin/events) for the admin UI - Transport: pluggable. Default is in-process (
tokio::sync::broadcast); behind--features redisyou can switch to Redis pub/sub for cross-node fanout — see Multi-Server Deployment.
Configuration
In crap.toml:
[live]
enabled = true # default: true
default_mode = "metadata" # default: "metadata" — global default for all collections
transport = "memory" # default: "memory" — in-process; set to "redis" for multi-node fanout
channel_capacity = 1024 # default: 1024
# max_sse_connections = 1000 # max concurrent SSE connections (0 = unlimited)
# max_subscribe_connections = 1000 # max concurrent gRPC Subscribe streams (0 = unlimited)
# subscriber_send_timeout_ms = 1000 # drop slow subscribers after this many ms (default: 1000)
transport = "redis" uses the same Redis URL as [cache] redis_url (single source of truth). When the binary isn’t built with --features redis, selecting "redis" aborts startup with a clear error.
Set enabled = false to disable live updates entirely. Both SSE and gRPC Subscribe will be unavailable.
Connection limits protect against resource exhaustion. When the limit is reached, new SSE connections receive 503 Service Unavailable and new gRPC Subscribe calls receive UNAVAILABLE status. Existing connections are not affected.
Subscriber lifecycle
Live-update subscribers (gRPC Subscribe or admin SSE) can be terminated by the server in three cases — all surface to the client as a closed stream and require a reconnect:
- Send timeout (SEC-D) — if forwarding an event to a specific subscriber takes longer than
subscriber_send_timeout_ms(default 1000 ms), that subscriber is dropped. Healthy subscribers are unaffected. - Lag drop (SEC-D) — if the broadcast channel overflows for a particular subscriber (it fell behind by more than
channel_capacityevents), that subscriber is dropped on its next read. Previously such subscribers were kept alive with a warning, which masked silent event loss; they are now closed deterministically. - User session revocation (SEC-E) — when a user is locked or hard-deleted via the service layer, every active stream owned by that user is immediately torn down with
PermissionDenied. Anonymous subscribers are unaffected.
Event Delivery Modes
Each collection can control what data events carry:
-
metadata(default) — events carry only metadata: sequence, timestamp, operation, collection, document_id, edited_by. No document data is included. Metadata mode skips the per-subscriberafter_readhooks and field-level read-access stripping on the event payload, because there is no payload to transform. Thebefore_broadcasthook still runs (once per event, pre-dispatch) and the collection’slivefilter function still gates whether the event is broadcast at all. Clients re-fetch viaFindByIDif they need document data. -
full— events carry complete document data, processed throughafter_readhooks and field-level access stripping — the same data aFindorFindByIDcall would return. Opt-in per collection.
Performance note: In full mode, after_read hooks run once per event per subscriber. For collections with expensive hooks and many subscribers, use metadata mode and let clients re-fetch.
Per-Collection Control
-- Broadcast all events in metadata mode (default)
crap.collections.define("posts", { ... })
-- Disable broadcasting entirely
crap.collections.define("audit_log", {
live = false,
...
})
-- Full data mode: events include document data with after_read hooks
crap.collections.define("posts", {
live = { mode = "full" },
...
})
-- Full data mode with a Lua filter function
crap.collections.define("posts", {
live = { mode = "full", filter = "hooks.posts.should_broadcast" },
...
})
-- Lua function decides per-event (metadata mode)
crap.collections.define("posts", {
live = "hooks.posts.should_broadcast",
...
})
The filter function receives { collection, operation, data } and returns true to broadcast or false/nil to suppress.
Access Control
Event streams enforce the same access rules as normal read operations:
| Layer | metadata | full | Description |
|---|---|---|---|
| Collection-level access | ✅ | ✅ | Only collections the subscriber can read |
| Row-level constraints | ✅ | ✅ | Constraint filters evaluated in-memory per event |
after_read hooks | — | ✅ | Data transformed per subscriber (same as Find) |
| Field-level access | — | ✅ | Denied fields stripped per subscriber |
before_broadcast hooks | ✅ | ✅ | Can modify/suppress events before delivery |
Row-level constraints use in-memory evaluation of the same filters that Find uses as SQL WHERE conditions. For example, if a user’s access returns { owner = ctx.user.id }, only events where owner matches are delivered.
Access is snapshotted at subscribe time. Permission changes require reconnect.
Event Structure
| Field | Description | metadata | full |
|---|---|---|---|
sequence | Monotonic sequence number | ✅ | ✅ |
timestamp | ISO 8601 timestamp | ✅ | ✅ |
target | "collection" or "global" | ✅ | ✅ |
operation | "create", "update", "delete" | ✅ | ✅ |
collection | Collection or global slug | ✅ | ✅ |
document_id | Document ID | ✅ | ✅ |
data | Document fields (hook-processed) | empty | ✅ |
edited_by | User who made the change | ✅ | ✅ |
Event Pipeline
Transaction:
before-hooks → DB operation → after-hooks → commit
After commit:
-> publish_event()
1. live setting check (enabled/disabled/function)
2. before_broadcast hooks (can modify/suppress)
3. EventBus.publish()
-> Per subscriber:
a. collection access (cached)
b. row-level constraints (cached, in-memory)
c. mode:
metadata → deliver metadata only
full → after_read hooks → field strip → deliver
Limitations
- Events are ephemeral — missed events are not replayed
- Access is snapshotted at subscribe time — permission changes require reconnect
- No field-level subscription filters
- No event persistence or replay
before_broadcasthooks have no CRUD access (fires after commit)- In
fullmode,after_readhooks run per subscriber — expensive hooks may impact performance at scale
gRPC Subscribe RPC
The Subscribe RPC provides a server-streaming endpoint for real-time mutation events.
Request
message SubscribeRequest {
repeated string collections = 1; // empty = all accessible
repeated string globals = 2; // empty = all accessible
repeated string operations = 3; // "create","update","delete" — empty = all
string token = 4; // auth token from Login RPC
}
Response Stream
message MutationEvent {
uint64 sequence = 1;
string timestamp = 2;
string target = 3; // "collection" or "global"
string operation = 4; // "create", "update", "delete"
string collection = 5;
string document_id = 6;
google.protobuf.Struct data = 7;
}
Usage with grpcurl
# Subscribe to all collections
grpcurl -plaintext -d '{}' localhost:50051 crap.ContentAPI/Subscribe
# Subscribe to specific collections with auth
grpcurl -plaintext -d '{
"collections": ["posts"],
"operations": ["create", "update"],
"token": "your-jwt-token"
}' localhost:50051 crap.ContentAPI/Subscribe
Access Control
- Authentication via
tokenfield (same token asLoginresponse) - Read access is checked at subscribe time for each requested collection/global
- Collections/globals without read access are silently excluded
- Returns
PERMISSION_DENIEDif no collections or globals are accessible - Returns
UNAVAILABLEif live updates are disabled in config
Reconnection
If the stream is interrupted, clients should reconnect. Events missed during disconnection are not replayed. Use the sequence field to detect gaps.
Connection Limits
The maximum number of concurrent Subscribe streams is controlled by max_subscribe_connections in [live] (default: 1000). When the limit is reached, new subscriptions receive UNAVAILABLE status. Set to 0 for unlimited.
Backpressure
The internal broadcast channel has a configurable capacity (default 1024). If a subscriber falls behind, events are dropped and the stream continues from the latest event (logged as a warning on the server).
Admin SSE Endpoint
The admin UI includes a Server-Sent Events (SSE) endpoint for real-time mutation notifications.
Endpoint
GET /admin/events
Protected by admin auth middleware (requires valid session cookie).
Event Format
Events are sent with event type mutation:
event: mutation
id: 42
data: {"sequence":42,"timestamp":"2024-01-15T10:30:00Z","target":"collection","operation":"create","collection":"posts","document_id":"abc123","edited_by":"user_456"}
The data payload is JSON with the same fields as the gRPC MutationEvent, plus an edited_by field containing the user ID of the authenticated user who made the change (or null for unauthenticated operations). The payload’s own data field is always present:
- metadata mode (default):
datais an empty object ({}). - full mode (collection has
live = { mode = "full" }):datacontains the document withafter_readhooks applied and field-level read-access stripping performed per subscriber — the same shape aFindorFindByIDwould return.
Admin UI Integration
The admin UI automatically connects to the SSE endpoint on all authenticated pages. When a mutation event is received, a toast notification is shown via the <crap-toast> component.
The SSE connection:
- Auto-reconnects on disconnection (native
EventSourcebehavior) - Sends keepalive pings every 30 seconds
- Only activates on pages with the admin layout
Access Control
Same as gRPC Subscribe: read access is checked at connection time per collection/global. Events for inaccessible collections are filtered out.
Note: Access control is snapshotted at subscribe time. If a user’s permissions change after they subscribe to the SSE stream (e.g., their role is updated or access rules are modified), they will continue receiving events based on the original permissions until the SSE connection is closed. To force a re-evaluation, the client must reconnect.
Connection Limits
The maximum number of concurrent SSE connections is controlled by max_sse_connections in [live] (default: 1000). When the limit is reached, new connections receive 503 Service Unavailable. Set to 0 for unlimited.
Custom Integration
If you override the admin templates, the SSE listener is in static/components/live-events.js. You can customize or replace it by placing your own static/components/live-events.js in your config dir’s static/ folder.
Live Update Hooks
Execution Order
For every mutation event, the live-update pipeline runs in this strict order — and short-circuits as soon as any step suppresses the event:
livesetting check — iflive = false, the event is dropped immediately. Ifliveis a function reference, it is called as a gate: returningfalse/nildrops the event and preventsbefore_broadcastfrom running at all.before_broadcasthooks — collection-level first, then global registered hooks. Any hook returningfalse/nilsuppresses the event and stops the chain.- EventBus dispatch — the event is delivered to each matching subscriber, with per-subscriber access checks,
after_readhooks (full mode only), and field stripping (full mode only).
The live filter function and before_broadcast hooks both receive a context table with { collection, operation, data } and have similar shapes, but they sit at different stages: live is the cheap gate, before_broadcast is the transformation/suppression stage.
before_broadcast
A lifecycle event that fires after the write transaction has committed, before the event reaches the EventBus. Hooks can suppress events or transform the broadcast data.
Collection-Level
crap.collections.define("posts", {
hooks = {
before_broadcast = { "hooks.posts.filter_broadcast" },
},
})
The hook function receives { collection, operation, data } and returns:
- The context table (possibly with modified
data) to continue broadcasting falseornilto suppress the event entirely
-- hooks/posts.lua
local M = {}
function M.filter_broadcast(ctx)
if ctx.operation == "delete" then return ctx end
if ctx.data.status == "published" then
return ctx -- broadcast
end
return false -- suppress draft changes
end
return M
Registered Hooks
Global registered hooks also fire for before_broadcast:
-- init.lua
crap.hooks.register("before_broadcast", function(ctx)
-- Strip sensitive fields from all broadcast data
ctx.data._password_hash = nil
ctx.data._reset_token = nil
return ctx
end)
Hook Order Within before_broadcast
- Collection-level
before_broadcasthooks (string refs from definition) - Global registered
before_broadcasthooks (crap.hooks.register)
If any hook returns false/nil, the event is suppressed and no further hooks run.
CRUD Access
before_broadcast hooks run after the transaction has committed and do not have CRUD access.
Data Modifications Are Event-Only
Mutating ctx.data inside a before_broadcast hook affects only the broadcast event payload. The stored document is not updated — the hook fires post-commit, after the write transaction has already closed. Use this to redact fields, decorate the broadcast with computed values, or flatten internal structure for subscribers, but reach for before_change / after_change hooks if you actually need the change to land in the database.
live Setting Functions
When live is a string (Lua function reference), the function is called before before_broadcast hooks:
crap.collections.define("posts", {
live = "hooks.posts.should_broadcast",
})
function M.should_broadcast(ctx)
-- Only broadcast published posts
return ctx.data.status == "published"
end
The function receives { collection, operation, data } and returns true/false. This is a fast gate — before_broadcast hooks only run if the live check passes. See Execution Order above.
Admin UI
Crap CMS includes a built-in admin UI served via Axum with Handlebars templates and HTMX. The admin is fully customizable through a filesystem-overlay model — drop a same-named file into your config directory to override any built-in template, stylesheet, or component.
How to customize
The customization surface has four axes — pick the one that matches your goal:
| Goal | Layer | Where to start |
|---|---|---|
| Restyle (colors, spacing, fonts) | CSS tokens | Themes guide, CSS variables reference |
| Tweak a page’s HTML structure | Templates | Template overlay guide, Template context reference |
| Replace or extend a component | Web Components | Components reference |
| Add a custom richtext node (CTA button, mention pill, embed) | Lua | Custom richtext node scenario |
| Add a custom field type (rating, color picker, slug builder) | Lua + HBS + JS | Custom field type scenario |
| Add a custom admin page | Lua + HBS template | Custom admin page scenario |
The customization motion is always the same: drop a file at the
matching path inside your config dir’s static/ or templates/
folder. The admin overlay resolves config-dir paths first, compiled
defaults second.
Scaffolding
Every customization mechanism has a matching crap-cms make
subcommand that drops the right files at the right paths and prints
any registration snippet you need to add to init.lua:
| To create… | Run |
|---|---|
| Custom admin page | crap-cms make page <slug> [--label …] [--section …] [--icon …] |
| Slot widget | crap-cms make slot <slot-name> [--file <filename>] |
| Custom richtext node | crap-cms make node <name> [--inline] |
| Per-field template (rating-style) | crap-cms make field <name> [--base-type number] |
| Theme starter | crap-cms make theme <name> |
| Custom Web Component | crap-cms make component <tag> |
| Collection / global / hook / job | crap-cms make collection | global | hook | job <slug> |
All scaffolds are interactive — omit positional args and the CLI
prompts. Use --force to overwrite existing files.
When to use what
There are seven override mechanisms — pick by what kind of change you’re making, not by what file you happen to be looking at. Most one-off customizations only need one of these.
| To… | Mechanism | Where |
|---|---|---|
| Add content at a defined extension point (extra dashboard widget, extra metadata tag, extra sidebar entry) | slot | drop .hbs files into templates/slots/<name>/ |
| Replace a markup chunk reused in multiple places (logo, meta tags, icon-font link) | partial | drop a same-named file at templates/partials/<name>.hbs |
Replace the brand wordmark / page <title> | config field | set [admin] site_name = "Acme" in crap.toml; rendered via {{crap.site_name}} in templates. (Adding new top-level config fields requires a Rust patch — [admin] is a typed struct.) |
| Replace one field instance’s rendering (rating, color picker, custom widget) | admin.template + admin.extra | declare the per-field path + config in the field’s admin = {…} block; drop the template at the named path |
| Replace a CSS rule or token (brand colors, spacing) | drop CSS | static/styles/themes/themes-<name>.css (or override static/styles/parts/<name>.css) |
| Replace an entire page template (collections list, dashboard) | drop HBS | drop a same-named file at templates/<page>.hbs |
| Replace a built-in Web Component (toast, drawer, …) | drop JS | drop a same-named file at static/components/<name>.js |
| Add behavior to a built-in component without replacing it (audit logging, analytics on toast) | capture-phase event listener | listen for the component’s crap:* event from static/components/custom.js |
Quick rule of thumb:
- Need new content? Slot.
- Editing a single value? Config.
- Editing one field instance’s UI?
admin.templateper-field. - Editing markup? Partial (if it’s a chunk) or full template override (if it’s a page).
- Editing styling? CSS file at the matching path.
- Editing component code? JS file at the matching path — or a capture-phase listener if you’re just tacking behavior on.
The slot system is additive — your slot file runs alongside
upstream’s defaults. Every other mechanism is replacement —
your file completely supersedes upstream’s. Run crap-cms templates status to see when an upstream replacement target has drifted from
the version you forked.
Upgrading from a previous version?
The pre-1.0 layout reshuffle moved several files into role-grouped
subdirectories (static/styles/, static/vendor/, static/icons/,
static/components/_internal/). All old paths still resolve via
compatibility aliases for this release, with a deprecation warning
logged on first hit.
See Migrating from the old layout
for the full path map and an auto-generated migration recipe via
crap-cms templates layout.
Access
Default: http://localhost:3000/admin
Access to the admin panel is controlled by two gates:
require_auth(default:true) — when no auth collection exists, the admin shows a “Setup Required” page (HTTP 503) instead of being open. Setrequire_auth = falsein[admin]for fully open dev mode.access(optional Lua function ref) — checked after successful authentication. Gates which authenticated users can access the admin panel. Returntrueto allow,false/nilto show “Access Denied” (HTTP 403).
[admin]
require_auth = true # block admin if no auth collection (default)
access = "access.admin_panel" # only allow users passing this function
-- access/admin_panel.lua
return function(ctx)
return ctx.user and ctx.user.role == "admin"
end
When auth collections are configured and no access function is set, any authenticated user can access the admin.
Security features:
- Content-Security-Policy header with configurable per-directive source lists (see
[admin.csp]) - CSRF protection on all forms and HTMX requests (double-submit cookie pattern)
Secureflag on session cookies in production (dev_mode = false)- Rate limiting on login (configurable max attempts and lockout duration)
X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy,Permissions-Policyheaders
Technology
- Axum web framework for routing and middleware
- Handlebars templates with partial inheritance
- HTMX for dynamic page updates without JavaScript frameworks
- Plain CSS with custom properties (no preprocessor, no build step)
- Web Components with Shadow DOM (
<crap-toast>,<crap-confirm>)
Routes
| Route | Description |
|---|---|
/health | Liveness check (public) |
/ready | Readiness check (public) |
/admin | Dashboard |
/admin/login | Login page (public) |
/admin/logout | Logout (public) |
/admin/forgot-password | Forgot password page (public) |
/admin/reset-password | Reset password page (public) |
/admin/verify-email | Email verification (public) |
/admin/collections | Collection list |
/admin/collections/{slug} | Collection items list |
/admin/collections/{slug}/create | Create form |
/admin/collections/{slug}/{id} | Edit form |
/admin/collections/{slug}/{id}/delete | Delete confirmation |
/admin/collections/{slug}/{id}/versions | Version history |
/admin/collections/{slug}/{id}/versions/{version_id}/restore | Restore a version |
/admin/collections/{slug}/validate | Inline validation (POST) |
/admin/collections/{slug}/evaluate-conditions | Display condition evaluation (POST) |
/admin/globals/{slug} | Global edit form |
/admin/globals/{slug}/validate | Global inline validation (POST) |
/admin/globals/{slug}/versions | Global version history |
/admin/globals/{slug}/versions/{version_id}/restore | Restore global version |
/admin/events | SSE live update stream |
/admin/api/search/{slug} | Relationship search endpoint |
/admin/api/session-refresh | Session token refresh (POST) |
/admin/api/locale | Save locale preference (POST) |
/admin/api/user-settings/{slug} | Save user settings (POST) |
/api/upload/{slug} | File upload endpoint (POST) |
/mcp | MCP HTTP endpoint (POST, if enabled) |
/static/* | Static assets (public) |
/uploads/{collection_slug}/{filename} | Uploaded files |
Session Refresh Endpoint
POST /admin/api/session-refresh reissues the admin session cookie when the user is about to be logged out by token expiry.
- Triggered by the client. The
<crap-session-guard>web component (static/components/session-guard.js) shows a pre-expiry warning toast and POSTs here when the operator clicks “Stay signed in”. It is not polled on a fixed interval — only fired in response to the warning. - Authentication required. The handler reads
Claimsfrom request extensions (populated by the admin auth middleware), so an unauthenticated request returns401 Unauthorizedbefore any work is done. CSRF is enforced via theX-CSRF-Tokenheader /crap_csrfcookie like the rest of the admin POST routes. - Re-validates the user before reissuing. It checks that the user still exists, is not
_locked, and that the token’ssession_versionmatches the current value in the auth collection (so a password change or session-version bump invalidates older tokens). Any failure returns401; a deleted user can’t silently keep refreshing. - Behavior on success. Issues a fresh JWT, sets
crap_session(and the matching expiry cookie) with the sameSameSite/Secureflags as login, and returns204 No Content. The body is empty — the client treats the new cookie as the success signal. - No explicit rate limit. The endpoint is not separately rate-limited, but it requires a valid existing session (so it can’t be abused unauthenticated) and the cost is one DB read plus a JWT sign.
Versioning & Drafts Workflow
For collections with versions = { drafts = true }, the admin UI provides a draft/publish workflow:
List view:
- Shows all documents (both draft and published) with status badges
- A “Status” column displays
publishedordraftper row
Create form:
- Publish (primary button) — creates as published, enforces required field validation
- Save as Draft (secondary button) — creates as draft, skips required field validation
Edit form:
- Draft document: “Publish” (primary) + “Save Draft” (secondary) buttons
- Published document: “Update” (primary) + “Save Draft” (secondary) + “Unpublish” (ghost) buttons
- Draft saves create a version snapshot only — the main (published) document is not modified until you publish
Sidebar:
- Status badge showing current document status
- Version history panel listing recent versions with version number, status, date, and a “Restore” button
- Restoring a version writes the snapshot data back to the main table and creates a new version entry
Collections without versions configured work exactly as before — a single “Create” or “Update” button with no status management.
See Versions & Drafts for the full configuration and behavioral reference.
CSS Architecture
- Custom properties in
:root(colors, spacing, fonts, shadows) - Separate files per concern:
layout.css,buttons.css,cards.css,forms.css,tables.css - Composed via
@importinstyles.css - BEM-ish naming (
.block,.block__element,.block--modifier) - Geist font family (variable weight)
JavaScript
- No build step, no npm, no bundler — browser-native ES modules
static/components/index.jsentry point loaded with<script type="module">- Each feature is a separate module under
static/components/(individually overridable) - JSDoc annotations for all types
- Web Components (Shadow DOM, CSS variables for theming) — see
Web Components for the full reference, including
the singleton discovery contract, the
crap:changeform-field event, thewindow.crapnamespace, and the override pattern. The library ships ~30 components:<crap-toast>,<crap-confirm>,<crap-confirm-dialog>,<crap-richtext>,<crap-code>,<crap-tags>,<crap-array-field>,<crap-validate-form>, …
Scenario 1: Corporate restyle
Goal: replace the default admin colors, fonts, and spacing with your brand.
Difficulty: low. ~15 minutes from scratch to a working theme.
You’ll touch: CSS only. No templates, no Rust, no Lua.
Approach
Crap CMS exposes its entire visual system as CSS custom
properties in
static/styles/tokens.css.
Themes are CSS files that override a subset of these tokens on
html[data-theme="..."] selectors — every component reading the
variables automatically participates in theming.
You’ll create a theme file with your brand tokens, register it in the imports chain, and (optionally) add a picker entry so users can switch into it.
Step 1 — drop your theme file
Create <config_dir>/static/styles/themes/themes-acme.css:
html[data-theme="acme"] {
color-scheme: light;
/* Brand colors */
--color-primary: #ff5500;
--color-primary-hover: #ff7733;
--color-primary-active: #d94800;
--color-primary-bg: rgba(255, 85, 0, 0.08);
/* Optional — keep danger/success/warning untouched, or restyle */
--color-danger: #d62828;
/* Optional — adjust shadows for your brand vibe */
--shadow-md: 0 4px 12px rgba(255, 85, 0, 0.10);
/* Optional — your font stack */
--font-family: "Inter", system-ui, -apple-system, sans-serif;
}
Only override the tokens you actually want to change — every other
value falls back to the default in tokens.css.
See CSS variables reference for the full token catalogue.
Step 2 — register the theme in the import chain
Override the entry stylesheet to include your theme. Drop
<config_dir>/static/styles/main.css (extracted from upstream, then
add your theme at the end):
$ crap-cms templates extract styles/main.css
Edit the extracted file and add your theme as the last import
(themes load after default.css so they can override its tokens):
/* <config_dir>/static/styles/main.css */
@import url("/static/styles/tokens.css");
@import url("/static/styles/base/normalize.css");
@import url("/static/styles/base/fonts.css");
@import url("/static/styles/base/reset.css");
@import url("/static/styles/layout/layout.css");
@import url("/static/styles/layout/edit-sidebar.css");
@import url("/static/styles/parts/cards.css");
@import url("/static/styles/parts/forms.css");
@import url("/static/styles/parts/buttons.css");
@import url("/static/styles/parts/lists.css");
@import url("/static/styles/parts/tables.css");
@import url("/static/styles/parts/breadcrumb.css");
@import url("/static/styles/parts/badges.css");
@import url("/static/styles/parts/pagination.css");
@import url("/static/styles/themes/default.css");
@import url("/static/styles/themes/themes-acme.css"); /* ← your theme */
Step 3 — activate the theme
The admin’s theme picker reads from localStorage’s crap-theme
key. Set it once in the browser console:
localStorage.setItem('crap-theme', 'acme');
location.reload();
Or reach in via the admin’s theme enhancer:
window.crap.theme.set('acme');
The <html data-theme="acme"> attribute toggles, your theme’s
custom properties take effect, and every component re-renders with
your colors.
Step 4 (optional) — set as the default
To make acme the default for new visitors (instead of light),
override the theme bootstrap script that runs in <head> before
paint. Drop <config_dir>/templates/layout/base.hbs (extracted from
upstream) and change the bootstrap line:
<script nonce="{{crap.csp_nonce}}">
(function(){
var t = localStorage.getItem('crap-theme') || 'acme';
document.documentElement.setAttribute('data-theme', t);
})();
</script>
Step 5 (optional) — also rebrand the wordmark + logo
You’ve covered colors and fonts. To finish the rebrand, see:
- Site name —
[admin] site_name = "Acme CMS"incrap.toml. - Logo partial
— drop your SVG at
templates/partials/logo.hbs. - Theme color meta tag — drop a custom
templates/partials/meta-tags.hbswith yourtheme-color.
Verifying
$ crap-cms templates status
should show your override files as · user-original (no upstream counterpart) — they’re new files, not extracted-and-edited copies
of upstream — and any extracted files (like main.css) as
✓ current while you’re on the same release.
After upgrading crap-cms, run templates status again — your theme
file stays user-original, but main.css may show behind if
upstream added a new @import. Use templates diff styles/main.css
to see what to add.
Scenario 2: Add a column to the collection list page
Goal: add a “Word count” column to the posts collection’s
list view, computed from each post’s body field.
Difficulty: medium. Two files to touch: a template overlay and optionally a Lua hook (if the value isn’t already in the document).
You’ll touch: templates/collections/items_table.hbs,
templates/collections/items_row.hbs, optionally a
before_render hook.
Approach
The list view renders rows via items_row.hbs with column cells in
the order specified by items_table.hbs’s header. To add a column,
override both partials and add a <th> / <td> pair. The cell
content can pull from any field in the document — or from a value
you compute in a before_render hook and stash on the page context.
Step 1 — extract the table + row templates
$ crap-cms templates extract collections/items_table.hbs collections/items_row.hbs
This drops both files into your config dir with source-version
headers so templates status tracks drift later.
Step 2 — add the column
Open <config_dir>/templates/collections/items_table.hbs and add a
header cell to the <thead>:
<thead>
<tr>
{{!-- existing cells --}}
<th>Word count</th>
</tr>
</thead>
Open <config_dir>/templates/collections/items_row.hbs and add a
matching cell:
{{!-- existing cells --}}
<td>{{this.word_count}}</td>
That’s it for the markup. The remaining question is where
{{this.word_count}} comes from.
Step 3 — provide the data
Two options depending on how the word count is stored:
Option A — already a field on the collection
If posts has a word_count field (e.g., updated by a before_change
hook on save), the value is already in the row data. The template
renders it directly — nothing more to do. This is the cleanest
approach: the count is also queryable, sortable, and filterable.
-- <config_dir>/init.lua — keep word_count fresh on every save.
crap.hooks.register("before_change", function(ctx)
if ctx.collection ~= "posts" then return ctx end
if ctx.operation ~= "create" and ctx.operation ~= "update" then return ctx end
local body = ctx.input.body or ""
ctx.input.word_count = select(2, string.gsub(body, "%S+", ""))
return ctx
end)
Pair this with a word_count integer field in the posts
collection schema. Existing documents need a one-off migration to
backfill the column for rows saved before the hook landed.
Option B — computed at render time
If you don’t want a schema field — say, the count is too cheap to
denormalize, or you want to keep the schema clean — compute it in
a before_render hook:
-- <config_dir>/init.lua
crap.hooks.register("before_render", function(ctx)
if not ctx.collection or ctx.collection.slug ~= "posts" then
return ctx
end
if not ctx.items then
return ctx
end
for _, doc in ipairs(ctx.items) do
doc.word_count = select(2, string.gsub(doc.body or "", "%S+", ""))
end
return ctx
end)
Notes:
before_renderis global — fires for every admin page render. Filter by what’s in the context (ctx.collection,ctx.items, etc.) to no-op for pages your hook doesn’t apply to.ctxis the page context directly — there’s noctx.templatefield; identify the page by which keys exist (ctx.itemsis set on collection list pages) plus their values.- Mutate or return — Lua tables are pass-by-reference, so
mutating
ctx.items[i].word_countis enough. Returningctxexplicitly is conventional and harmless. - Cost — the hook runs in the request path. For 50 rows × a word-count regex, this is a sub-millisecond cost. For more expensive enrichments, prefer Option A.
Step 4 — restart (or rely on dev mode)
If you’re running with [admin] dev_mode = true, the templates are
reloaded per-request — refresh /admin/collections/posts and the
new column appears.
If dev_mode = false, restart crap-cms.
Step 5 — make the column show by default
The list view respects user-saved column selections. By default,
crap-cms shows all columns; users can hide some via the column
picker. To make word_count part of the default selection, look at
the list-settings handler
for how default columns are computed — you may need to register
word_count as a known column.
What this scenario doesn’t cover
- Sorting by the new column — that requires the column to be a real DB field, not a hook-computed value.
- Filtering by the new column — same.
- Editing the value — same. If you want round-trip editing, add a real field to the collection schema and skip the hook.
For one-off display columns (counts, derived values, indicators), the hook-then-render pattern is the cleanest. For first-class columns, add a schema field.
Verifying
$ crap-cms templates status
✓ templates/collections/items_table.hbs — current
✓ templates/collections/items_row.hbs — current
Both your overrides are tracked. After upgrading crap-cms, if
upstream renames or restructures these templates, templates status
will flag them as behind — run templates diff collections/items_row.hbs to see what to re-port.
Scenario 3: Replace the toast component
Goal: change how <crap-toast> looks or behaves — different
animation, different layout, audit logging, etc.
Difficulty: depends on goal. Adding behavior is one line in
custom.js (5 minutes). Replacing the rendering entirely is a fork
of static/components/toast.js (~30 minutes plus ongoing
maintenance).
You’ll touch: static/components/custom.js (for behavior add),
or static/components/toast.js (for full replacement).
Approach
There are three paths, each suited to a different goal:
-
Add behavior — listen for the public event, do your thing, let the original component continue. Strictly additive. Inherits all upstream improvements automatically. This is the recommended path for ~95% of “I want X to happen when toast shows” goals.
-
Replace rendering — drop your own
toast.js. Your version completely supersedes upstream. You inherit no upstream improvements until you re-port them. Use when you want full control over the markup and animation. -
Override CSS only — drop
toast.js-specific CSS variables in your theme. Use when you only want to tweak the visual.
Path 1 — add behavior via capture-phase listener
Goal example: log every toast to a backend audit endpoint.
Drop a single file in your config dir:
// <config_dir>/static/components/custom.js
document.addEventListener('crap:toast-request', (e) => {
fetch('/api/audit/toast', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: e.detail.message,
type: e.detail.type ?? 'info',
timestamp: Date.now(),
}),
});
// Don't stop propagation — upstream's <crap-toast> still gets the
// event and shows the toast normally. Your listener runs alongside.
}, true /* capture phase */);
custom.js is auto-imported from index.js if it exists in your
overlay. No registration needed.
This is strictly additive — you didn’t replace the toast component, so upstream improvements (animation tweaks, queue fixes, accessibility updates) flow through automatically.
See events reference for the full list of public events you can listen to this way.
Path 2 — full replacement
Goal example: replace the toast UI with a wholly different design (e.g., a banner at the top instead of corner toasts).
$ crap-cms templates extract components/toast.js
This copies the embedded toast.js into your config dir at
<config_dir>/static/components/toast.js with a source-version
header.
Edit the file freely. Your version completely replaces upstream’s. Some constraints:
-
Keep the tag name
crap-toast— built-in code dispatchescrap:toast-requestevents expecting<crap-toast>to be registered (HTMX response headers likeX-Crap-Toastalso flow through it). -
Listen for the same public event (
crap:toast-request) so built-in calls keep working. Import the constant fromevents.jsrather than re-typing the string:import { EV_TOAST_REQUEST } from './events.js'; -
Register the tag at the bottom of the file, mirroring how upstream’s
toast.jsdoes it:customElements.define('crap-toast', YourToastClass);No defensive
if (!customElements.get(...))guard is needed for a full overlay replacement — the overlay handler serves your file when the URL is/static/components/toast.js, so upstream’s registration code never runs.
After overriding, crap-cms templates status will show:
static/components/toast.js ✓ current
…until you upgrade crap-cms. After upgrade:
static/components/toast.js ⚠ behind: extracted from 0.1.0-alpha.8
Run crap-cms templates diff components/toast.js to see what
upstream changed and re-port the bits that matter.
Path 3 — CSS-only override
If you only want to tweak the visual (colors, spacing, fonts) without changing behavior, override the CSS tokens. Toast inherits from the same theme tokens as the rest of the admin:
/* <config_dir>/static/styles/themes/themes-acme.css */
html[data-theme="acme"] {
/* These tokens flow into toast's constructable stylesheet via
`var(--…)` references — change them and toast picks them up. */
--color-primary: #ff5500;
--color-primary-bg: rgba(255, 85, 0, 0.08);
--color-success: #2ea043;
--color-danger: #d62828;
/* Spacing + radius cascade to toast as well */
--space-md: 0.5rem;
--radius-md: 0; /* square corners */
}
See CSS variables reference for the full token catalogue and Themes guide for the registration pattern.
Note: Built-in components don’t currently expose CSS
::part()selectors — there are nopart="…"attributes on the internal Shadow-DOM elements yet. Theming via CSS custom properties is the only token-level external customization path today. For finer structural control, fall through to Path 2.
Choosing between paths
| Goal | Path |
|---|---|
| Audit logging on every toast | Path 1 (listener) |
| Send toast events to analytics | Path 1 |
| Block certain toast messages | Path 1 (with e.stopPropagation() in your handler) |
| Change the toast colors / spacing / radius | Path 3 (theme tokens) |
| Change the toast animation timing or motion | Path 2 (the timing is internal to toast.js) |
| Change the toast layout (banner vs. corner) | Path 2 |
| Change the toast icon set | Path 2 (icons are inline in toast’s render) |
| Show toasts as native browser notifications | Path 1 — call Notification.requestPermission() and new Notification(e.detail.message) |
Most “I want X to happen” goals are Path 1. Reach for Path 2 only when you’re willing to take on the maintenance burden of a fork.
Verifying
$ crap-cms templates status
For Path 1, custom.js shows as · user-original — no drift to
track.
For Path 2, toast.js shows as ✓ current initially, then
⚠ behind after upgrade. That’s your signal to run templates diff and re-port.
Scenario 4: Dashboard widget that fetches a 3rd-party API
Goal: add a card to the admin dashboard that displays current weather (or any external API value) for ops awareness.
Difficulty: medium. Two files: a slot template + a
crap.template_data registration in init.lua.
You’ll touch: templates/slots/dashboard_widgets/<name>.hbs,
init.lua.
Approach
The dashboard’s dashboard/index.hbs declares a dashboard_widgets
slot:
{{slot "dashboard_widgets"}}
Drop a .hbs file into the slot directory and it renders alongside
any other contributions. To pull in dynamic data, register a
template-data function via crap.template_data.register and call
it from your slot template with {{data "name"}}. The function
runs on demand — only when the slot template references it, so
pages that don’t show the widget pay no cost.
This is the same pattern the custom page scenario uses for live counts.
Step 1 — drop the slot file
{{!-- <config_dir>/templates/slots/dashboard_widgets/weather.hbs --}}
<div class="card">
<div class="card__header">
<span class="material-symbols-outlined">cloud</span>
<h3>Weather</h3>
</div>
<div class="card__body">
{{#with (data "weather_now")}}
<p class="metric">{{temp}}°C, {{condition}}</p>
<p class="muted">{{location}} — updated {{updated_at}}</p>
{{else}}
<p class="muted">Weather data unavailable.</p>
{{/with}}
</div>
</div>
The filename inside slots/dashboard_widgets/ doesn’t matter for
routing — anything .hbs renders. The filename only controls
render order (alphabetical), so prefix with NN- if you need
to control where your card appears among other widgets.
Step 2 — register the template-data function
Add to <config_dir>/init.lua:
crap.template_data.register("weather_now", function(ctx)
-- ctx is the page render context (read-only here, just for context).
-- Return a table; the template binds it via {{#with (data "weather_now")}}.
local api_key = crap.env.get("CRAP_WEATHER_API_KEY")
if not api_key then
crap.log.warn("weather_now: CRAP_WEATHER_API_KEY not set")
return nil -- {{#with}} {{else}} branch handles missing data
end
local response = crap.http.request({
method = "GET",
url = "https://api.weather.example/current?location=berlin",
headers = { ["Authorization"] = "Bearer " .. api_key },
timeout = 5000, -- ms
})
if response.status ~= 200 then
crap.log.warn(string.format(
"weather_now: API returned status %d", response.status
))
return nil
end
local data = crap.json.decode(response.body)
return {
temp = data.temperature,
condition = data.condition,
location = data.location,
updated_at = os.date("%H:%M"),
}
end)
Notes on the registration:
crap.template_data.register("name", fn)—nameis what the template uses in{{data "name"}}. The fn runs on demand.fn(ctx)— the page render context (ctx.user,ctx.nav,ctx.crap.site_name, etc.). Read-only by convention; this isn’t the place to mutate page-wide state.- Return a table —
{{#with (data "weather_now")}}binds it. Returningnilmakes{{#with}}fall to its{{else}}branch. crap.env.get(key)— read-only env access restricted toCRAP_*andLUA_*prefixed vars (returnsnilfor any other key). So your env var must be namedCRAP_WEATHER_API_KEY, notWEATHER_API_KEY.crap.http.request(opts)— single options table withmethod,url,headers,body,timeout. Returns a table withstatus,headers,body. SSRF protections are on by default (private-IP requests blocked unless explicitly allowed).crap.json.decode(s)— parse a JSON string into a Lua table.crap.log.warn(msg)/crap.log.info(msg)— structured logging. Output appears in the crap-cms server log alongside Rust log entries.
Step 3 — restart
Lua loads at startup. Restart crap-cms to pick up your new
init.lua registration:
$ pkill -f 'crap-cms serve' && cargo run -- --config /path/to/config serve
Templates reload per request in dev_mode = true, but Lua
registrations are evaluated once at startup. There’s no
file-watcher.
Step 4 — verify
Open /admin. The card renders alongside any other dashboard
widgets:
┌──────────────────────────────────────┐
│ Welcome back, alice@example.com │
└──────────────────────────────────────┘
┌─────────────────┐ ┌──────────────────┐
│ Weather │ │ Recent activity │
│ 18°C, Cloudy │ │ ... │
│ Berlin — 14:32 │ └──────────────────┘
└─────────────────┘
If the API is down or the env var is missing, the {{else}}
branch renders Weather data unavailable. instead — no error
page.
Caching the API response
crap.template_data doesn’t ship a built-in cache. The function
runs on each render. For a 3rd-party API you don’t want to hit on
every request, two options:
Option A — module-level Lua cache. Cache the result in a Lua upvalue with a TTL:
do
local cached_value, cached_at = nil, 0
local TTL_SECONDS = 600 -- 10 minutes
crap.template_data.register("weather_now", function(ctx)
local now = os.time()
if cached_value and (now - cached_at) < TTL_SECONDS then
return cached_value
end
-- ... fetch as in Step 2 ...
local fresh = { temp = ..., condition = ..., ... }
cached_value = fresh
cached_at = now
return fresh
end)
end
This works well for low-traffic admin pages. The cache is per-Lua-VM (crap-cms uses a small VM pool), so the API is hit once per VM per TTL window.
Option B — push the cache to the API call. Some upstream APIs
support cache headers; if the source is your own service, put a
cache layer in front of it (Varnish, Redis, CloudFront). Then your
template-data function calls a fast cached endpoint and
crap.template_data doesn’t need to cache itself.
For most admin-dashboard widgets, Option A is overkill — admin traffic is low. Skip caching unless you measure a problem.
What this scenario doesn’t cover
-
Auto-refresh in the browser — the page renders server-side. For a card that updates without a full reload, use HTMX:
<div hx-get="/admin/p/widgets/weather" hx-trigger="every 600s" hx-swap="innerHTML"> {{#with (data "weather_now")}}...{{/with}} </div>This requires a separate custom page at
/admin/p/widgets/weatherthat returns just the inner HTML. See Scenario 5. -
Per-user widgets — the slot renders for everyone. Filter inside the slot template using
{{user.role}}if you want role-gated widgets.
Verifying
$ crap-cms templates status
· templates/slots/dashboard_widgets/weather.hbs — user-original (no upstream counterpart)
· init.lua — user-original (no upstream counterpart)
Slot files are user-original by definition (no upstream counterpart
since they’re additive). They never drift; templates status just
confirms they exist.
Scenario 5: Add a custom admin page
Goal: add a “System info” page to the admin showing live process metrics, with its own URL, sidebar entry, and admin-only access.
Difficulty: low. ~15 minutes from scratch to a working page.
You’ll touch: one HBS template, one init.lua block,
optionally one access function.
Approach
Crap CMS has filesystem-routed custom pages. Drop a template at
<config_dir>/templates/pages/<slug>.hbs and the route
/admin/p/<slug> renders it automatically. Optionally call
crap.pages.register("<slug>", { ... }) in init.lua to add a
sidebar entry, restrict access, and set the page label / icon.
For dynamic data on the page, use the same crap.template_data.register
{{data "name"}}pattern as dashboard widgets — no separate “page data” mechanism.
Step 1 — drop the template
<config_dir>/templates/pages/system_info.hbs:
{{#> layout/base}}
<h1>System info</h1>
<div class="cards">
<div class="card">
<div class="card__header">
<span class="material-symbols-outlined">info</span>
<h3>Build</h3>
</div>
<div class="card__body">
<p><strong>Version:</strong> {{crap.version}}</p>
<p><strong>Build hash:</strong> <code>{{crap.build_hash}}</code></p>
<p><strong>Dev mode:</strong> {{#if crap.dev_mode}}on{{else}}off{{/if}}</p>
</div>
</div>
{{#with (data "system_info_counts")}}
<div class="card">
<div class="card__header">
<span class="material-symbols-outlined">database</span>
<h3>Counts</h3>
</div>
<div class="card__body">
<p><strong>Collections:</strong> {{collections}}</p>
<p><strong>Globals:</strong> {{globals}}</p>
<p><strong>Custom pages:</strong> {{custom_pages}}</p>
</div>
</div>
{{/with}}
</div>
{{/layout/base}}
The template wraps layout/base (the standard admin chrome) and
uses three pieces of context:
crap.*— process metadata (version, build hash, dev mode, site name, etc.). See template context reference.{{data "system_info_counts"}}— pulls from a Lua function registered below. The data fn runs on demand — only when the template references it.- Standard HBS —
{{#if}},{{#with}}, etc.
The page is now reachable at /admin/p/system_info. Without a Lua
registration, it just doesn’t appear in the sidebar — direct URL
access works.
Step 2 — register the sidebar entry
Add to <config_dir>/init.lua:
crap.pages.register("system_info", {
section = "Tools", -- sidebar section heading; nil = ungrouped
label = "System info", -- sidebar label; nil = no nav entry
icon = "monitoring", -- Material Symbols icon name
access = "access.admin_only", -- optional access function ref
})
The slug must match the template filename (without .hbs).
Slugs are restricted to a-z, 0-9, -, _ — anything else is
rejected at registration time.
| Field | Required? | Effect |
|---|---|---|
section | no | Sidebar section heading. nil → renders ungrouped at the bottom. |
label | no | Sidebar label. nil → page routes but isn’t shown in nav. |
icon | no | Material Symbols icon name (e.g. "monitoring", "heart-pulse"). |
access | no | Lua function-ref (registered via crap.access.register). Returning false produces a 403 and hides the page from sidebar nav. |
Step 3 — provide the dynamic counts
In <config_dir>/init.lua:
crap.template_data.register("system_info_counts", function(ctx)
local nav = ctx.nav or {}
return {
collections = nav.collections and #nav.collections or 0,
globals = nav.globals and #nav.globals or 0,
custom_pages = nav.custom_pages and #nav.custom_pages or 0,
}
end)
The ctx argument is the page render context — ctx.user,
ctx.nav, ctx.crap, etc. are all available. The function returns
a table; that table is what {{#with (data "system_info_counts")}}
binds in the template.
The function runs on demand — only when a rendering template
evaluates the {{data}} call. Pages that don’t reference it pay no
cost.
Step 4 (optional) — restrict to admins
If you set access = "access.admin_only" above, define the access
function. Conventional layout: a single function per file under
<config_dir>/access/, then required in init.lua. But you can
also register inline.
Either way, register via crap.access.register:
-- <config_dir>/access/admin_only.lua
---@param context crap.AccessContext
---@return boolean
return function(context)
return context.user ~= nil and context.user.role == "admin"
end
-- <config_dir>/init.lua
crap.access.register("access.admin_only", require("access.admin_only"))
If the function returns false for the current user, the route
returns 403 and the sidebar entry is filtered out (so non-admins
don’t see a link they can’t follow).
Step 5 — restart
Lua loads at startup. Restart crap-cms (or kill and re-run serve).
Open /admin — your “System info” entry appears in the “Tools”
section of the sidebar. Click it; the page renders at
/admin/p/system_info.
What this scenario covers
- ✅ A new admin URL (
/admin/p/<slug>) - ✅ A sidebar entry with section, label, icon
- ✅ Per-page access control via Lua function
- ✅ Dynamic data via
crap.template_data.register - ✅ Full admin chrome (header, sidebar, theme switcher, all of it)
What this scenario doesn’t cover
- Custom POST endpoints / form actions — pages render
read-only. For mutations, drive them through gRPC or via a
collection’s standard CRUD routes; there’s no
/admin/p/<slug>/submitpattern. (See the gRPC API for write paths from custom JS.) - Streaming / SSE / live updates per page — the page renders
server-side. Use
<crap-live-events>or HTMX swaps for dynamic content within the page.
Verifying
$ crap-cms templates status
· templates/pages/system_info.hbs — user-original (no upstream counterpart)
· init.lua — user-original (no upstream counterpart)
· access/admin_only.lua — user-original (no upstream counterpart)
Custom pages and Lua files are user-original by definition (no
upstream counterpart). They never drift; templates status just
confirms they exist.
The shipped example/init.lua in the repo has this exact pattern
working — see example/init.lua
and example/templates/pages/system_info.hbs
for the live reference.
Scenario 6: Add a custom richtext node
Goal: add a new richtext node type (e.g., a “Call to Action”
button or an @mention pill) that authors can insert inside any
richtext field in any collection.
Difficulty: medium. ~30 minutes from scratch to a working custom node, with admin UI, validation, and HTML rendering.
You’ll touch: init.lua only — no new files, no Rust, no JS.
Or run crap-cms make node <name> to scaffold the registration
file.
Looking to add a top-level custom field type (e.g. a rating column on a collection, with stars in the admin and integer storage)? See Scenario 7: Add a custom field type. That scenario covers per-field render templates via
admin.template+admin.extra— first-class shipped support.
Approach
Crap CMS lets you register custom richtext nodes from Lua via
crap.richtext.register_node. A node is a typed insertion point
inside the richtext document tree:
- Block-level (
inline = false) — a full block, like a hero card or a CTA button row. - Inline (
inline = true) — sits inside a paragraph, like an@mentionpill or a custom badge.
Each node carries its own typed attributes (text, number, select, date, etc.), full admin UI editing, validation, and a Lua render function that turns the node into HTML for output.
The example/init.lua shipped in the repo defines two real custom
nodes — a CTA button and an @mention pill — that you can copy as
a starting template.
Step 1 — register the node
Add to <config_dir>/init.lua:
-- Block-level: Call to Action button
crap.richtext.register_node("cta", {
label = "Call to Action",
inline = false,
attrs = {
crap.fields.text({
name = "text",
required = true,
min_length = 2,
max_length = 80,
admin = {
label = "Button Text",
description = "The visible text on the button",
},
}),
crap.fields.text({
name = "url",
required = true,
admin = { label = "URL", placeholder = "https://..." },
}),
crap.fields.select({
name = "style",
admin = { label = "Style" },
options = {
{ label = "Primary", value = "primary" },
{ label = "Secondary", value = "secondary" },
{ label = "Outline", value = "outline" },
},
}),
crap.fields.number({
name = "padding",
min = 0,
max = 100,
admin = { label = "Padding (px)", step = "1", width = "50%" },
}),
},
searchable_attrs = { "text" },
render = function(attrs)
local style = ""
if attrs.padding and attrs.padding ~= "" then
style = string.format(' style="padding: %spx 0"', tostring(attrs.padding))
end
return string.format(
'<a href="%s" class="btn btn--%s"%s>%s</a>',
attrs.url or "#",
attrs.style or "primary",
style,
attrs.text or ""
)
end,
})
What each spec field does:
| Field | Required | Effect |
|---|---|---|
label | no | Display name in the richtext block picker. Defaults to the node name. |
inline | no | true for inline nodes (mentions, badges); false (default) for block-level. |
attrs | no | Array of typed attributes via crap.fields.text/number/select/date/email/json/code/textarea/radio/checkbox. Restricted to scalar types — no nested arrays/blocks. |
searchable_attrs | no | Names of attrs whose values get indexed for full-text search. Must reference real attr names. |
render | no | Lua function (attrs) -> string that turns the node into HTML. Return any HTML you want; remember to escape user input. If omitted, the node falls through to the <crap-node> passthrough instead of returning HTML directly. |
Two ways to render custom-node output
Custom richtext nodes have two output paths, and there’s no HBS-template equivalent — node output is programmatic.
Path A — Lua render function (server-side HTML)
Provide a render = function(attrs) ... end in the spec. When the
admin (or anything else) calls crap.richtext.render(content), your
function fires for every node of that type and its return value is
spliced into the HTML output. This is the path used by the CTA
example above.
Best for:
- Pages that render the full HTML server-side (Markdown blogs, static sites, server-rendered pages backed by crap-cms).
- Cases where you want the
<a class="btn">(or whatever) to appear directly in the served HTML.
Path B — <crap-node> passthrough (client-side rendering)
Omit render entirely. The renderer emits a placeholder element
instead:
<crap-node data-type="cta" data-attrs='{"text":"Sign up","url":"/signup",...}'></crap-node>
Your downstream consumer (a Web Component, a JS framework, a JSX
component, an iOS app reading the JSON) picks up the
<crap-node data-type="..."> element and renders it however it
wants. The attrs are JSON-encoded into the data-attrs attribute.
Best for:
- Single-page apps and React/Vue/Svelte frontends where the richtext is rendered by a frontend component, not the server.
- Cases where the render is environment-specific (different markup on iOS vs. web, dark mode adjustments at view time, A/B-tested variants, etc.).
- Mixed deployments: server-render the framing, let the client decide how to render the richtext nodes.
You can register a node with just attrs — admin-UI editing
works fully (the form is auto-generated from the attrs spec), and
the consuming side handles rendering:
crap.richtext.register_node("cta", {
label = "Call to Action",
attrs = {
crap.fields.text({ name = "text", required = true }),
crap.fields.text({ name = "url", required = true }),
crap.fields.select({ name = "style", options = { ... } }),
},
-- No render fn — output will be a <crap-node> passthrough.
})
What renders without a render function
When the renderer encounters a custom node and no render is
registered for it, output looks like:
<crap-node
data-type="cta"
data-attrs='{"text":"Sign up","url":"/signup","style":"primary"}'
></crap-node>
The consumer is responsible for transforming these elements into
final HTML. The data-attrs is HTML-escaped JSON of the node’s
attribute values.
Why no HBS template path
Crap-cms doesn’t ship an HBS template renderer for custom richtext
nodes. The two paths above (Lua function + JSON passthrough) cover
both server-side and client-side rendering needs without
introducing a third mechanism. If you specifically want HBS,
you can call back into Handlebars from your Lua render function
— but in practice the Lua string.format / table.concat style
shown in the CTA example is sufficient for node-level HTML.
Admin form rendering
The admin’s in-document editing form (the modal that pops up when
you insert or edit a node) is auto-generated from the attrs
spec. There’s no per-node admin template to override; the form
is built dynamically by <crap-richtext> from the attr definitions.
This is by design — node attrs are restricted to scalar types
(text, number, select, etc.), so the auto-generated form is always
a flat collection of standard <crap-*> field components. The
consistency means every custom node gets the same UX as the
built-in nodes.
If you need a wholly different admin UI for a node (e.g., a custom
visual picker, drag-and-drop sub-editor, etc.), you’d need to fork
<crap-richtext> itself. For most “extra typed data on a
content node” cases, the auto-form is exactly what you want.
Step 2 — restart
Lua loads at startup. Restart crap-cms.
Step 3 — use it
Open any collection with a richtext field (e.g., posts.body).
Click the block-picker + button — your “Call to Action” entry
appears alongside the built-in nodes (paragraph, heading,
blockquote, etc.). Insert one; the admin renders an editable form
for text, url, style, padding based on the attrs you
declared.
When the document is rendered (server-side, via the richtext field’s
{{render}} helper), your render function fires for every CTA
node and returns the HTML you specified.
Inline nodes
For inline content (mentions, badges, custom small widgets), set
inline = true:
crap.richtext.register_node("mention", {
label = "Mention",
inline = true,
attrs = {
crap.fields.text({ name = "name", required = true, admin = { label = "Name" } }),
crap.fields.text({ name = "user_id", admin = { label = "User ID" } }),
},
searchable_attrs = { "name" },
render = function(attrs)
return string.format('<span class="mention">@%s</span>', attrs.name or "?")
end,
})
Inline nodes appear in the inline-formatting toolbar (next to bold, italic, link) instead of the block picker.
What you can build with this
The block-shape is general enough to cover most “custom data with admin UI inside a document” needs:
| Use case | Shape |
|---|---|
| Hero / banner | block-level node with text + image-URL + alignment select |
| Embed (YouTube, Twitter) | block-level node with url text attr; render emits the embed iframe |
| Pull quote | block-level node with quote textarea + author text |
| Footnote | inline node with note textarea |
| Mention | inline node with user_id lookup |
| Glossary term | inline node with term text + definition textarea |
| CTA / button | (the example above) |
| Code playground | block-level node with lang select + code code attr |
The render function gives you total control over output HTML, so
you can wrap nodes in any markup your site theme needs.
Limitations
These are real today:
- Attr types restricted to scalars. Allowed:
text,number,textarea,select,radio,checkbox,date,email,json,code. Not allowed: nestedarray, nestedblocks,relationship. (Usejsonif you need a structured blob.) - No live preview of the rendered HTML. The admin shows the attr-editing form; the rendered output is what end-users see on the public site. Test renders happen server-side at content fetch time.
searchable_attrsmust be top-level scalars. You can’t search into a nested JSON attr.
Verifying
$ crap-cms templates status
· init.lua — user-original (no upstream counterpart)
Custom-node registrations live entirely in init.lua. They’re
user-original and never drift.
The shipped example has the CTA + mention nodes working — see
example/init.lua
for the live reference.
Scenario 7: Add a custom field type
Goal: add a “rating” field to a collection — a 1–5 integer
backed by a custom star-picker UI in the admin, while keeping the
data sortable, filterable, and stored as a real INTEGER column.
Difficulty: medium. ~20 minutes from scratch using the scaffold; maybe an hour by hand. Three coordinated files.
You’ll touch: a Lua plugin file, an HBS template, and a Web
Component — or run crap-cms make field <name> to generate all
three at once.
Approach
Crap CMS lets any field instance opt out of its type’s default
render template by declaring admin.template = "fields/<name>" on
the field, plus optional per-field config via admin.extra. The
field stays storage-typed as the underlying built-in (number,
text, select, …) — SQL schema, validation, sorting, filtering
all flow through the built-in type — but the admin form renders a
custom widget you control.
The pattern is three coordinated files:
- A Lua plugin that wraps the built-in field type with the
per-field
admin.templateandadmin.extrabaked in, so collection schemas just callrating.field({ name = "..." }). - A per-field HBS template at
<config_dir>/templates/fields/<name>.hbsthat renders your widget inside the standardpartials/fieldchrome. - A Web Component at
<config_dir>/static/components/<tag>.jsthat drives the actual UI (clickable stars, color picker, drag handle, etc.).
Step 1 — scaffold (recommended)
Run the make field command:
$ crap-cms make field rating --base-type number
+ Created /path/to/config/templates/fields/rating.hbs
+ Created /path/to/config/plugins/rating.lua
+ Created /path/to/config/static/components/crap-rating.js
+ Created field 'rating' — three files wired together via admin.template.
Use it in a collection:
local rating = require("plugins.rating")
crap.collections.define("products", {
fields = {
rating.field({ name = "my_rating" }),
...
},
})
This generates skeletons of all three files, pre-wired so they work together. The Web Component is a form-associated custom element — its value participates in native form submission and validation without any hidden-input shim.
Step 2 — register the Web Component
The scaffold prints a one-line import to add to your custom.js:
// <config_dir>/static/components/custom.js
import './crap-rating.js';
custom.js is auto-imported from index.js on every admin page, so
your component registers once at boot.
Step 3 — use it in a collection
-- <config_dir>/init.lua
local rating = require("plugins.rating")
crap.collections.define("products", {
fields = {
crap.fields.text({ name = "name", required = true }),
rating.field({
name = "rating",
required = true,
admin = {
extra = { color = "amber" }, -- override per-instance
},
}),
},
})
rating.field({ ... }) is just crap.fields.number({ min=1, max=5, admin.template="fields/rating", admin.extra={...}, ... }) with
sensible defaults — the wrapper is a few lines of Lua you can edit
freely.
Step 4 — flesh out the Web Component
The scaffold writes a placeholder render. Replace the body of
_render() with your real UI. For a star picker:
// <config_dir>/static/components/crap-rating.js
class CrapRating extends HTMLElement {
static formAssociated = true;
static observedAttributes = ['value'];
constructor() {
super();
this._internals = this.attachInternals();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this._render();
}
attributeChangedCallback() {
this._internals.setFormValue(this.value || '');
this._render();
}
get value() { return this.getAttribute('value') ?? ''; }
set value(v) { this.setAttribute('value', String(v)); }
_render() {
const max = Number(this.dataset.max ?? 5);
const current = Number(this.value || 0);
const color = this.dataset.color || 'amber';
this.shadowRoot.innerHTML = `
<style>
:host { display: inline-flex; gap: 0.125rem; }
button { background: none; border: none; cursor: pointer;
font-size: 1.5rem; color: var(--text-tertiary); }
button[data-on] { color: var(--color-${color}, gold); }
</style>
${Array.from({ length: max }, (_, i) => {
const filled = i < current;
return `<button type="button" data-i="${i + 1}" ${filled ? 'data-on' : ''}>★</button>`;
}).join('')}
`;
for (const btn of this.shadowRoot.querySelectorAll('button')) {
btn.addEventListener('click', () => {
this.value = btn.dataset.i;
this.dispatchEvent(new Event('crap:change', { bubbles: true, composed: true }));
});
}
}
}
if (!customElements.get('crap-rating')) {
customElements.define('crap-rating', CrapRating);
}
crap:change is the public event that
<crap-dirty-form> listens for to mark the form as having unsaved
changes — fire it on every value change.
Step 5 — restart and verify
Lua loads at startup. Restart crap-cms (or rely on dev-mode template reload for the HBS).
Open /admin/collections/products/create. The rating field
renders as five clickable stars; clicking one updates the form
value; the standard label/required/error chrome wraps the widget.
crap-cms templates status reports your three new files as
· user-original:
$ crap-cms templates status
· plugins/rating.lua — user-original (no upstream counterpart)
· static/components/crap-rating.js — user-original (no upstream counterpart)
· templates/fields/rating.hbs — user-original (no upstream counterpart)
How this stays robust
- Per-instance template binding.
admin.template = "fields/rating"opts only this field out offields/<type>lookup inRenderFieldHelper. Every othernumberfield keeps using the built-infields/number.hbs. No global template override, no field-name matching. admin.extrais freeform per-field config. Passcolor,icon,max_stars, anything JSON-serializable — your template reads it as{{extra.<key>}}. Same template + component reused across fields with different settings without forking.- Storage stays correct. A rating field is still a
number; the SQL column isINTEGER;min/maxvalidation works; sorting and filtering use the integer value natively. Only the admin rendering is custom. - Path safety.
admin.templatepaths are validated at field-parse time — only[a-zA-Z0-9/_-]allowed, no.., no absolute paths, no empty segments. A bad path is rejected at startup with a clear error. - Deeply nested fields work. The same per-field binding flows
through array rows, group sub-fields, and tab panels —
enrichment preserves
templateandextraregardless of nesting depth (regression-tested).
What this scenario doesn’t cover
A rating field built this way is still a number underneath. If
you specifically need:
- A new SQL column type distinct from
INTEGER/TEXT/ etc. (e.g. a custom enum stored with bespoke encoding), - Custom validation rules at the field-type level (not workable as
a
before_changehook on the collection), - The field type to ship as part of a published collection schema that other crap-cms instances must accept,
…then you need a top-level FieldType variant — a Rust change.
Lua-registered top-level field types are a tracked roadmap item
beyond the per-field-template mechanism above.
For 95% of “I want a custom widget for this kind of value” goals
(ratings, color pickers, slug builders, spinners, audio-trim
controls, …) the three-file pattern above is enough. The shipped
example has the rating field working — see
example/plugins/rating.lua,
example/templates/fields/rating.hbs,
and example/static/components/crap-stars.js.
When to use richtext nodes instead
If your custom data shape lives inside content (an article body with embedded CTAs, mentions, callouts) rather than as a top-level column on the collection, see Scenario 6: Add a custom richtext node. Richtext nodes share the typed- attrs + Web-Component pattern but are scoped to richtext field content rather than row-level columns.
Scenario 7: Upgrade crap-cms — what breaks?
Goal: upgrade crap-cms to a new release; understand what your overrides need re-porting and what changed in the embedded defaults.
Difficulty: low, with the right tooling. ~5 minutes for a clean upgrade with a handful of overrides.
You’ll touch: nothing structural — this is a tooling-driven inspection workflow.
The upgrade workflow
# 1. Bump the binary (release-pinned: cargo, distro pkg, container, etc.).
$ cargo install crap-cms --version 0.1.0-alpha.9
# 2. Inspect drift — what overlays of yours are now behind upstream?
$ crap-cms templates status
# 3. For each flagged file, see exactly what upstream changed:
$ crap-cms templates diff templates/layout/base.hbs
# 4. Re-port: extract a fresh copy, then merge your edits in.
$ crap-cms templates extract --force layout/base.hbs
# 5. Verify nothing else regressed:
$ crap-cms templates status
That’s the loop. Most upgrades won’t flag anything — your override extracted from version 0.1.0-alpha.5 and the upstream is still 0.1.0-alpha.5 for that particular file means no drift.
What templates status tells you
| State | Icon | Meaning | Action |
|---|---|---|---|
| Current | ✓ | Header version matches running. | None. |
| Pristine | = | Matches upstream byte-for-byte. | None — you extracted but never edited. |
| Behind | ⚠ | Header version older than running. | Run templates diff to see upstream changes. Decide whether to re-port. |
| Ahead | ↑ | Header version newer than running. | Downgrade scenario — your override targets a future version. Update your environment or revert. |
| NoHeader | ? | No source-version header. | Hand-written or stripped. No drift visibility — git is your only tool. |
| UnknownVersion | ? | Source-version header present but unparseable as semver. | Repair the header (or re-extract). |
| OrphanedUpstream | ✗ | File claims to extend an upstream that’s gone. | Upstream renamed or removed the file. Your override is now dead — delete or migrate. |
| UserOriginal | · | No upstream counterpart. | Custom widget, bespoke theme, etc. Always reported informationally. |
See drift tooling reference for deeper detail.
Common upgrade patterns
Pattern A — drift on a template you edited
$ crap-cms templates status
⚠ templates/layout/base.hbs — behind: extracted from 0.1.0-alpha.5
$ crap-cms templates diff templates/layout/base.hbs
--- upstream/templates/layout/base.hbs
+++ /path/to/config/templates/layout/base.hbs
@@ ... @@
- <link href="/static/styles.css" rel="stylesheet" />
+ <link href="/static/styles/main.css" rel="stylesheet" />
Upstream renamed styles.css → styles/main.css. The
compatibility-alias layer keeps your overlay working today, but
you’ll see deprecation warnings in the logs. To clear them:
$ crap-cms templates extract --force layout/base.hbs
Then re-apply your customizations (sed, manual diff, or a side-by-side editor) onto the freshly extracted copy. Keep the new source-version header so future drift detection works.
Pattern B — orphaned override
$ crap-cms templates status
✗ templates/old/my-widget.hbs — orphaned: extracted from upstream but no longer exists there
Upstream deleted or renamed the template. Your override is referencing nothing. Two options:
- Delete the override — if you don’t need the custom rendering anymore.
- Migrate to the new path — find where upstream moved the
template (changelog,
templates list) and rename your override to match.
Pattern C — old layout (pre-1.0)
$ crap-cms templates layout
Old layout detected (3 files):
static/list-toolbar.css → static/styles/parts/lists.css
...
You’re on the pre-1.0 reshuffle layout. Aliases serve your old
paths transparently for this release, with deprecation warnings on
first hit. To clear the warnings, follow the auto-generated
migration recipe printed by templates layout.
See Migrating from the old layout for the full path map and recipe.
Pattern D — context-key removal
A subtle case: your overlay template references a context key that
upstream removed. templates status reports the file as behind
but templates diff only shows the version-header change — the
silent breakage is in your template’s {{some.removed.key}}
which now renders empty.
The fix: read the template-context reference for the page you’re overriding. Every page’s typed context is documented; if a key disappeared, you’ll see it isn’t listed.
A future crap-cms doctor command will scan your overlays for
references to removed context keys and flag them. Until then,
manual review against the template-context reference is the
defense.
Releases that broke things
The pre-1.0 reshuffle (this release) is the largest layout change
crap-cms has done. From 1.0 onwards, breakage of this magnitude is
governed by the stability tiers:
stable modules get a deprecation cycle; experimental modules
can break in any minor; internal modules can break without
warning.
Subscribe to the crap-cms GitHub releases to see the changelog
under each release’s “Public surface” heading — that’s where
breaking changes get announced.
Tooling gaps to be aware of
- No automatic re-porter.
templates extract --forceoverwrites your edits with the new upstream. You re-apply your customizations manually. This is intentional — automatic merging silently breaks edge cases that only surface at runtime on pages you don’t routinely test. Manual is honest. - No deep-import scanner yet. If your overlay JS file
imports an upstream helper that was renamed, the only error is a 404 in the browser console. The plannedcrap-cms doctorcommand will scan for these. Until then, exercise the admin in dev-mode after every upgrade and watch the console. - No auto-rebuild trigger. After dropping or editing a file, the next request reads it (in dev mode) or restart picks it up (in production). No file-watcher.
Verifying an upgrade went clean
After re-porting all behind and orphaned overrides:
$ crap-cms templates status
Templates customization status (config dir: ./crap, running version: 0.1.0-alpha.9)
✓ static/styles/themes/themes-acme.css — current
✓ templates/layout/base.hbs — current
· templates/slots/dashboard_widgets/weather.hbs — user-original (no upstream counterpart)
· static/components/custom.js — user-original (no upstream counterpart)
Summary: 2 current, 0 behind, 0 ahead, 0 pristine, 0 unknown header, 0 no header, 0 orphaned, 2 user-original
Zero behind, zero orphaned, zero unknown header. Restart, run
your manual smoke test, ship.
Slots
Slots are named extension points in built-in templates where you can drop your own content without overriding the surrounding template. Where partials let you replace a markup chunk, slots let you add to one.
{{!-- Built-in template declares a slot --}}
{{slot "dashboard_widgets"}}
{{!-- You drop a file at the matching path --}}
{{!-- <config_dir>/templates/slots/dashboard_widgets/weather.hbs --}}
<crap-card>
<h3>Weather</h3>
<p>{{temp}}°C</p>
</crap-card>
That’s the entire mechanism. Drop a file under
templates/slots/<slot_name>/<anything>.hbs; it renders at the
matching {{slot "..."}} site in the upstream template, alongside
any other contributions to the same slot.
How slot rendering works
When a built-in template hits {{slot "name"}}, the helper:
- Enumerates every registered template name starting with
slots/name/(both upstream defaults and your overlay files). - Sorts them alphabetically.
- Renders each against the current page context.
- Concatenates the output and writes it at the slot site.
If no slot files exist for that name, the helper renders nothing — or, if the slot was declared in block form, the inline fallback.
File naming
The filename inside slots/<slot_name>/ doesn’t matter for routing
— anything with a .hbs extension renders. The filename only
controls render order (alphabetical).
Use the filename to namespace your contributions and control order:
templates/slots/dashboard_widgets/
10-weather.hbs # renders first
20-recent-activity.hbs # renders second
90-system-status.hbs # renders last
A common convention is NN-<purpose>.hbs where NN is a two-digit
ordinal — leaves room for inserting future slots without renaming.
Page context
Slot files render with the same template context as the page they
appear in. If you drop a file at
slots/page_header_actions/admin-status.hbs, it has access to
everything the surrounding header.hbs sees: {{user.email}},
{{nav.collections}}, {{crap.site_name}}, and so on.
Reach past any hash-param overlay (see below) via {{@root.x}}:
{{!-- slot file with hash params merged on top --}}
{{name}} {{!-- hash param --}}
{{@root.user.email}} {{!-- always the page-level data --}}
Hash params (per-invocation data)
Slots can pass per-invocation data the slot file sees at the root:
{{!-- Built-in template invokes the slot with hash params --}}
{{slot "field_help" name=field.name kind=field.field_type}}
{{!-- slot file sees the values at the root --}}
{{!-- slots/field_help/long-text-hint.hbs --}}
{{#if (eq kind "richtext")}}
<p class="form__help">Use <kbd>Ctrl+B</kbd> for bold.</p>
{{/if}}
Hash params are useful for slots that fire once per item (e.g. once per field, once per collection row) and need the item’s data without traversing the page context.
Block form (inline fallback)
A built-in template can declare a slot with an inline fallback that renders only when no slot files exist:
{{#slot "dashboard_widgets"}}
<p class="muted">No widgets configured yet.</p>
{{/slot}}
If you drop any file at slots/dashboard_widgets/, the fallback is
suppressed and your file(s) render instead.
Built-in slots
These slots are declared in the built-in templates. Each one is a public extension surface — its name and context are part of the stable API.
| Slot | Declared in | Context | Use for |
|---|---|---|---|
head_extras | layout/base.hbs | full page context | extra <meta> tags, OG tags, robots directives, PWA <link rel="manifest">, custom <link rel="preconnect">, analytics <script> |
body_end_scripts | layout/base.hbs | full page context | end-of-body analytics, custom event listeners, third-party scripts that should load after the admin |
page_header_actions | layout/header.hbs | full page context | extra buttons in the top header bar (next to the logout button) |
dashboard_widgets | dashboard/index.hbs | dashboard context | custom dashboard cards (recent activity, system status, weather, queue depth, …) |
collection_edit_toolbar | collections/edit_form.hbs | edit-form context (document, collection, user) | extra toolbar actions on collection edit pages (e.g., a “Preview” button) |
collection_edit_sidebar | collections/edit_sidebar.hbs | edit-form context | extra sidebar panels on collection edit pages (related items, audit log, custom metadata) |
sidebar_bottom | layout/sidebar.hbs | nav context | extra navigation links pinned to the bottom of the left sidebar |
login_extras | auth/login.hbs | minimal auth context | additional content on the login page (compliance notices, SSO links, banner messages) |
Worked example — dashboard weather widget
Goal: add a weather card to the admin dashboard that shows the current temperature.
Step 1: drop a slot file at the matching path. Use
{{data "name"}} to pull dynamic values from a Lua function
registered below:
{{!-- <config_dir>/templates/slots/dashboard_widgets/weather.hbs --}}
<div class="card">
<div class="card__header">
<span class="material-symbols-outlined">cloud</span>
<h3>Weather</h3>
</div>
<div class="card__body">
{{#with (data "weather_now")}}
<p class="metric">{{temp}}°C, {{condition}}</p>
<p class="muted">{{location}} — updated {{updated_at}}</p>
{{else}}
<p class="muted">Weather data unavailable.</p>
{{/with}}
</div>
</div>
Step 2: register the data function in init.lua:
-- <config_dir>/init.lua
crap.template_data.register("weather_now", function(ctx)
-- ctx is the page render context. Return a table; {{#with (data ...)}}
-- binds it. Return nil to fall through to the {{else}} branch.
return {
temp = 22,
condition = "Sunny",
location = "Berlin",
updated_at = os.date("%H:%M"),
}
end)
The function runs on demand — only when a page actually evaluates
{{data "weather_now"}}. Pages without your widget pay no cost.
Step 3: restart crap-cms (Lua loads at startup). Open
/admin — the card renders alongside any other dashboard widgets.
For the full version with crap.http.request, env-var-keyed API
auth, error handling, and caching, see
Scenario 4: Dashboard widget.
Adding a slot to a custom template
If you’ve overridden a built-in template (<config_dir>/templates/foo.hbs),
you can declare your own slots in it:
{{!-- your overridden template --}}
<div class="my-page">
{{slot "my_page_extras" page="my-page"}}
</div>
Anyone (including future-you) can extend the page by dropping a file
at slots/my_page_extras/<anything>.hbs. The hash param page is
visible inside slot files as {{page}} for context-sensitive output.
When NOT to use a slot
- Replacing a single value (site name, theme color) — use a
config field with
{{crap.foo}}rendering. - Replacing markup (the logo SVG, the meta-tags block) — use a
partial drop at
templates/partials/<name>.hbs. - Replacing a whole page template — drop the file at
templates/<page>.hbs.
Slots are specifically for additive insertions at named extension points. Reaching for one when you really want a replacement leads to contortions; reaching for a replacement when you want to add content alongside upstream’s defaults forces you to maintain a fork. See the admin UI overview for the full mechanism matrix.
Partials
Partials are named, reusable chunks of HBS markup included from
other templates via the {{> name}} syntax. They form one of the
admin UI’s three customization mechanisms — use a partial when you
want to replace a markup chunk that’s reused in multiple places
(logo, breadcrumb, status badge), without touching every template
that includes it.
{{!-- A built-in template includes a partial --}}
<div class="header__logo">
{{> partials/logo class="header__logo-icon"}}
{{crap.site_name}}
</div>
{{!-- You override the partial by dropping the same path in your config dir --}}
{{!-- <config_dir>/templates/partials/logo.hbs --}}
<svg class="{{class}}" viewBox="0 0 24 24">
<path d="M ... your brand mark ..." />
</svg>
That’s it — the override applies to every template that includes the partial.
How partial overrides work
Partials register under a name derived from their relative path in
templates/. So templates/partials/logo.hbs registers as
partials/logo. When the loader walks your config dir, files at the
same path register under the same name and win over the embedded
default.
{{> partials/logo class="..."}} then resolves to your file
everywhere it’s invoked. No need to override the surrounding pages
(header.hbs, auth.hbs, etc.) — the include is the seam.
Partial parameters
Partials take parameters via the {{> name key=value}} syntax. Inside
the partial, parameters are available at the root context:
{{!-- caller --}}
{{> partials/htmx-nav-link href="/admin/users" label_key="users" variant="primary" icon="people"}}
{{!-- partials/htmx-nav-link.hbs --}}
<a
class="button button--{{variant}}"
href="{{href}}"
hx-get="{{href}}"
hx-target="body"
hx-push-url="true"
>
{{#if icon}}<span class="material-symbols-outlined">{{icon}}</span>{{/if}}
{{t label_key}}
</a>
Keep parameters narrow and well-named. The partial’s parameter contract is what overlay authors will code against — changing a parameter name breaks every overlay that depends on it.
Block-form partials
Partials can accept a body via the {{#> name}}body content{{/name}}
syntax. Useful when the partial is a wrapper around content the
caller provides:
{{!-- caller --}}
{{#> partials/warning-card title_key="delete_has_references"}}
<p>3 incoming references prevent deletion.</p>
<a href="{{back_refs_url}}">View references</a>
{{/partials/warning-card}}
{{!-- partials/warning-card.hbs --}}
<div class="card card--warning">
<strong>{{t title_key}}</strong>
{{> @partial-block}} {{!-- caller's body renders here --}}
</div>
Block-form partials are how the admin’s partials/field.hbs wrapper
adds the label/error/help chrome around every field-type’s input
markup.
Built-in partials
| Partial | Used for |
|---|---|
partials/logo.hbs | Brand SVG. Caller passes class. |
partials/meta-tags.hbs | <head> metadata: charset, viewport, theme-color, favicon link. |
partials/icon-font.hbs | Material Symbols stylesheet <link>. Override for self-hosting / privacy. |
partials/field.hbs | Block-form wrapper around field inputs (label, required indicator, error, help). |
partials/breadcrumb.hbs | Page breadcrumb trail. |
partials/pagination.hbs | List-view next/previous controls. |
partials/status-badge.hbs | Document status pill (published, draft, etc.). Caller passes status. |
partials/loading-indicator.hbs | HTMX request indicator. Caller passes variant (inline or sidebar). |
partials/array-row-header.hbs | Drag-handle / move / duplicate / remove buttons for array-field rows. Caller passes expanded, has_errors. |
partials/error-page.hbs | Error-page chrome (used by errors/404.hbs, etc.). |
partials/form-actions.hbs | Save/Publish/Cancel button row at the bottom of edit forms. |
partials/htmx-nav-link.hbs | Anchor with hx-* attributes for client-side nav. |
partials/sidebar-panel.hbs | Collapsible sidebar panel wrapper (used by version history, back-refs). |
partials/version-sidebar.hbs | Version-history sidebar contents. |
partials/version-table.hbs | Version-history table on the standalone versions page. |
partials/warning-card.hbs | Block-form <div class="card card--warning"> wrapper. |
Worked example — swap the brand logo
Goal: replace the heart-in-house mark with your company’s wordmark.
Step 1: drop your SVG into the config dir at the partial’s path:
{{!-- <config_dir>/templates/partials/logo.hbs --}}
<svg
class="{{class}}"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 24"
fill="currentColor"
>
<text x="0" y="18" font-size="20" font-weight="700">ACME</text>
</svg>
Step 2: that’s it. The wordmark renders in both the header
(header.hbs includes it via {{> partials/logo class="header__logo-icon"}})
and the auth-card icon (auth.hbs includes it via
{{> partials/logo class="auth-card__icon"}}).
The {{class}} parameter is preserved so the SVG inherits the right
size / colour from the calling template’s CSS.
Worked example — self-host Material Symbols for privacy
Goal: don’t load the icon font from Google Fonts (privacy / GDPR compliance / air-gapped deployments).
Step 1: vendor the woff2 file (download from https://fonts.gstatic.com) and a CSS file that points at it:
<config_dir>/static/vendor/material-symbols.css
<config_dir>/static/vendor/material-symbols.woff2
Step 2: override the icon-font partial to load your local copy:
{{!-- <config_dir>/templates/partials/icon-font.hbs --}}
<link
rel="stylesheet"
href="/static/vendor/material-symbols.css"
/>
Step 3: that’s it. Both layouts (base.hbs and auth.hbs) load
your local stylesheet instead of Google’s CDN.
When NOT to use a partial
- Adding content at a defined extension point — use a slot. Slots are additive; partials are replacement.
- Replacing a single value — use a config field.
{{crap.site_name}}is a config field, not a partial. - Replacing a whole page template — just drop the page file at
templates/<page>.hbs. No partial wrapper needed.
Partials are specifically for structured markup chunks reused in multiple places. Reaching for one when you really want additive content (slot) or a single value (config) leads to over-coupling. See the admin UI overview for the full mechanism matrix.
Drift detection
Partials are part of the overlay drift surface. After overriding,
crap-cms templates status will show your file with a source-version
header (if extracted via templates extract) or a no source header
note (if hand-written). When upstream renames or restructures a
partial in a future release, templates status flags it so you can
re-port. See Drift tooling.
Template Overlay
The admin UI uses a template overlay system: templates in your config directory override the compiled defaults.
How It Works
When rendering a template, Crap CMS checks:
- Config directory —
<config_dir>/templates/<name>.hbs - Compiled defaults — built into the binary at compile time
If a file exists in the config directory, it’s used. Otherwise, the compiled default is used.
Dev Mode
When admin.dev_mode = true in crap.toml, templates are reloaded from disk on every request. This enables live editing without restarting.
When dev_mode = false, templates are cached after first load (production mode).
Template Errors in Dev Mode
If an operator-provided template in <config_dir>/templates/ has a Handlebars syntax error while admin.dev_mode = true, the request returns a 500 Internal Server Error. Crap CMS does not automatically fall back to the compiled default template — once a file shadows a default, the override is authoritative.
To recover:
- Fix the syntax error in your overlay template, or
- Delete (or rename) the file from
<config_dir>/templates/to fall back to the compiled default.
For deployments, prefer dev_mode = false so the overlay is registered and cached on startup rather than re-parsed (and potentially 500-ing) on every request.
Template Inheritance
Templates use Handlebars partial inheritance:
{{#> layout/base}}
<h1>My Custom Page</h1>
<p>Content here</p>
{{/layout/base}}
The layout/base partial provides the HTML shell (head, sidebar, header).
Field Partials
Each field type has a partial in templates/fields/:
fields/text.hbsfields/number.hbsfields/textarea.hbsfields/richtext.hbsfields/select.hbsfields/checkbox.hbsfields/date.hbsfields/email.hbsfields/json.hbsfields/relationship.hbsfields/array.hbsfields/blocks.hbsfields/password.hbsfields/radio.hbsfields/code.hbsfields/upload.hbsfields/join.hbsfields/group.hbsfields/collapsible.hbsfields/tabs.hbsfields/row.hbs
The edit form iterates field definitions and renders the matching partial.
Overriding Templates
To customize a template, create the same file path under your config directory’s templates/ folder:
my-project/
└── templates/
└── fields/
└── richtext.hbs # overrides the default richtext field template
Available Template Variables
Templates receive context data from the Axum handlers. Common variables include:
collection— collection definitiondocument— document data (edit forms)docs— document list (list views)fields— field definitionsglobal— global definition (global edit pages)user— authenticated user (if auth is configured)
Static Files
Static files (CSS, JS, fonts, images) use the same overlay pattern as templates.
Overlay Pattern
- Config directory —
<config_dir>/static/is served viatower_http::ServeDir - Compiled defaults — built into the binary via
include_dir!macro
If a file exists in both locations, the config directory version wins.
Accessing Static Files
All static files are served under /static/:
<link rel="stylesheet" href="/static/styles/main.css">
<script type="module" src="/static/components/index.js"></script>
Layout
static/
components/ # Web Components — public ones flat, plumbing in _internal/
_internal/ # framework-reserved: h.js, css.js, util/, …
_defaults/ # parallel route — always serves embedded upstream
custom.js # auto-imported user seam (optional)
toast.js drawer.js … # public components
richtext/ list-settings/
styles/
main.css # entry — @imports the rest
tokens.css # design tokens
base/ # normalize, fonts, reset
parts/ # buttons, cards, forms, …
layout/ # page chrome
themes/ # default + user themes-<name>.css
vendor/ # bundled htmx, codemirror, prosemirror
icons/ # SVGs
fonts/ # font files
Overriding Static Files
Place files in your config directory’s static/ folder:
my-project/
└── static/
└── styles/
└── themes/
└── themes-acme.css # served at /static/styles/themes/themes-acme.css
To override a built-in file, use the same path:
my-project/
└── static/
├── styles/main.css # overrides the compiled-in entry stylesheet
└── components/toast.js # overrides just the toast component
Compiled-In Files
Default static files are compiled into the binary using the include_dir! macro. This means:
- The binary is self-contained — no external files needed for the default admin UI
- After modifying compiled-in static files, you must run
cargo buildfor changes to take effect - Config directory overrides don’t require rebuilding
Vendored Vendor Libraries
Three third-party JavaScript libraries are vendored into static/ rather
than loaded from a CDN:
| File | Source | Bundler script |
|---|---|---|
static/vendor/htmx.js | htmx.org | scripts/bundle-htmx.sh |
static/vendor/prosemirror.js | prosemirror.net | scripts/bundle-prosemirror.sh |
static/vendor/codemirror.js | codemirror.net | scripts/bundle-codemirror.sh |
Each script downloads its inputs, performs any bundling needed, verifies
a pinned hash (htmx) or commits the build output (codemirror,
prosemirror), and writes the artifact into static/. Re-run only when
upgrading; the produced files are committed to git.
Why vendor instead of CDN?
- One trust boundary: every script the admin loads is
'self'. CSPscript-srcdoesn’t need to whitelist any third party. - One DNS resolution at page load instead of per-CDN.
- Reproducible deploys: the bytes that ran in CI are the bytes that
ship in the binary (via
include_dir!). - No external availability dependency at runtime.
Overlay authors who need a different htmx/prosemirror/codemirror
version can drop a replacement at the same path
(<config_dir>/static/vendor/htmx.js) — the overlay always wins.
MIME Types
Content-Type headers are automatically detected from file extensions using the mime_guess crate.
Cache model
Every static response carries:
Cache-Control: public, no-cache— the browser may cache the response, but must revalidate with the server on every subsequent request before reusing the cached copy. (Despite the name,no-cacheis not “don’t cache” — that would beno-store.)ETag— embedded files useBUILD_HASH(a content-derived hash baked at compile time, recomputed on everycargo build); config-dir files use theServeDir-default mtime/size token.
Each subsequent request sends If-None-Match: <previous-etag>; the
server replies 304 Not Modified (no body) when the ETag still matches,
or 200 with the new content when it doesn’t. Browsers reuse the
cached body in the 304 case, so the network cost is just the
conditional-GET round-trip — no asset re-download.
This model intentionally prioritises overlay-author DX over a few hundred bytes of revalidation traffic:
- Production deploy —
cargo buildchangesBUILD_HASH, every embedded file’s ETag changes, the next page load gets fresh content. Config-dir files keep their unchanged mtime ETags and stay 304s. - Config-dir edit — overlay author saves a file in
<config_dir>/static/, mtime changes,ServeDirETag changes, the next request returns the new content. No restart, no rebuild required.
Why no ?v=BUILD_HASH query string
You may have seen <script src="…?v={{crap.build_hash}}"> in older
admin templates. We dropped it: with the ETag-based revalidation above,
it didn’t actually change anything. ES-module imports inside the
JavaScript files (import './toast.js') and CSS @import url("…")
statements don’t carry the query string anyway, so they always
revalidate via ETag — and that’s exactly what we want, because adding
?v=… to a long-cached versioned URL would defeat the overlay model
(the new URL would never invalidate when an overlay author edits
<config_dir>/static/foo.js).
If your CDN or reverse proxy rewrites Cache-Control: no-cache to
something more aggressive (some old corporate proxies do), you’ll need
to either configure the proxy to honour the directive or strip it from
intermediate caches with a Vary / Surrogate-Control rule appropriate
to your stack.
Technical Note
The embedded fallback handler uses axum::http::Uri extraction (not axum::extract::Path) because it runs as a ServeDir fallback service where no route parameters are defined.
Themes
The admin UI includes built-in theme support with multiple color schemes.
Built-In Themes
| Theme | Type | Description |
|---|---|---|
| Light | light | Default theme. Clean blue-accented light design. |
| Rosé Pine Dawn | light | Warm, muted light theme based on the Rosé Pine palette. |
| Tokyo Night | dark | Cool blue-purple dark theme. |
| Catppuccin Mocha | dark | Pastel-accented dark theme from the Catppuccin palette. |
| Gruvbox Dark | dark | Warm retro dark theme with orange accents. |
Switching Themes
Click the palette icon in the admin header to open the theme picker. The selected theme is persisted in localStorage and restored on page load (no flash of unstyled content).
How Themes Work
The default Light theme is defined in :root CSS custom properties in styles.css. Additional themes live in themes.css and override these variables using html[data-theme="<name>"] selectors.
Theme values are static CSS. Every theme’s custom-property values are hardcoded in CSS files — either the built-in
themes.cssor an operator-supplied stylesheet under<config_dir>/static/. Crap CMS does not read theme values from the database,crap.toml, or any other operator input and inject them into the stylesheet. There is no template/string interpolation in the theme pipeline, so there is no CSS-injection surface from operator configuration.
/* Default light theme (styles.css) */
:root {
color-scheme: light;
--color-primary: #1677ff;
--bg-body: #f4f7fc;
--text-primary: rgba(0, 0, 0, 0.88);
/* ... */
}
/* Dark theme override (themes.css) */
html[data-theme="tokyo-night"] {
color-scheme: dark;
--color-primary: #7aa2f7;
--bg-body: #1a1b26;
--text-primary: #c0caf5;
/* ... */
}
Custom Themes
To create a custom theme, add a CSS file in your config directory’s static/ folder and override the theme picker template.
1. Create the theme CSS
Create static/themes-custom.css in your config directory:
html[data-theme="my-theme"] {
color-scheme: light; /* or dark */
/* Primary accent */
--color-primary: #6366f1;
--color-primary-hover: #818cf8;
--color-primary-active: #4f46e5;
--color-primary-bg: rgba(99, 102, 241, 0.08);
/* Danger/error */
--color-danger: #ef4444;
--color-danger-hover: #f87171;
--color-danger-active: #dc2626;
--color-danger-bg: rgba(239, 68, 68, 0.08);
/* Success */
--color-success: #22c55e;
--color-success-bg: rgba(34, 197, 94, 0.08);
/* Warning */
--color-warning: #f59e0b;
--color-warning-bg: rgba(245, 158, 11, 0.08);
/* Text */
--text-primary: #1e293b;
--text-secondary: #475569;
--text-tertiary: #94a3b8;
--text-on-primary: #ffffff;
/* Surfaces */
--bg-body: #f8fafc;
--bg-surface: #ffffff;
--bg-elevated: #f1f5f9;
--bg-hover: rgba(0, 0, 0, 0.04);
/* Borders */
--border-color: rgba(0, 0, 0, 0.08);
--border-color-hover: rgba(0, 0, 0, 0.15);
/* Shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
/* Inputs */
--input-bg: #ffffff;
--input-border: rgba(0, 0, 0, 0.12);
/* Header */
--header-bg: #f1f5f9;
--header-border: rgba(0, 0, 0, 0.08);
/* Sidebar */
--sidebar-bg: transparent;
--sidebar-active-bg: rgba(99, 102, 241, 0.1);
--sidebar-active-text: #6366f1;
}
2. Drop it into themes/
The simplest path: drop themes-<name>.css into your config dir’s
static/styles/themes/ folder, then add a single line to a styles
override:
<config_dir>/
└── static/
└── styles/
├── main.css # overlays the entry — adds the @import
└── themes/
└── themes-acme.css # your theme tokens
In your overlay main.css, copy the upstream chain and append your
theme:
@import url("/static/styles/tokens.css");
@import url("/static/styles/base/normalize.css");
@import url("/static/styles/base/fonts.css");
@import url("/static/styles/base/reset.css");
@import url("/static/styles/layout/layout.css");
@import url("/static/styles/layout/edit-sidebar.css");
@import url("/static/styles/parts/cards.css");
@import url("/static/styles/parts/forms.css");
@import url("/static/styles/parts/buttons.css");
@import url("/static/styles/parts/lists.css");
@import url("/static/styles/parts/tables.css");
@import url("/static/styles/parts/breadcrumb.css");
@import url("/static/styles/parts/badges.css");
@import url("/static/styles/parts/pagination.css");
@import url("/static/styles/themes/default.css");
@import url("/static/styles/themes/themes-acme.css");
3. Add the picker option
Override templates/layout/header.hbs and add a button to the .theme-picker__dropdown:
<button type="button" class="theme-picker__option" data-theme-value="my-theme">
<span class="theme-picker__swatch" style="background:#f8fafc"></span>
My Theme
</button>
CSS Custom Properties Reference
All variables that themes should override:
| Variable | Description |
|---|---|
| Colors | |
--color-primary | Primary accent color |
--color-primary-hover | Primary hover state |
--color-primary-active | Primary active/pressed state |
--color-primary-bg | Primary tinted background (low opacity) |
--color-danger | Error/destructive color |
--color-danger-hover | Danger hover state |
--color-danger-active | Danger active state |
--color-danger-bg | Danger tinted background |
--color-success | Success color |
--color-success-bg | Success tinted background |
--color-warning | Warning color |
--color-warning-bg | Warning tinted background |
| Text | |
--text-primary | Primary text |
--text-secondary | Secondary/muted text |
--text-tertiary | Disabled/hint text |
--text-on-primary | Text on primary-colored backgrounds |
| Surfaces | |
--bg-body | Page background |
--bg-surface | Card/panel background |
--bg-elevated | Elevated surface (modals, popovers) |
--bg-hover | Generic hover background |
| Borders | |
--border-color | Default border color |
--border-color-hover | Border hover color |
| Shadows | |
--shadow-sm | Small shadow (cards) |
--shadow-md | Medium shadow (dropdowns) |
--shadow-lg | Large shadow (modals) |
| Inputs | |
--input-bg | Form input background |
--input-border | Form input border |
--select-arrow | Select dropdown arrow (SVG data URL) |
| Layout | |
--header-bg | Header background |
--header-border | Header bottom border |
--sidebar-bg | Sidebar background |
--sidebar-active-bg | Active sidebar item background |
--sidebar-active-text | Active sidebar item text color |
Variables not typically overridden by themes (inherited from :root): --radius-*, --space-*, --transition-*, --text-xs through --text-2xl, --sidebar-width, --input-height.
See CSS Variables for the full token catalogue,
including the --code-* syntax-highlight palette consumed by
<crap-code> and the size/typography tokens that don’t change between
themes.
Display Conditions
Display conditions let you show or hide fields in the admin UI based on the values of other fields. This is useful for context-dependent forms — for example, showing a URL field only when the post type is “link”.
Configuration
Add admin.condition to a field definition, referencing a Lua function:
crap.fields.text({
name = "external_url",
admin = {
condition = "hooks.posts.show_external_url",
},
}),
The condition references a Lua function using the standard hook ref format (hooks.<collection>.<name>). The function receives the current form data and returns either a condition table (client-side) or a boolean (server-side).
The data parameter is typed per-collection (crap.data.Posts, crap.global_data.SiteSettings) for IDE autocomplete. The type generator emits these types automatically.
Use crap-cms make hook with --type condition to scaffold condition hooks:
crap-cms -C ./config make hook show_external_url \
-t condition -c posts -l table -F post_type
Condition Functions
Client-Side (Condition Table)
When the function returns a table, it is serialized to JSON and embedded in the HTML. JavaScript evaluates it instantly on field changes — no server round-trip.
-- hooks/posts/show_external_url.lua
return crap.collections.posts.condition(function(data)
-- data is typed crap.data.Posts; data.post_type narrows to its select union
return { field = "post_type", equals = "link" }
end)
The crap.collections.posts.condition(fn) factory narrows data to
crap.data.Posts for body-level autocomplete. See
crap.collections.<slug>.condition
and crap.any.display_condition
for the generic equivalent.
Server-Side (Boolean)
When the function returns a boolean, the field visibility is re-evaluated on the server via a debounced fetch (300ms delay after the last input change). Use this for complex logic that can’t be expressed as a simple condition table.
-- hooks/posts/show_premium_options.lua
return crap.collections.posts.condition(function(data)
-- Complex logic that needs server-side evaluation
local tags = data.tags or {}
for _, tag in ipairs(tags) do
if tag == "premium" then return true end
end
return false
end)
Performance tip: Prefer condition tables over booleans whenever possible. Tables evaluate instantly in the browser; booleans require a server round-trip on every field change.
Condition Table Operators
| Operator | Example | Description |
|---|---|---|
equals | { field = "type", equals = "link" } | Exact match |
not_equals | { field = "type", not_equals = "draft" } | Not equal |
in | { field = "type", ["in"] = {"link", "video"} } | Value in list |
not_in | { field = "type", not_in = {"a", "b"} } | Value not in list |
is_truthy | { field = "has_image", is_truthy = true } | Non-empty, non-nil, non-false |
is_falsy | { field = "has_image", is_falsy = true } | Empty, nil, or false |
Multiple Conditions (AND)
Return an array of condition tables to require all conditions to be true:
-- hooks/posts/show_advanced.lua
return crap.collections.posts.condition(function(data)
return {
{ field = "post_type", not_equals = "link" },
{ field = "excerpt", is_truthy = true },
}
end)
How It Works
Page Load
- The server calls the Lua condition function with the current document data
- Based on the return type:
- Table: serialized as a
data-conditionJSON attribute on the field wrapper; initial visibility computed server-side - Boolean: result sets initial visibility; function reference stored as
data-condition-ref
- Table: serialized as a
- Fields with
falseconditions render withdisplay: none(no flash of content)
Client-Side Reactivity (Condition Tables)
When the user changes a form field:
- JavaScript reads the
data-conditionJSON from each conditional field - Evaluates the condition against current form values
- Shows or hides the field instantly
Server-Side Reactivity (Boolean Functions)
When the user changes a form field:
- JavaScript debounces for 300ms
- POSTs current form data to
/admin/collections/{slug}/evaluate-conditions - Server calls each boolean condition function
- Response updates field visibility
Sidebar Fields
Display conditions work on fields in any position, including sidebar fields (admin.position = "sidebar").
Safe Defaults
- If a condition function throws an error, the field remains visible (safe default)
- If the condition returns
nil, the field remains visible - On page load, fields are hidden server-side before rendering (no flash)
Complexity Limits
There are no built-in depth, length, or array-size limits on condition tables returned from Lua. The evaluator (evaluate_condition_table) recurses through arrays of conditions until it bottoms out, and each leaf object is a single AND clause.
In practice, keep condition tables small and flat:
- A single object (one operator, one field), or
- An array of objects (AND-combined).
Deeply nested or runaway-large tables will be evaluated in full both server-side (initial render) and client-side (on every form change) — so keeping them simple is a performance and readability choice, not a hard requirement. Conditions that need richer logic (loops, lookups, multi-field reasoning) are better expressed as boolean condition functions.
Template Formatter
Crap CMS ships a Handlebars formatter as a crap-cms fmt subcommand.
Templates in your config-dir overlay and the built-in templates/
directory are kept consistent the same way cargo fmt keeps Rust
consistent — one rule set, one tool, no editor disagreement.
crap-cms fmt # format everything under templates/
crap-cms fmt --check # CI gate: exit 1 if any file would change
crap-cms fmt path/to/file.hbs # one file
cat my.hbs | crap-cms fmt --stdio # editor pipe
The formatter is idempotent: fmt(fmt(x)) == fmt(x). Running it
twice produces the same result as running it once.
See the CLI reference for full flag documentation and editor integration snippets.
Rule set
1. Indentation
Two-space indent. Both HTML elements and Handlebars block helpers contribute one level each.
{{#if user}}
<div class="profile">
<h1>{{user.name}}</h1>
</div>
{{/if}}
{{else}} / {{else if}} returns to the parent level for the keyword,
then the body re-indents:
{{#if (eq variant "fieldset")}}
<fieldset>...</fieldset>
{{else if (eq variant "checkbox")}}
<div class="checkbox">...</div>
{{else}}
<label>...</label>
{{/if}}
{{#> partial}}…{{/partial}} invocations indent their body the same
way:
{{#> partials/field}}
<input type="text" name="email" />
{{/partials/field}}
2. Block helpers always own a line
{{#if}} / {{#each}} / {{#unless}} / {{#with}} / {{else}} /
{{/x}} each appear on their own line. Inline collapsing of
{{#if x}}<span>...{{/if}} is never produced — predictable beats
clever.
3. HTML attributes
- Zero or one attribute — kept inline:
<p>x</p> <a href="/x">y</a> - Two or more attributes — each on its own line, closing
>on its own line at the tag’s column:<a class="card" href="/admin/collections/{{slug}}" hx-get="/admin/collections/{{slug}}" hx-target="body" hx-push-url="true" > ... </a>
Embedded {{#if x}}required{{/if}} chunks within an attribute list are
preserved in place and stack as their own line in the multi-attr form.
4. Inline body collapse
A tag with 0–1 plain attributes wrapping a single short text-or-expression body stays on one line, as long as it fits within 100 characters:
<span class="badge">{{t "draft"}}</span>
A nested element or block helper in the body forces multi-line:
<p class="x">
<span>y</span>
</p>
5. Mustache spacing
Compact: {{t label}}, not {{ t label }}. Sub-expressions are
unchanged: {{t (concat "x" y)}}.
6. Self-closing void elements
<input />, <meta />, <br />, <hr />, <img />, <link />,
<source />, <area />, <embed />, <track />, <wbr />,
<col />, <base />. The trailing /> is added if missing.
7. Lowercase tags + attrs, double-quoted values
<INPUT TYPE='text'> → <input type="text" />
Values containing a literal " (e.g. inline JSON) fall back to single
quotes:
<meta name="htmx-config" content='{"includeIndicatorStyles":false}' />
8. Boolean attributes are bare
<input required="" /> → <input required />
<input required="required" /> → <input required />
<input required /> → <input required />
A meaningful value on a known boolean attribute is kept (the same attribute name can carry data on custom elements):
<crap-relationship-search selected='{{json items}}' />
9. Comments preserved verbatim
Both <!-- ... --> and {{!-- ... --}} keep their internal whitespace,
line breaks, and structure. Documentation comments at the top of
partials survive the formatter unchanged:
{{!-- partials/field
Wraps a form field with label + required marker + locale badge +
error + help text. Three structural variants share the same
error/help/required logic.
...
--}}
10. Triple-stash passthrough
{{{render_field this}}} is treated like a regular expression — same
spacing rules, no escaping.
11. Whitespace + final newline
- Two or more consecutive blank lines collapse to one.
- Trailing whitespace stripped per line.
- Single final newline guaranteed.
What’s intentionally not done
- Text content reflow. Prose inside text nodes is preserved as-is, not wrapped at any column.
- Raw-content elements (
<script>,<style>,<pre>,<textarea>). Their bodies are captured at tokenisation time and passed through the formatter verbatim — no indent normalisation, no mustache parsing, no whitespace collapse, no quote conversion. These elements have their own grammar (JS/CSS/JSON/preformatted text) that the formatter must not rewrite. Standalone JS/CSS files are formatted by Biome. The matching close tag (</script>etc.) is located by a case-insensitive linear scan, mirroring the HTML5 parser’s raw-text content model. Empty bodies (whitespace-only) collapse to nothing so<script src="..."></script>renders cleanly. - Whitespace-control mustaches (
{{~ ... ~}}). Rare; passed through unchanged. - Complex expression re-flow inside
{{...}}. Only outer-delimiter spacing is normalised.
Editor integration
Neovim (conform.nvim)
{
'stevearc/conform.nvim',
init = function()
vim.filetype.add { extension = { hbs = 'handlebars' } }
end,
opts = {
formatters_by_ft = { handlebars = { 'crap_cms' } },
formatters = {
crap_cms = {
command = 'crap-cms',
args = { 'fmt', '--stdio' },
stdin = true,
},
},
},
}
Pre-commit hook
#!/bin/bash
set -e
cargo fmt -- --check
cargo clippy -- -D warnings
cargo run --quiet --bin crap-cms -- fmt --check
CI
- name: Handlebars template formatting
run: cargo run --quiet --bin crap-cms -- fmt --check
Web Components
The admin UI is built from ~30 vanilla Web Components living in
static/components/. They fall into three roles:
- Singletons — one instance per page, mounted by the layout. Other
code dispatches a request event to discover the instance and invoke
methods on it (
<crap-toast>,<crap-drawer>,<crap-confirm-dialog>,<crap-delete-dialog>,<crap-create-panel>). - Form fields — wrap a slotted
<input>/<textarea>and add behaviour (<crap-tags>,<crap-code>,<crap-richtext>,<crap-password-toggle>,<crap-focal-point>). - Page enhancers — auto-init on connect to enhance the surrounding
HTMX-rendered markup (
<crap-array-field>,<crap-sticky-header>,<crap-dirty-form>,<crap-validate-form>,<crap-conditions>,<crap-list-settings>,<crap-scroll-restore>).
Every component is registered automatically by importing
/static/components/index.js (loaded by layout/base.hbs and
layout/auth.hbs). Override authors don’t need to touch
customElements.define() directly.
Discovery
Singleton components: crap:<name>-request event
A component dispatches a CustomEvent with that name, then reads
event.detail.instance populated by the singleton’s listener. The
util/discover.js::discoverSingleton(eventName) helper handles the
dance:
import { discoverSingleton } from './util/discover.js';
const drawer = discoverSingleton('crap:drawer-request');
drawer?.open({ title: 'Settings', html: '<p>…</p>' });
window.crap namespace (sugar)
static/components/global.js exposes a flat namespace as the
console-friendly / inline-template convenience layer:
window.crap.toast({ message: 'Saved', type: 'success' });
window.crap.confirm('Delete this?').then((ok) => { … });
window.crap.drawer.open({ title: '…', html: '…' });
window.crap.deleteDialog.open({ slug, id, title });
window.crap.createPanel.open({ collection, onCreated });
window.crap.theme.set('tokyo-night');
window.crap.csrf(); // shorthand for util/cookies.js::readCsrfCookie
Both layers reach the same singleton instance — window.crap is sugar
over the canonical event-discovery + module APIs documented above.
Singleton reference
| Tag | Role | Discovery event | Module |
|---|---|---|---|
<crap-toast> | Toast notifications | crap:toast-request | static/components/toast.js |
<crap-drawer> | Right-side slide-in panel | crap:drawer-request | static/components/drawer.js |
<crap-confirm-dialog> | Promise-based confirm | crap:confirm-dialog-request | static/components/confirm-dialog.js |
<crap-delete-dialog> | Delete-document confirm | crap:delete-dialog-request | static/components/delete-dialog.js |
<crap-create-panel> | Inline create-from-relation | crap:create-panel-request | static/components/create-panel.js |
<crap-session-dialog> | Idle-session warn / stay | (mounted by <crap-session-guard>) | static/components/session-guard.js |
<crap-toast> — toast({ message, type?, duration? })
import { toast } from './util/toast.js';
toast({ message: 'Saved', type: 'success' });
// types: 'success' | 'error' | 'info' (default)
// duration: ms (default 3500)
Or via the event directly:
document.dispatchEvent(new CustomEvent('crap:toast-request', {
detail: { message: 'Hi', type: 'info' },
}));
<crap-drawer> — instance.open(opts) / instance.close()
opts: { title, html?, url? }. If url is given the drawer fetches
the URL into its body via HTMX-style swap. html is a literal HTML
string (escape user input before passing).
<crap-confirm-dialog> — instance.prompt(message, opts?)
Returns Promise<boolean> — resolves true when the user clicks
Confirm, false on Cancel/Escape/backdrop. <crap-confirm> (the form-
intercepting variant) consumes this dialog automatically and falls back
to window.confirm() when no dialog is mounted.
<crap-delete-dialog> — instance.open({ slug, id, title, soft, canPerm })
Backs all [data-delete-id] buttons in the admin. Dispatches
crap:document-deleted after a successful delete so list pages can
refresh.
<crap-create-panel> — instance.open({ collection, onCreated, title? })
Inline create modal for relationship/upload fields. onCreated(doc) is
invoked with the new document on success.
Form-field components
These wrap form-bound inputs. Their tags must remain in light DOM
(or a slot-projected light child) for the browser to submit the value.
Most also dispatch crap:change ({ name, value }) on edit so
<crap-validate-form> and <crap-conditions> can react.
| Tag | Wraps | Notes |
|---|---|---|
<crap-tags> | hidden <input> | comma/Enter-separated tag input; emits crap:change |
<crap-code> | hidden <textarea> | CodeMirror 6 editor with theme-aware syntax highlight |
<crap-richtext> | hidden <textarea> | ProseMirror editor; HTML or JSON output |
<crap-password-toggle> | slotted <input type=password> | Shadow DOM; renders own toggle button + icon |
<crap-focal-point> | slotted <img> + hidden inputs | Drag-to-set focal-point coordinates for image fields |
<crap-relationship-search> | hidden <input> | Search-and-pick references (single or has-many) |
<crap-upload-preview> | hidden <input> + slot | Drag-and-drop upload + preview |
<crap-block-picker> | hidden <select> | Used inside blocks-field add-row UI |
<crap-array-field> | wraps an array-row container | Coordinates drag-reorder, add/remove, validation badge |
<crap-validate-form> | wraps a <form> | Live server-side validation via validate-url attr |
<crap-dirty-form> | wraps a <form> | Warns on navigation away with unsaved edits |
<crap-conditions> | wraps a <form> | Show/hide fields based on data-condition JSON |
crap:change event contract
Every editable field component dispatches new CustomEvent('crap:change', { detail: { name, value }, bubbles: true }) whenever the underlying
form value changes. This is the canonical signal for form-watchers
(crap-conditions, crap-dirty-form, crap-validate-form).
Page enhancers
Tag-only enhancements that auto-init on connect; no public API.
| Tag | Role |
|---|---|
<crap-sticky-header> | Sticky page-title bar with shadow on scroll |
<crap-list-settings> | Column picker + filter builder for list pages |
<crap-back-refs> | Lazy-loaded incoming-references panel |
<crap-collapsible> | Collapsible group/fieldset (uses <details> semantics) |
<crap-tabs> | Tab switcher inside group fields |
<crap-sidebar> | Mobile sidebar toggle |
<crap-scroll-restore> | Preserves scroll position across HTMX swaps |
<crap-session-guard> | Idle-session warning + auto-extend |
<crap-live-events> | SSE subscription for live document updates |
<crap-time> | Locale-aware datetime formatter |
Three pickers via CrapPickerBase
static/components/picker-base.js is the shared toggle/dropdown/
outside-click base class for:
<crap-locale-picker>— content-locale switcher (cookie-driven)<crap-ui-locale-picker>— admin-UI locale (server-persisted)<crap-theme-picker>— theme switcher (localStorage)
Subclasses declare static selectors (toggleSelector, dropdownSelector,
itemSelector, openClass, valueDatasetKey) and implement
_onValue(value). About 25 LOC each.
Util modules
Re-exported from static/components/util/index.js:
| Module | Exports |
|---|---|
util/cookies.js | readCookie(name), readCsrfCookie(), writeCookie(name, value, opts) |
util/toast.js | toast({ message, type?, duration? }) |
util/htmx.js | getHttpVerb(event) — normalise HTMX htmx:configRequest verb to upper |
util/discover.js | discoverSingleton(eventName) — returns the discovered instance or null |
util/json.js | parseJsonAttribute(el, attr, fallback), readDataIsland(host, id, fallback) |
Internal helpers (not part of the public API)
static/components/h.js—h(tag, props, ...children)typed DOM builder. ReplacesinnerHTMLtemplate strings.static/components/css.js—css`…`tagged template that returns aCSSStyleSheetforadoptedStyleSheets.static/components/i18n.js—t(key)reads thecrap-i18ndata island injected bylayout/base.hbs. The island body is emitted by the server-side{{{admin_i18n}}}helper, which serialises a curated set of keys for the active_localeas a single JSON object. To expose extra keys to JS, edit theADMIN_JS_KEYSlist insrc/admin/templates/helpers/admin_i18n.rs. Missing keys still resolve at the call site (t()falls back to the raw key) but show up untranslated.
Override pattern
Every component lives under static/components/<name>.js. Drop a
replacement at the same path in your config directory’s
static/components/<name>.js and it overrides the compiled default
(file-by-file overlay).
The override must register the same custom-element tag so existing templates continue working. To extend instead of replace, import the upstream class, subclass it, then re-define:
// <config_dir>/static/components/toast.js
import { CrapToast as Base } from '/static/components/toast.js';
class CustomToast extends Base {
show(opts) {
console.log('toast intercepted', opts);
return super.show(opts);
}
}
customElements.define('crap-toast', CustomToast);
Util modules are individually overrideable too —
static/components/util/cookies.js etc.
Tooling contract
- CSP:
script-srcis nonce-based andstyle-srcis'self'. No inlinestyle="…"attributes; constructed stylesheets only viacss.js. Components must not callel.style.setProperty('--var', '…')on light-DOM elements without an inline-style allowlist. - HTMX: components don’t fight HTMX swaps. They store cleanup state
in
disconnectedCallbackso HTMX-replaced subtrees re-initialise cleanly on the nextconnectedCallback. - Tests:
tests/e2e/browser_*.rsexercise each component via chromiumoxide. Add a regression test when changing public behaviour.
Template partials
Server-side counterpart to the JS components. Lives in
templates/partials/ and templates/layout/. Same overlay rules:
drop a file at the matching path in your config dir’s templates/
folder to override.
Partials (templates/partials/)
| Partial | Role |
|---|---|
partials/field.hbs | Wraps form input with label, required marker, locale badge, error, help; three variants: default, fieldset (radio groups), checkbox (slot-then-label) |
partials/sidebar-panel.hbs | <div class="edit-sidebar__panel"> with optional header (icon + label) and slotted body |
partials/array-row-header.hbs | Drag handle + toggle + title slot + error badge + 4 action buttons; consumed by <crap-array-field> |
partials/htmx-nav-link.hbs | <a class="button" hx-get hx-target="body" hx-push-url> link |
partials/status-badge.hbs | <span class="badge badge--{status}">{status}</span> |
partials/error-page.hbs | Full 404/403/500-style error card |
partials/warning-card.hbs | <div class="card card--warning"> with title and slotted body |
partials/loading-indicator.hbs | HTMX hx-indicator target with inline and sidebar variants |
partials/form-actions.hbs | <div class="form__actions"> chrome + cancel link, action buttons via slot |
partials/breadcrumb.hbs | Crumbs trail |
partials/pagination.hbs | Prev / page-info / Next |
partials/version-sidebar.hbs | Version-history panel inside an edit sidebar |
partials/version-table.hbs | Full-width versions table |
Most accept named parameters and inherit the rest of the call-site
context. Partials with body slots use the {{#> partials/foo …}}…{{/}}
block-call syntax and reference the slot via {{> @partial-block }}.
Layouts (templates/layout/)
| Layout | Role |
|---|---|
layout/base.hbs | Authenticated admin chrome: head + sidebar + header + main slot |
layout/auth.hbs | Unauthenticated chrome: head + auth-card + slot for the form/content |
layout/header.hbs | Page header partial rendered by base.hbs |
layout/sidebar.hbs | Left navigation rendered by base.hbs |
Pages use partial-block syntax: {{#> layout/base}}…page content…{{/layout/base}}.
See CSS Variables for the design-token contract that every component reads from.
Atom Inventory
Spec doc, not yet enforced. This page enumerates every web component in
static/components/and proposes what its stable public surface should be — the version we’d commit to not break. It’s the reference for the eventual Phase 3 refactor (atomization, versioned APIs, narrow stable surface). Today’s components mostly already obey the proposed contracts; the discrepancies are flagged.
Method
For each component we record:
- Tag — the
<crap-*>element name. - Role —
atom(single concern, well-bounded),composition(multi-piece, internally orchestrates other elements; candidates for breakdown), orsingleton(one instance per page, accessed via request-event discovery). - Stable surface — the public API that overlay authors and custom
widget authors program against.
- Attributes — host-element attributes that affect behaviour.
- Events — fired or listened to. References the named exports in
static/components/events.js. - Slots / parts — for shadow-DOM atoms only.
- Internal — anything explicitly not part of the contract. Inner DOM structure, internal classes, internal event names — all free to change.
Atoms < 200 LOC are listed first within each category.
Singletons
One instance per page, mounted by the layout. Discoverable via the
events in events.js:
| Tag | Discovery event | Methods (stable) | LOC |
|---|---|---|---|
<crap-toast> | EV_TOAST_REQUEST | show({ message, type, duration }) | 172 |
<crap-drawer> | EV_DRAWER_REQUEST | open({ title }) → mount into .body; close() | 379 |
<crap-confirm-dialog> | EV_CONFIRM_DIALOG_REQUEST | prompt(message, opts) → Promise<boolean> | 183 |
<crap-delete-dialog> | EV_DELETE_DIALOG_REQUEST | open({ slug, id, title }) | 377 |
<crap-create-panel> | EV_CREATE_PANEL_REQUEST | open({ collection, onCreated }); close() | 433 |
<crap-session-dialog> | (auto-mounted, no API) | — | 352 |
Stable contract per singleton:
- The discovery event name (constant in
events.js). - The methods listed above; their argument shapes.
- The
detail.instancediscovery-write protocol.
Internal: shadow DOM contents, CSS, internal state, internal class
names. The current implementations all use Shadow DOM with adopted
stylesheets — overlay authors restyle via CSS custom properties (which
pierce shadow boundaries) or ::part(...) selectors where exposed.
Atoms (form-shaped)
Wrap a slotted form input and add behaviour. Form-associated where
appropriate; emit EV_CHANGE (bubbling) when value changes so
<crap-dirty-form> can mark the form dirty.
| Tag | Slot | Public attributes | Events fired | LOC |
|---|---|---|---|---|
<crap-password-toggle> | <input type="password"> | — | — | 104 |
<crap-tags> | hidden <input> | data-min-length, data-max-length, data-min, data-max, data-placeholder, data-readonly, data-error, data-field-type | EV_CHANGE | 286 |
<crap-code> | hidden <input> + <textarea> | data-language, data-languages, data-readonly | EV_CHANGE | 408 |
<crap-focal-point> | <img> + hidden <input> | — | — | 142 |
<crap-richtext> | hidden <input> + <textarea> | data-features, data-format, data-nodes | EV_CHANGE | 487 |
Stable contract:
- The host attributes listed.
EV_CHANGEfires (bubbling) on value change.- The slotted input remains light-DOM and form-participating (browser submits it natively; htmx serializes it normally).
Internal: shadow DOM, internal CSS classes, internal event names.
Atoms (page-enhancement)
Light-DOM components that decorate server-rendered markup or are
mounted dynamically by an orchestrator. Some inject their own
stylesheet via document.adoptedStyleSheets on first connect (noted).
| Tag | Role | LOC |
|---|---|---|
<crap-confirm> | Wrap a child form, prompt before submit | 89 |
<crap-dirty-form> | Mark form dirty on EV_CHANGE, prompt on navigate-away | 187 |
<crap-sticky-header> | Pin a header on scroll | 50 |
<crap-sidebar> | Sidebar toggle behaviour | 83 |
<crap-time> | Format ISO timestamps in user’s locale | 57 |
<crap-collapsible> | Group/collapsible toggle | 51 |
<crap-locale-picker> | Editor locale switcher | 35 |
<crap-ui-locale-picker> | Admin UI locale switcher | 49 |
<crap-theme-picker> | Theme switcher (light/dark/auto + tokyo-night etc.) | 95 |
<crap-tabs> | Tab keyboard nav + URL-hash sync | 107 |
<crap-block-picker> | Wraps a <select> of block types; emits EV_REQUEST_ADD_BLOCK | 222 |
<crap-uploads> | Drag-drop upload handler | 128 |
<crap-back-refs> | Lazy-loaded back-references panel | 134 |
<crap-conditions> | Display-conditions evaluator | 276 |
<crap-scroll-restore> | Scroll position preservation across htmx swaps | 241 |
<crap-validate-form> | Native HTML5 form-validation surfacing | 451 |
<crap-live-events> | SSE subscriber for live document updates | 315 |
<crap-array-row> | Array/blocks row wrapper; owns row label-watcher logic | 105 |
<crap-pill-list> | Chip cluster; data-items JSON; emits crap:pill-removed. Self-styled | 197 |
<crap-column-picker> | Drawer body for picking visible columns; htmx-submits | 189 |
<crap-filter-builder> | Drawer body for where[…] filter composition. Exports OPS_BY_TYPE | 593 |
Stable contract (page-enhancement common):
- The host-element tag itself (presence on the page = behaviour active).
- Documented
data-*attributes. - Events listened to (the contract with surrounding components).
Internal: how the component reads/writes the DOM; CSS classes it adds; htmx-event piggybacking.
Compositions — refactor candidates
These render and orchestrate multiple internal pieces. They’re the primary atomization targets for Phase 3.
<crap-array-field> — array + blocks repeater (545 LOC orchestrator + 105 LOC atom)
Status: partially atomized (Phase 3.2). Extracted <crap-array-row>
(stable atom, 105 LOC) which owns the row label-watcher concern. The
remaining orchestrator handles add/remove/reorder/duplicate via event
delegation, drag-and-drop sorting, index rewriting on the cloned
template subtree, and max-rows enforcement.
A further split into <crap-array-controls> (the +/-/duplicate/move
buttons) was scoped out of Phase 3.2 — the buttons today are inline
<button data-action="..."> rendered by Handlebars and dispatched
via the orchestrator’s click delegation. Splitting them would require
rebuilding the action wiring as inter-component events; there’s no
demonstrated demand for swapping just the buttons today, so we
stopped at the row.
<crap-list-settings> — list-page toolbar (atomized in 3.3)
Status: fully atomized. The toolbar’s two drawer bodies are standalone web components mounted by the orchestrator:
| Tag | LOC | Stable surface |
|---|---|---|
<crap-list-settings> | 163 | Orchestrator: data-action="open-column-picker" / data-action="open-filter-builder" buttons; htmx-search focus preservation. |
<crap-column-picker> | 189 | data-collection (slug) + data-options (JSON ColumnOption[]); fires crap:column-picker-saved on htmx success. |
<crap-filter-builder> | 593 | data-collection (slug) + data-fields (JSON FieldMeta[]); fires crap:filter-builder-applied on apply. Exports OPS_BY_TYPE for subclass extension. |
Orchestration: the toolbar listens for data-action clicks,
discovers the page’s <crap-drawer> singleton via EV_DRAWER_REQUEST,
and mounts a freshly constructed picker/builder element (with data
already attached on its dataset) into the drawer body. The element’s
connectedCallback builds the UI; the orchestrator listens for the
element’s completion event to close the drawer.
Override patterns for users:
- Full replace: drop a replacement at
<config_dir>/static/components/list-settings/{column-picker,filter-builder}.js. - Subclass: import
CrapColumnPicker/CrapFilterBuilderfrom the modules and extend; redefine the tag in your override file. Both classes expose protected hooks (_buildValueInput,_renderOpsInto,_onSuccess) for incremental customization.
Standalone usability: a <crap-column-picker> or
<crap-filter-builder> can be dropped anywhere with the right
dataset attributes — they don’t depend on <crap-list-settings>
specifically, only on the data being attached to their own host.
<crap-relationship-search> — relationship + upload picker (1075 LOC orchestrator + 197 LOC atom)
Status: partially atomized (Phase 3.4). The chip cluster
extracted as <crap-pill-list>. The rest stays as a composition.
| Tag | LOC | Stable surface |
|---|---|---|
<crap-relationship-search> | 1075 | Host-element data-* attrs (collection, field-name, has-many, polymorphic, picker, etc.). Treat as a black box. |
<crap-pill-list> | 197 | data-items (JSON Item[]), data-readonly, data-polymorphic. Fires crap:pill-removed with { id } detail. Self-styled (injects its own stylesheet). Reusable — drop into any has-many UI. |
Honest about why we stopped at the pill list. The earlier spec
proposed <crap-search-input> and <crap-search-results> as further
sub-atoms. Reading the actual code makes it clear those wouldn’t be
genuine atoms — they’d share this._selected, this._results,
this._collection with the orchestrator and need every piece of state
threaded through attributes. The split would create more interfaces
without more independence. The whole search → fetch → render → select
loop is inherently one state machine; pretending otherwise costs more
in coordination than it saves in modularity.
The pill-list, in contrast, is naturally reusable: input is items, output is “user wants this id removed.” It works standalone, and future has-many UIs (custom field types with chip-shaped selection, new tag-style inputs) can use it directly.
Stable contract today: the host-element tag + the data-*
attributes used to bootstrap state. Internal HTML and classes are
private. Field-template overlays should target the component as a
black box. Inside the orchestrator, <crap-pill-list> is the one
piece overlay authors can swap independently — drop a replacement at
<config_dir>/static/components/pill-list.js to customize chip
rendering globally (affects every <crap-relationship-search> plus
any other component that adopts the atom).
Helpers (not custom elements)
Imported by other modules; not registered with customElements.define().
| Module | Purpose |
|---|---|
css.js | css\…`tagged-template returns aCSSStyleSheet`. |
h.js | h(tag, props, ...children) hyperscript helper. |
i18n.js | t(key) translation lookup; HTMX-swap cache invalidation. |
events.js | Named event-string constants (this doc’s source of truth). |
theme.js | getTheme(), setTheme(), applyTheme(). |
groups.js | Field group/collapsible toggle handler (legacy; shared logic). |
picker-base.js | Common base for block-picker and similar option-picker UI. |
util/cookies.js | readCsrfCookie(). |
util/discover.js | discoverSingleton(eventName) for singleton-component discovery. |
util/htmx.js | getHttpVerb(form). |
util/json.js | readDataIsland(id). |
util/toast.js | toast({ message, type, duration }) sugar over EV_TOAST_REQUEST. |
global.js | window.crap.* console / inline-template namespace. |
index.js | Module manifest; imports every component for side effects. |
These don’t have a tag-shaped public API — their stability comes from the export shape (function signatures, returned types).
Stability tiers
Every component module’s JSDoc declares one of three tiers via a
@stability tag at the bottom of the module-level block. Tier dictates
breaking-change policy:
stable— public API listed above; breaking changes need a deprecation cycle, never inside a minor release.experimental— usable, but the API may change between minors.internal— anything not listed in this doc. Free to change.
The current distribution (post-Phase-3.4):
| Tier | Count | Components | Policy |
|---|---|---|---|
| stable | 32 | 6 singletons + 5 form atoms + 17 page-enhancement atoms + 4 newly-extracted atoms (<crap-array-row>, <crap-pill-list>, <crap-column-picker>, <crap-filter-builder>) + events.js | Back-compat enforced; breaking changes get a deprecation cycle. |
| experimental | 3 | array-fields, relationship-search, list-settings (the three composition orchestrators) | Internal HTML / orchestration shape can change. The host-element tag + documented data-* attributes stay stable so field templates that emit them keep working. |
| internal | 20 | Helpers (css, h, i18n, groups, picker-base), util/ subtree, global.js, index.js, seven richtext/* ProseMirror submodules | Free to change without notice; not part of the public surface. |
Lookup with grep -l "@stability stable" static/components/*.js to
list every public-API file. The @stability tag is the single
machine-readable source of truth for tooling that wants to enforce
tier policy (lint rules, codemods, doc-extractor scripts).
Out of scope
- The richtext editor’s ProseMirror integration. ProseMirror has its
own plugin/schema API; treat
<crap-richtext>as a thin adapter and documentdata-format,data-features,data-nodesas the public surface. The schema-extension story is documented separately. - The CodeMirror integration in
<crap-code>similarly.
These wrap third-party editors with their own contracts; we keep our adapter narrow and stable, and direct users to the upstream docs for deep customization.
Admin template context reference
Every admin page renders a typed Rust struct serialized to JSON, runs it through the optional before_render Lua hook, and hands it to Handlebars. This file lists every page, its page.type discriminant, the template it renders, and the fields the template can rely on.
Field types use Rust-style notation: string, integer, boolean, Vec<T>, Option<T>. Composite leaves like CrapMeta, NavData, FieldContext link into the shared definitions section at the bottom.
Login page
-
page.type:auth_login -
Template:
templates/auth/login.hbs -
crap(CrapMeta) -
_locale(string) -
available_locales(Vec<string>) -
title(string) -
page(PageMeta) -
error(Option<string>) (optional) — Error key (e.g.,"error_invalid_credentials") — present after a failed login post. -
email(Option<string>) (optional) — Pre-fills the email field after a failed login. -
collections(Vec<AuthCollection>) -
show_collection_picker(boolean) -
disable_local(boolean) -
show_forgot_password(boolean) -
success(Option<string>) (optional) — Whitelisted success-message key shown after redirect from logout / email verification / password reset. Always emitted (asnullwhen absent) to preserve the originalOption-as-null contract.
MFA challenge page
-
page.type:auth_mfa -
Template:
templates/auth/mfa.hbs -
crap(CrapMeta) -
_locale(string) -
available_locales(Vec<string>) -
title(string) -
page(PageMeta) -
error(Option<string>) (optional)
Forgot password page
-
page.type:auth_forgot -
Template:
templates/auth/forgot_password.hbs -
crap(CrapMeta) -
_locale(string) -
available_locales(Vec<string>) -
title(string) -
page(PageMeta) -
success(boolean) -
collections(Vec<AuthCollection>) -
show_collection_picker(boolean)
Reset password page
-
page.type:auth_reset -
Template:
templates/auth/reset_password.hbs -
crap(CrapMeta) -
_locale(string) -
available_locales(Vec<string>) -
title(string) -
page(PageMeta) -
token(Option<string>) (optional) — Token from the URL — present only when valid. Absent when the link is bad / expired (in which caseerroris set instead). -
error(Option<string>) (optional)
Error pages (403 / 404 / 500)
-
page.type:error_403 | error_404 | error_500 -
Template:
templates/errors/{403,404,500}.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
message(string) — User-facing error message body.
Dashboard
-
page.type:dashboard -
Template:
templates/dashboard/index.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection_cards(Vec<CollectionCard>) -
global_cards(Vec<GlobalCard>)
Collection list
-
page.type:collection_list -
Template:
templates/collections/list.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collections(Vec<CollectionEntry>)
Collection items list
-
page.type:collection_items -
Template:
templates/collections/items.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
perms(CollectionPermissions) -
docs(Vec<any>) -
pagination(PaginationContext) -
has_drafts(boolean) -
has_soft_delete(boolean) -
is_trash(boolean) -
search(Option<string>) (optional) -
sort(Option<string>) (optional) -
table_columns(Vec<any>) -
column_options(Vec<any>) -
filter_fields(Vec<any>) -
active_filters(Vec<any>) -
active_filter_count(integer) -
title_sort_url(Option<string>) (optional) -
title_sorted_asc(boolean) -
title_sorted_desc(boolean)
Collection edit form
-
page.type:collection_edit -
Template:
templates/collections/edit.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
perms(CollectionPermissions) -
document(DocumentRef) -
fields(Vec<FieldContext>) -
sidebar_fields(Vec<FieldContext>) -
editing(boolean) -
has_drafts(boolean) -
has_versions(boolean) -
versions(Vec<any>) -
has_more_versions(boolean) -
restore_url_prefix(string) -
versions_url(string) -
document_title(string) -
ref_count(integer) -
has_locales(boolean) (optional) -
current_locale(string) (optional) -
locales(Vec<LocaleTemplateOption>) (optional) -
upload(UploadFormContext | null) (optional) — Upload preview block — present only on upload collections.
Collection create form
-
page.type:collection_create -
Template:
templates/collections/edit.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
perms(CollectionPermissions) -
fields(Vec<FieldContext>) -
sidebar_fields(Vec<FieldContext>) -
editing(boolean) -
has_drafts(boolean) -
has_locales(boolean) (optional) -
current_locale(string) (optional) -
locales(Vec<LocaleTemplateOption>) (optional) -
upload(UploadFormContext | null) (optional)
Collection form-error re-render
-
page.type:collection_edit | collection_create -
Template:
templates/collections/edit.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
perms(CollectionPermissions) -
document(DocumentRef | null) (optional) — Document stub (withidonly) on edit error; absent on create error. -
fields(Vec<FieldContext>) -
sidebar_fields(Vec<FieldContext>) -
editing(boolean) -
has_drafts(boolean) -
upload_hidden_fields(Option<Vec<any>>) (optional) — Hidden upload fields preserved from the submitted form (edit-mode upload errors only, so the user keeps their pending file metadata).
Collection delete confirmation
-
page.type:collection_delete -
Template:
templates/collections/delete.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
document_id(string) -
title_value(Option<string>) (optional) — Document title for display.None(serialized asnull) when the collection has no title field or the read fell through. -
ref_count(integer)
Collection versions list
-
page.type:collection_versions -
Template:
templates/collections/versions.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
document(DocumentRef) -
pagination(PaginationContext) -
doc_title(string) -
versions(Vec<any>) -
restore_url_prefix(string)
Collection restore confirmation
-
page.type:collection_versions -
Template:
templates/collections/restore.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
collection(CollectionContext) -
document(DocumentRef) -
version_number(any) — Version number being restored (from the version row’sversioncolumn). -
missing_relations(Vec<any>) — IDs of relationship references whose targets no longer exist. -
restore_url(string) -
back_url(string)
Global edit form
-
page.type:global_edit -
Template:
templates/globals/edit.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
global(GlobalContext) -
perms(GlobalPermissions) -
fields(Vec<FieldContext>) -
sidebar_fields(Vec<FieldContext>) -
has_drafts(boolean) -
has_versions(boolean) -
versions(Vec<any>) -
has_more_versions(boolean) -
restore_url_prefix(string) -
versions_url(string) -
doc_status(string) -
has_locales(boolean) (optional) -
current_locale(string) (optional) -
locales(Vec<LocaleTemplateOption>) (optional)
Global form-error re-render
-
page.type:global_edit -
Template:
templates/globals/edit.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
global(GlobalContext) -
perms(GlobalPermissions) -
fields(Vec<FieldContext>) -
sidebar_fields(Vec<FieldContext>)
Global versions list
-
page.type:global_versions -
Template:
templates/globals/versions.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
global(GlobalContext) -
pagination(PaginationContext) -
versions(Vec<any>) -
restore_url_prefix(string)
Global restore confirmation
-
page.type:global_versions -
Template:
templates/globals/restore.hbs -
crap(CrapMeta) -
nav(NavData) -
user(UserContext | null) (optional) -
_locale(string) — Active UI translation locale. -
available_locales(Vec<string>) — Available UI translation locales (for the locale picker). -
title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead. -
page(PageMeta) -
breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates. -
has_editor_locales(Option<boolean>) (optional) -
editor_locale(Option<string>) (optional) -
editor_locales(Option<Vec<EditorLocaleOption>>) (optional) -
global(GlobalContext) -
version_number(any) -
missing_relations(Vec<any>) -
restore_url(string) -
back_url(string)
Shared definitions
Every page above flattens BasePageContext (or AuthBasePageContext for auth-flow pages) into its top-level fields. The base structs and their leaves are defined here once.
BasePageContext
crap(CrapMeta)nav(NavData)user(UserContext | null) (optional)_locale(string) — Active UI translation locale.available_locales(Vec<string>) — Available UI translation locales (for the locale picker).title(string) — Page title — duplicated at top level for backward compat with the base layout that reads{{title}}directly. Templates that have migrated read{{page.title}}instead.page(PageMeta)breadcrumbs(Vec<Breadcrumb>) — Top-level breadcrumb mirror ofpage.breadcrumbs. The breadcrumb partial preferspage.breadcrumbsand falls back to this. Kept for backward compat with overridden templates.has_editor_locales(Option<boolean>) (optional)editor_locale(Option<string>) (optional)editor_locales(Option<Vec<EditorLocaleOption>>) (optional)
AuthBasePageContext
PageMeta
type(string) — Page-type discriminant. Serialized as asnake_casestring literal so templates can branch with{{#if (eq page.type "collection_edit")}}.title(string) — Page title or translation key.title_name(Option<string>) (optional) — Optional interpolation param for{{t page.title name=page.title_name}}.breadcrumbs(Vec<Breadcrumb>) — Breadcrumb trail rendered bypartials/breadcrumb.hbs.
CrapMeta
version(string) — Crate version (Cargo.tomlversion).build_hash(string) — Build hash (set by build script from git).dev_mode(boolean) — Whether admin dev-mode is enabled (per-request template reload, etc.).auth_enabled(boolean) — Whether the system has any auth-enabled collections.csp_nonce(string) — Per-request CSP nonce (empty string outside request scope).site_name(string) — Branding string shown in the admin header wordmark and<title>tags. Defaults to"Crap CMS"; configurable via[admin] site_name = "..."incrap.toml.
NavData
collections(Vec<NavCollection>)globals(Vec<NavGlobal>)custom_pages(Vec<CustomPage>) — Filesystem-routed custom admin pages registered viacrap.pages.register. Only entries with alabelset appear here.
NavCollection
slug(string)display_name(string)is_auth(boolean)is_upload(boolean)
NavGlobal
slug(string)display_name(string)
UserContext
email(string)id(string)collection(string)
EditorLocaleOption
value(string)label(string)selected(boolean)
LocaleTemplateOption
value(string)label(string)selected(boolean)
Breadcrumb
label(string) — The text label to display for the breadcrumb.url(Option<string>) (optional) — The optional URL to link to. If None, the breadcrumb is the current page.label_name(Option<string>) (optional) — Optional interpolation param for{{t label name=label_name}}.
CollectionContext
slug(string)display_name(string)singular_name(string)title_field(Option<string>) (optional)timestamps(boolean)soft_delete(boolean)admin(AdminMeta)upload(UploadMeta | null) (optional)versions(VersionsMeta | null) (optional)auth(AuthMeta | null) (optional)fields_meta(Vec<FieldMeta>)
GlobalContext
slug(string)display_name(string)has_drafts(boolean)has_versions(boolean)versions(VersionsMeta | null) (optional)fields_meta(Vec<FieldMeta>)
DocumentRef
id(string)created_at(Option<string>) (optional)updated_at(Option<string>) (optional)status(Option<string>) (optional)data(DocumentFields | null) (optional)
PaginationContext
per_page(integer)total(integer)has_prev(boolean)has_next(boolean)prev_url(string)next_url(string)page(Option<integer>) (optional) — Page-mode only — current page number (1-indexed).total_pages(Option<integer>) (optional) — Page-mode only — total page count.
FieldContext
(No fields.)
AuthCollection
slug(string)display_name(string)
CollectionEntry
slug(string)display_name(string)field_count(integer)
CollectionCard
slug(string)display_name(string)singular_name(string)count(integer)last_updated(Option<string>) (optional)is_auth(boolean)is_upload(boolean)has_versions(boolean)
GlobalCard
slug(string)display_name(string)last_updated(Option<string>) (optional)has_versions(boolean)
UploadFormContext
accept(Option<string>) (optional) — Comma-joined accept list for the file input — emitted only when the collection declares allowed mime types.focal_x(Option<number>) (optional)focal_y(Option<number>) (optional)preview(Option<string>) (optional) — Image preview URL when the file is an image.info(UploadInfo | null) (optional) — Filename + dimensions/filesize info pill.
UploadInfo
filename(string)filesize_display(Option<string>) (optional)dimensions(Option<string>) (optional)
CSS Variables
The admin UI uses CSS custom properties for every design decision —
spacing, color, typography, sizes, shadows, transitions, and component-
specific knobs. Themes (static/styles/themes/default.css) override
these on html[data-theme="…"], so any component reading the
variables automatically participates in theming.
The full token set lives in
static/styles/tokens.css
under :root. Below is the contract overlay authors and component
authors should code against.
Base unit
--base: 0.25rem; /* 4px @ default font size */
Every spacing/size/control token is derived from --base with a small
multiplier so changing --base rescales the whole admin proportionally.
Spacing (--space-*)
| Token | Value | Pixels (default) |
|---|---|---|
--space-2xs | base × 0.5 | 2px |
--space-xs | base | 4px |
--space-xs2 | base × 1.5 | 6px |
--space-sm | base × 2 | 8px |
--space-sm2 | base × 2.5 | 10px |
--space-md | base × 3 | 12px |
--space-lg | base × 4 | 16px |
--space-xl | base × 6 | 24px |
--space-2xl | base × 8 | 32px |
Typography (--text-*)
| Token | Value | Pixels (default) |
|---|---|---|
--text-xs | 0.75rem | 12px |
--text-sm | 0.8125rem | 13px |
--text-base | 0.875rem | 14px |
--text-lg | 1rem | 16px |
--text-xl | 1.125rem | 18px |
--text-2xl | 1.375rem | 22px |
Font family is Geist (variable font, weights 100-900) with a
system-font fallback chain.
Sizes
--icon-xs: calc(base × 3.5); /* small status icons */
--icon-sm: calc(base × 4); /* button-inline icons */
--icon-md: calc(base × 4.5); /* default icon */
--icon-lg: calc(base × 6); /* section icons */
--icon-xl: calc(base × 12); /* hero/empty-state icons */
--control-sm: calc(base × 7); /* small button height */
--control-md: calc(base × 8);
--control-lg: calc(base × 9); /* default button/input height */
--button-height: var(--control-lg);
--button-height-sm: var(--control-sm);
--input-height: var(--control-lg);
Radii
--radius-sm: 4px;
--radius-md: 6px;
--radius-lg: 8px;
--radius-xl: 12px;
--radius-full: 9999px;
Shadows
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.04);
--shadow-md: 0 2px 8px rgba(0, 0, 0, 0.06);
--shadow-lg: 0 4px 16px rgba(0, 0, 0, 0.08);
Themes override shadows for dark variants
(see themes.css).
Transitions
--transition-fast: 0.15s ease;
--transition-normal: 0.25s ease;
--transition-smooth: 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
Color — semantic palette
The four “intents” each have a base, hover, active (where applicable),
and a low-opacity background (-bg) for tinted highlights.
| Family | Base | Hover | Active | BG (12% alpha) |
|---|---|---|---|---|
| Primary | --color-primary | --color-primary-hover | --color-primary-active | --color-primary-bg |
| Danger | --color-danger | --color-danger-hover | --color-danger-active | --color-danger-bg |
| Success | --color-success | — | — | --color-success-bg |
| Warning | --color-warning | — | — | --color-warning-bg |
Plus a separate semantic accent layer that points at primary by default
but lets themes redirect (--accent-primary, --accent-primary-bg).
Text colors
--text-primary: /* default body text */
--text-secondary: /* dimmer, e.g. card meta */
--text-tertiary: /* dimmest, e.g. placeholders, help text */
--text-on-primary: /* foreground on primary-coloured surfaces */
Surfaces & borders
--bg-body: /* page background */
--bg-surface: /* card / input background */
--bg-elevated: /* modals, panels, header */
--bg-hover: /* generic hover wash */
--border-color: /* default borders, separators */
--border-color-hover: /* slightly darker for inputs/buttons */
--surface-primary, --surface-secondary, --surface-hover /* semantic aliases */
--border-default, --border-primary /* semantic aliases */
Header & sidebar
--header-height: calc(base × 10); /* sticky-header height */
--header-bg, --header-border
--sidebar-width: calc(base × 52);
--sidebar-bg
--sidebar-active-bg
--sidebar-active-text
Inputs
--input-bg, --input-border, --input-height
--padding-with-icon: calc(base × 10); /* room for trailing icon */
--select-arrow: <svg> data URL /* themed dropdown chevron */
Layout maxima
--max-width-form: calc(base × 100);
--dropdown-max-height: calc(base × 60);
--preview-max-width: calc(base × 50);
--preview-max-width-lg: calc(base × 75);
Code-editor syntax palette
<crap-code> consumes a --code-* palette so syntax highlighting
follows the active theme. Light defaults live in styles.css; each
dark theme in themes.css redefines the full set.
--code-keyword /* control flow, declarations */
--code-string /* string literals */
--code-number /* numeric literals */
--code-comment /* comments */
--code-atom /* booleans, null, etc. */
--code-property /* object property keys */
--code-function /* function names */
--code-definition /* declaration target name */
--code-type /* type names */
--code-operator /* +, -, etc. */
--code-regexp /* regex literals */
--code-meta /* preprocessor / shebangs */
--code-tag /* HTML/XML tag names */
--code-attribute /* HTML/XML attribute names */
--code-heading /* Markdown heading */
--code-link /* Markdown link / hyperlink */
How themes override
themes.css redefines the relevant palette + surface + text tokens
under html[data-theme="<name>"]. The <crap-theme-picker> component
sets that attribute and persists the choice in localStorage under
the crap-theme key. A small inline FOUC-prevention script in
layout/base.hbs reads the same key on first paint to avoid a
light-then-dark flash on page load.
To add a custom theme, override static/themes.css (or append a new
selector block) defining at minimum:
- The full color palette (primary/danger/success/warning + bg variants)
--text-*foreground colors--bg-*surface colors--border-color/--border-color-hover- The
--code-*palette --input-bg/--input-border/--select-arrow
Then wire the new theme into <crap-theme-picker> by adding a
<button data-theme-value="…"> to its dropdown markup in
layout/header.hbs (or your override).
Events
Cross-component custom events emitted by the built-in <crap-*> web
components form a stable public API. The full vocabulary is
declared in static/components/events.js
as exported EV_* constants. Overlay authors and custom-component
authors can:
- Listen for these events to react to admin actions (audit logging, analytics, validation hooks).
- Dispatch them to drive built-in singletons (open the toast layer, request a confirm dialog, populate the side drawer).
This is the recommended path for adding behavior to built-in components without replacing them. See the admin UI overview for when to use this pattern vs. an override.
Three event categories
Events fall into three categories with different intents and listening conventions:
| Category | Pattern | Where to dispatch | Where to listen |
|---|---|---|---|
| Singleton-request | *-request | document | the singleton element listens on document |
| Change notifications | crap:change | the form-field host element | the surrounding <crap-dirty-form> listens (bubbles up) |
| Local notifications | inside a composite | child element | parent element in the same component tree |
Singleton-request events
These events drive the page-mounted singleton components
(<crap-toast>, <crap-drawer>, etc.). Dispatch on document and
the singleton picks the event up.
EV_TOAST_REQUEST — crap:toast-request
Open the toast layer with a message.
import { EV_TOAST_REQUEST } from '/static/components/events.js';
document.dispatchEvent(new CustomEvent(EV_TOAST_REQUEST, {
detail: { message: 'Saved', type: 'success' },
}));
detail shape:
| Field | Type | Required | Notes |
|---|---|---|---|
message | string | yes | The message to display. |
type | 'info' | 'success' | 'warning' | 'error' | no | Default 'info'. Controls colour and icon. |
duration | number | no | Auto-dismiss after N ms. 0 keeps it open until manually dismissed. Default 3500. |
Convenience wrapper — the canonical helper is window.crap.toast({...}), which dispatches the event for you.
EV_DRAWER_REQUEST — crap:drawer-request
Open the right-side drawer with arbitrary content.
document.dispatchEvent(new CustomEvent(EV_DRAWER_REQUEST, {
detail: { url: '/admin/collections/posts/123', title: 'Edit post' },
}));
Pass { detail: {} } to discover the singleton instance — the
drawer writes back detail.instance = this. See util/discover.js
for the helper.
EV_CONFIRM_DIALOG_REQUEST — crap:confirm-dialog-request
Ask the user a yes/no question.
document.dispatchEvent(new CustomEvent(EV_CONFIRM_DIALOG_REQUEST, {
detail: {
message: 'Discard changes?',
onConfirm: () => navigateAway(),
onCancel: () => null,
},
}));
EV_DELETE_DIALOG_REQUEST — crap:delete-dialog-request
Open the delete-confirmation dialog. The dialog handles soft-delete / hard-delete / reference-counting automatically.
EV_CREATE_PANEL_REQUEST — crap:create-panel-request
Open the inline create-panel drawer (used by relationship pickers that allow creating the related document inline).
Change notifications
EV_CHANGE — crap:change
Bubbling event fired by form-shaped components when their value
changes. Listened to by the surrounding <crap-dirty-form> to mark
the form as having unsaved changes.
Emitting components: <crap-tags>, <crap-code>, <crap-richtext>,
<crap-relationship-search>, <crap-uploads>, <crap-focal-point>,
<crap-conditions>.
Plain Event — no detail. The current value is on the host
element (read via the standard form-element APIs or the component’s
.value property).
// Listen on a parent for any change in nested form-shaped components.
formEl.addEventListener('crap:change', (e) => {
const host = e.target;
console.log('changed:', host.tagName, host.value);
});
Local notifications
These events stay within a composite component tree — parent and
child are colocated, the event doesn’t reach document.
EV_PICK — crap:pick
Emitted by <crap-relationship-search>’s dropdown when the user
selects an item. The parent search field listens to set its value.
EV_REQUEST_ADD_BLOCK — crap:request-add-block
Emitted by <crap-block-picker> when a block type is chosen. Picked
up by the surrounding <crap-array-field> to insert a new block row.
Adding behavior — capture-phase listener pattern
The recommended way to add behavior to a built-in component (audit logging, analytics, validation) is to listen for its public event in the capture phase:
// <config_dir>/static/components/custom.js
document.addEventListener('crap:toast-request', (e) => {
fetch('/api/audit', {
method: 'POST',
body: JSON.stringify({ message: e.detail.message }),
});
// No stopPropagation — upstream's <crap-toast> still gets the
// event and shows the toast normally.
}, true /* capture phase */);
This pattern is strictly additive. You don’t replace the toast component, so any upstream improvements (bug fixes, new features) flow through automatically. Compare:
- Replace the component: drop your own
static/components/toast.js. You inherit no upstream improvements. - Add to the component: capture-phase listener in
custom.js. Upstream’s behavior continues. You add yours alongside.
For most “I want to do X when toast Y happens” goals, the listener pattern is cleaner.
Custom events in your overlay
If you write your own <crap-*> components (registered via the
custom.js seam), follow the same naming convention:
crap:<name>-requestfor singleton-request stylecrap:<verb>for bubbling changes- Document the
detailshape in a JSDoc typedef alongside the exported constant - Export the constant from a stable module path
This keeps your custom events discoverable in the same way the built-in ones are.
Adding a new event to the built-in vocabulary
Adding to the built-in vocabulary requires an upstream PR — these events are part of the public API. The contract:
- Add the named export in
static/components/events.jswith a JSDoc@typedeffor thedetailshape. - Update this reference page with the new entry.
- Use the constant, not the string, in every dispatcher and listener — overlay authors will program against the constant.
Strings dispatched inline anywhere else (without an EV_* constant)
are component-internal and may change without warning.
Routes
The admin UI exposes the routes below. All under /admin/ are
authenticated and CSRF-protected (where applicable). /static/ and
/uploads/ are public.
HTML routes
| Route | Description |
|---|---|
/admin | Dashboard |
/admin/login | Login page (public) |
/admin/logout | Logout |
/admin/forgot-password | Forgot password page (public) |
/admin/reset-password | Reset password page (public, requires token) |
/admin/verify-email | Email verification (public, requires token) |
/admin/collections | Collection list |
/admin/collections/{slug} | Collection items list |
/admin/collections/{slug}/create | Create form |
/admin/collections/{slug}/{id} | Edit form |
/admin/collections/{slug}/{id}/delete | Delete confirmation |
/admin/collections/{slug}/{id}/versions | Version history |
/admin/collections/{slug}/{id}/versions/{version_id}/restore | Restore a version (POST) |
/admin/globals/{slug} | Global edit form |
/admin/globals/{slug}/versions | Global version history |
/admin/globals/{slug}/versions/{version_id}/restore | Restore global version (POST) |
API routes (admin)
| Route | Method | Description |
|---|---|---|
/admin/collections/{slug}/validate | POST | Inline validation |
/admin/collections/{slug}/evaluate-conditions | POST | Display condition evaluation |
/admin/globals/{slug}/validate | POST | Global inline validation |
/admin/events | GET | SSE live update stream |
/admin/api/search/{slug} | GET | Relationship search |
/admin/api/session-refresh | POST | Reissue session cookie before expiry |
/admin/api/locale | POST | Save user’s locale preference |
/admin/api/user-settings/{slug} | POST | Save list-view column / filter selections |
Public routes
| Route | Description |
|---|---|
/health | Liveness check |
/ready | Readiness check |
/static/* | Static assets (overlay-served — see Static files guide) |
/uploads/{collection_slug}/{filename} | Uploaded files |
/api/upload/{slug} | File upload endpoint (POST) |
/mcp | MCP HTTP endpoint (POST, when MCP is enabled) |
Session refresh endpoint
POST /admin/api/session-refresh reissues the admin session cookie
when the user is about to be logged out by token expiry.
- Triggered by the client. The
<crap-session-guard>web component (static/components/session-guard.js) shows a pre-expiry warning toast and POSTs here when the operator clicks “Stay signed in”. Not polled on a fixed interval — only fired in response to the warning. - Authentication required. The handler reads
Claimsfrom request extensions (populated by the admin auth middleware), so an unauthenticated request returns401 Unauthorized. CSRF is enforced via theX-CSRF-Tokenheader /crap_csrfcookie. - Re-validates the user before reissuing. Checks that the user
still exists, is not
_locked, and that the token’ssession_versionmatches the current value in the auth collection (so a password change or session-version bump invalidates older tokens). Any failure returns401; a deleted user can’t silently keep refreshing. - Behavior on success. Issues a fresh JWT, sets
crap_session(and the matching expiry cookie) with the sameSameSite/Secureflags as login, and returns204 No Content. The body is empty — the client treats the new cookie as the success signal. - No explicit rate limit. The endpoint requires a valid existing session (so it can’t be abused unauthenticated) and the cost is one DB read plus a JWT sign.
Custom admin pages
A subset of admin URLs are filesystem-routed: any HBS template
at <config_dir>/templates/pages/<slug>.hbs is automatically served
at /admin/p/<slug> (slug-validated, case-sensitive). No Rust code
or fork required.
| Route | Description |
|---|---|
/admin/p/{slug} | Renders <config_dir>/templates/pages/{slug}.hbs against the standard admin context. Sidebar entry, label, icon, and per-page access control come from crap.pages.register("{slug}", { ... }) in init.lua. |
Slugs are restricted to a-z, 0-9, -, _. Pages without a
crap.pages.register block route normally but don’t appear in the
sidebar nav.
See Scenario 5: Add a custom admin page
for the full walkthrough including the worked
example/templates/pages/system_info.hbs reference.
Adding routes that aren’t filesystem-routed
The fixed admin route table (everything above the custom-page
section) is in src/admin/server.rs. Adding routes outside the
/admin/p/{slug} pattern requires a fork — for example, a
/admin/api/my-endpoint POST handler. For most admin extensibility
needs, the custom-page mechanism + the existing API endpoints
(SSE, search, validate, user-settings) cover the use cases without
a fork.
Migrating from the old overlay layout
In the run-up to 1.0, the admin UI customization surface was reshuffled into a stable, role-grouped layout. This page is the one-stop migration guide for any config dir built against the previous layout.
Breaking change — no compatibility aliases. Old paths now 404 outright. Config-dir overlays at any old path silently stop serving after the upgrade. Migrate before you upgrade, using the recipe below.
TL;DR
- Public components (
<crap-toast>,<crap-richtext>, etc.): override paths are unchanged. If your config dir hasstatic/components/toast.js, it still works exactly as before. - CSS files: moved from
static/*.cssflat intostatic/styles/{base,parts,layout,themes}/. Overlays at the old flat paths return 404. - Vendored JS (
htmx.js,codemirror.js,prosemirror.js): moved tostatic/vendor/. Old paths 404. - Icons (
favicon.svg,crap-cms.svg): moved tostatic/icons/. Old paths 404. - Plumbing JS modules (
h.js,css.js,i18n.js,util/, others): moved tostatic/components/_internal/. Old paths 404. Most users should never have overridden these. - Templates: not moved. Page-family folders (
auth/,collections/,dashboard/,errors/,globals/) stay at the top level alongsidepartials/,fields/,layout/,email/.
Run crap-cms templates layout against your config dir for an
auto-generated migration recipe (mkdir -p + git mv lines plus
flagged manual cleanups). Run it before upgrading: once you’re
on alpha.8, overlays at the old paths simply stop serving and the
admin falls back to the embedded defaults without a warning.
Why the change
Five problems with the old layout, in roughly the order users hit them:
- Visual clutter at the static root. Fourteen sibling CSS files plus the entry stylesheet plus three vendor JS bundles plus two SVGs all rubbing shoulders. No directory hint to indicate which was which.
- No segregation between override targets and plumbing. The
components/folder mixed 33 public web components with 13 internal helpers (h.js,css.js,events.js,util/*). New integrators couldn’t tell which files were safe to fork. - No “extend, don’t replace” anchor. Users wanting to add a thin subclass on top of a built-in component had no stable URL to import the upstream version from.
- No user seam for new components. Adding a bespoke
<my-widget>required a fork ofindex.jsto get it imported. - No upgrade visibility. Once you’d customized files, there was no built-in tooling to tell you which ones had drifted from upstream or moved.
The reshuffle solves all five with the smallest blast radius possible: public override paths stay unchanged, plumbing moves out of the way, and three new conventions land alongside.
What’s new
static/styles/ — CSS organized into a system
static/styles/
main.css # entry — @imports the rest in cascade order
tokens.css # design tokens (CSS custom properties)
base/
normalize.css # vendored normalize
fonts.css # @font-face declarations
reset.css # global resets, utilities, web-component plumbing
parts/
badges.css breadcrumb.css buttons.css cards.css
forms.css lists.css pagination.css tables.css
layout/
layout.css edit-sidebar.css
themes/
default.css # light/dark default tokens
# users drop themes-<name>.css here
The entry HTML reference is now <link href="/static/styles/main.css">.
The old URL /static/styles.css returns 404 — update overlays before
upgrading.
static/vendor/ — bundled third-party
htmx.js, codemirror.js, prosemirror.js moved here. The HBS
layout <script> tags now reference /static/vendor/<name>.js. Old
URLs (/static/htmx.js, etc.) return 404.
static/icons/ — SVGs
favicon.svg and crap-cms.svg moved here. The favicon <link> now
references /static/icons/favicon.svg. Old URLs return 404.
static/components/_internal/ — plumbing
The 13 internal helper modules moved into this reserved namespace:
static/components/_internal/
css.js global.js groups.js
h.js i18n.js picker-base.js
util/
cookies.js discover.js htmx.js
index.js json.js toast.js
The leading underscore marks the namespace as framework-reserved. Don’t override these unless you know exactly what you’re doing — they have no stability contract. Public components are unaffected.
Adding behavior without replacing — capture-phase event listeners
Most singletons (<crap-toast>, <crap-drawer>, <crap-confirm-dialog>,
etc.) are dispatch-discovered: code anywhere on the page fires a
CustomEvent and the singleton picks it up. To add behavior without
replacing the component, listen for the same event in the capture
phase and let it continue:
// <config_dir>/static/components/custom.js
document.addEventListener('crap:toast-request', (e) => {
fetch('/api/audit', {
method: 'POST',
body: JSON.stringify({ message: e.detail.message }),
});
// No stopPropagation() — upstream's <crap-toast> still gets the
// event and shows the toast normally. Strictly additive.
}, true /* capture phase */);
This is strictly additive — you don’t replace the toast component, so upstream improvements to the toast UI flow through automatically. Inheritance / subclassing isn’t required for the common “I want to add behavior X to component Y” goal.
For the rarer case where you genuinely need to replace the component
(e.g. swap out the entire rendering), drop a same-named file at
<config_dir>/static/components/<name>.js. Run
crap-cms templates status to see when upstream drifts so you can
re-port your changes.
static/components/custom.js — bespoke component seam
If <config_dir>/static/components/custom.js exists, the admin’s
index.js auto-imports it after all built-in atoms register. Use it
to register your own <my-widget> components without forking
index.js:
// <config_dir>/static/components/custom.js
import './my-weather-card.js';
import './my-status-pill.js';
When the file is absent, the auto-import is a silent no-op.
Path-by-path migration map
The full move table. Every old path in this table returns 404 in
alpha.8. Run crap-cms templates layout to get the exact git mv
lines for the files you actually have.
Static — CSS
| Old path | New path |
|---|---|
static/styles.css | static/styles/main.css |
static/normalize.css | static/styles/base/normalize.css |
static/fonts.css | static/styles/base/fonts.css |
static/badges.css | static/styles/parts/badges.css |
static/breadcrumb.css | static/styles/parts/breadcrumb.css |
static/buttons.css | static/styles/parts/buttons.css |
static/cards.css | static/styles/parts/cards.css |
static/forms.css | static/styles/parts/forms.css |
static/tables.css | static/styles/parts/tables.css |
static/layout.css | static/styles/layout/layout.css |
static/edit-sidebar.css | static/styles/layout/edit-sidebar.css |
static/themes.css | static/styles/themes/default.css |
static/lists.css and static/list-toolbar.css | merged → static/styles/parts/lists.css |
(extracted from old styles.css) | static/styles/tokens.css |
(extracted from old styles.css) | static/styles/parts/pagination.css |
Static — vendor + icons
| Old path | New path |
|---|---|
static/htmx.js | static/vendor/htmx.js |
static/codemirror.js | static/vendor/codemirror.js |
static/prosemirror.js | static/vendor/prosemirror.js |
static/favicon.svg | static/icons/favicon.svg |
static/crap-cms.svg | static/icons/crap-cms.svg |
Static — plumbing JS
| Old path | New path |
|---|---|
static/components/css.js | static/components/_internal/css.js |
static/components/global.js | static/components/_internal/global.js |
static/components/groups.js | static/components/_internal/groups.js |
static/components/h.js | static/components/_internal/h.js |
static/components/i18n.js | static/components/_internal/i18n.js |
static/components/picker-base.js | static/components/_internal/picker-base.js |
static/components/util/cookies.js | static/components/_internal/util/cookies.js |
static/components/util/discover.js | static/components/_internal/util/discover.js |
static/components/util/htmx.js | static/components/_internal/util/htmx.js |
static/components/util/index.js | static/components/_internal/util/index.js |
static/components/util/json.js | static/components/_internal/util/json.js |
static/components/util/toast.js | static/components/_internal/util/toast.js |
Public components — unchanged
The 33 public web components (<crap-toast>, <crap-richtext>,
<crap-relationship-search>, etc.) stay at
static/components/<name>.js. Override paths are unchanged.
Templates — unchanged
No template files moved. templates/auth/, templates/collections/,
templates/dashboard/, etc. stay flat at the top level alongside
templates/partials/, templates/fields/, templates/layout/,
templates/email/.
Auto-generated migration recipe
For any config dir built against the old layout:
$ crap-cms templates layout
The command walks your config dir, prints every old-layout file it
finds with its new-layout target, and emits copy-pasteable shell
commands (mkdir -p, git mv, plus cat ... > ... for the merged
lists.css/list-toolbar.css case). It also flags after-move
verifications the tool can’t safely automate (@import paths inside
moved CSS, relative import paths inside moved JS).
The command is read-only — it describes; you transform.
Why no compatibility aliases?
Every alias is a permanent maintenance tax: it pins a second public
URL to the same asset, has to be tested across upgrades, and tends to
outlive the deprecation it was meant to soften. The reshuffle is
small, mechanical, and tooling-assisted (crap-cms templates layout
gives you the exact git mv lines), so a one-shot migration is less
costly than maintaining aliases through 1.0 and beyond. If you need a
soft rollout, stage the upgrade in pre-prod with the migration
applied, verify under the strict CSP, then bump production.
Drift tooling
Once you’ve started overriding templates, components, or styles, you have a fork. Forks bit-rot — upstream renames a context key, your template still references the old one and renders empty silently. Or upstream restructures a partial, your override stops being invoked.
The crap-cms templates family of subcommands is the toolkit for
keeping forks healthy. Four read-only commands:
| Command | What it does |
|---|---|
crap-cms templates list | Lists every file you can extract — the universe of override targets. |
crap-cms templates extract | Copies an upstream default into your config dir, with a source-version header. |
crap-cms templates status | Reports which of your overrides have drifted from upstream. |
crap-cms templates diff | Shows a unified diff between one of your overrides and its upstream counterpart. |
crap-cms templates layout | Reports old-layout files in your config dir and recommends git mv commands to migrate. |
All five run against your config dir; none of them mutate any file they don’t have to (the table below is precise about which commands do and don’t touch the filesystem).
templates list — discover override targets
$ crap-cms templates list
Prints every file in the embedded defaults — the complete list of paths you can drop into your config dir to override. Filterable by type:
$ crap-cms templates list --type templates
$ crap-cms templates list --type static
--verbose shows file sizes and a tree view.
Mutates filesystem: no.
templates extract — start from a copy of upstream
$ crap-cms templates extract layout/base.hbs
Copies the embedded default for layout/base.hbs into
<config_dir>/templates/layout/base.hbs. Prepends a
{{!-- crap-cms:source 0.1.0-alpha.8 --}} comment so templates status can detect drift later.
Multiple paths are allowed:
$ crap-cms templates extract layout/base.hbs styles/main.css
Or extract everything (with optional type filter):
$ crap-cms templates extract --all
$ crap-cms templates extract --all --type templates
Mutates filesystem: writes into your config dir. Skips files
that already exist unless --force is passed.
templates status — drift overview
$ crap-cms templates status
Walks your config dir, parses the source-version header from each override, and reports drift state per file:
Templates customization status (config dir: ./crap, running version: 0.1.0-alpha.8)
✓ static/styles/themes/themes-acme.css — current
⚠ templates/layout/base.hbs — behind: extracted from 0.1.0-alpha.5
✗ templates/old/header.hbs — orphaned: extracted from upstream but no longer exists there
· static/components/custom.js — user-original (no upstream counterpart)
= templates/auth/login.hbs — pristine (matches upstream)
Summary: 1 current, 1 behind, 0 ahead, 1 pristine, 0 unknown header, 0 no header, 1 orphaned, 1 user-original
Run `crap-cms templates diff <PATH>` to compare a file against upstream.
Drift states (icons in the status output):
| Icon | State | Meaning |
|---|---|---|
✓ | Current | Header version matches running crap-cms version. |
= | Pristine | Matches upstream byte-for-byte (you extracted but never edited). |
⚠ | Behind | Header version is older than running. Re-extract to see what changed upstream. |
↑ | Ahead | Header version is newer (downgrade scenario). |
? | NoHeader | No source-version header (hand-written or stripped). No drift visibility for that file — git is your tool. |
? | UnknownVersion | Source-version header present but unparseable as semver. Repair or re-extract. |
✗ | OrphanedUpstream | File claims to extend an upstream that no longer exists (deleted / renamed in a later release). |
· | UserOriginal | No upstream counterpart. A wholly user-authored file (custom widget, bespoke theme, slot contribution, custom admin page). Reported informationally; never a warning. |
Mutates filesystem: no.
templates diff — see what changed upstream
$ crap-cms templates diff templates/layout/base.hbs
Prints a unified diff between your overlay file and the embedded upstream:
--- upstream/templates/layout/base.hbs
+++ /path/to/your/config/templates/layout/base.hbs
@@ ... @@
- <link href="/static/styles/main.css" rel="stylesheet" />
+ <link href="/static/styles/main.css" rel="stylesheet" />
+ <link href="/static/styles/themes/themes-acme.css" rel="stylesheet" />
Useful when templates status flagged a file as behind and you
want to see what changed upstream so you can re-port your edits.
The diff is computed via the similar
crate’s Myers algorithm — multi-line insertions group correctly
rather than producing lockstep noise.
Mutates filesystem: no.
templates layout — migrate to a new layout
$ crap-cms templates layout
Walks your config dir, identifies files at old layout paths (pre-1.0 reshuffle), and prints an auto-generated migration recipe:
Old layout detected (3 files):
static/list-toolbar.css → static/styles/parts/lists.css
static/lists.css → static/styles/parts/lists.css
static/styles.css → static/styles/main.css
Recommended migration (run from /path/to/config):
mkdir -p static/styles static/styles/parts
git mv static/styles.css static/styles/main.css
# MERGE — 2 old files into static/styles/parts/lists.css
cat static/list-toolbar.css static/lists.css > static/styles/parts/lists.css
git rm static/list-toolbar.css static/lists.css
git add static/styles/parts/lists.css
After moving, verify these things the tool can't safely rewrite:
• `import` paths inside moved JS files (relative paths may break).
• `{{> "path/to/partial"}}` references in HBS (name lookups are safe).
• `@import url(...)` references in moved CSS files.
• `<link>` / `<script>` URLs in any layout HBS files you've overridden.
Then run `crap-cms templates status` to confirm drift visibility re-attaches.
Includes git mv commands for simple moves and cat ... > ... /
git rm recipes for files that merge into a single new file
(e.g., lists.css + list-toolbar.css → parts/lists.css).
Mutates filesystem: no — read-only. The recipe describes; you transform. The tool is honest about what it can’t safely do (rewrite imports inside moved files), and lists those manual verifications.
See Migrating from the old layout for the full background on the pre-1.0 reshuffle and the compatibility-alias behavior.
Workflow — typical fork-maintenance cycle
# After upgrading crap-cms to a new release:
$ cargo install crap-cms --version 0.1.0-alpha.9
# 1. See what's drifted in your config dir:
$ crap-cms templates status
# 2. For each file flagged as "behind", inspect the upstream changes:
$ crap-cms templates diff templates/layout/base.hbs
# 3. Re-port your edits onto a fresh extract, OR keep your overlay
# if upstream's changes don't affect your customizations:
$ crap-cms templates extract --force layout/base.hbs
# Re-apply your edits to the freshly-extracted copy.
# 4. Verify no orphaned overrides:
$ crap-cms templates status
# Should show all overrides as ✓ current or = pristine.
The workflow scales: a config dir with 50 overrides, run status
once, focus on the 3 files flagged behind or orphaned. The other
47 are still tracking upstream cleanly.
Source-version header
When templates extract writes a file, it prepends a one-line
header that records the upstream version:
{{!-- crap-cms:source 0.1.0-alpha.8 --}}
<!DOCTYPE html>
...
/* crap-cms:source 0.1.0-alpha.8 */
:root {
...
}
/* crap-cms:source 0.1.0-alpha.8 */
import { ... } from '...';
...
The header is purely metadata — the file works identically with
or without it. templates status reads the header to compute drift.
A user who hand-writes an override (or strips the header for
aesthetic reasons) loses drift visibility for that file but keeps
the override functional.
If you regret stripping a header, just re-extract with --force
into a temporary directory, copy the header line back, and discard
the rest.
Stability tiers
Every public-surface module in the admin UI carries a @stability
JSDoc tag in its module-level comment:
/**
* Toast notifications — `<crap-toast>`.
*
* @module toast
* @stability stable
*/
The tier tells you what to expect when you depend on that module’s public API across upgrades. Three tiers, plus a default for files without a tag.
Tier definitions
@stability stable
The module is part of the documented public API. Its exports — host attributes for components, named events, slots, partials, config fields, CSS tokens — are covered by the deprecation policy. Breaking changes get a major version bump and a deprecation cycle.
What’s stable about a stable module:
- The tag name (for components)
- Documented attributes / parameters
- Documented events with their
detailshapes - Named slots and their contexts (where declared via
{{slot "name"}}) - CSS custom properties exported as theme tokens
- CSS
::part(...)selectors where exposed viapart="..."attributes inside the component’s Shadow DOM
Note: as of this release, no built-in components expose
part="..."attributes, so::partselectors don’t currently work as a customization path. They’re listed here because they’re part of the contract if a component declares them in a future release. For today’s CSS-level customization, use theme tokens.
What’s not part of the contract even on a stable module:
- Internal HTML structure (Shadow DOM components)
- Class names on internal elements (
.foo__barinside the component) - Function names of private (
_method) methods - Internal CSS that isn’t a custom property or an exposed
::part
Override at your own pace. If upstream changes anything you depend
on, you’ll see it in crap-cms templates status (for file overlays)
or as a deprecation warning in your dev-mode console (for runtime
contract changes).
@stability experimental
The module is shipped but its API is still settling. Breaking changes can land in any minor release. Used for features that work but haven’t gone through the design review for a stable contract yet.
Three components currently carry this tier (run a grep at HEAD to see the live list — they shift as features mature):
$ find static/components -name "*.js" -exec grep -l "@stability experimental" {} \;
If you depend on an experimental module, lock to a specific crap-cms version in your deployment and pin the override file too — treat the upgrade as opt-in. Read the changelog before bumping.
@stability internal
The module is plumbing. Not for override. Its contract changes without warning. This includes:
_internal/modules (h.js,css.js,i18n.js,util/*)- Sub-modules of public components (
richtext/,list-settings/) - The
index.jsentry point itself groups.js,picker-base.js
Listed in components reference for
discoverability, but not part of the override surface. If you
override an internal module, expect breakage on the next upgrade.
The leading underscore on _internal/ is a visual marker for the
filesystem convention (Hugo’s _default/, Next.js’s _folder —
underscore = framework-reserved).
Untagged
A handful of modules have no @stability tag yet. Treat them as
internal until proven otherwise — they haven’t been formally
classified, and the absence of a tag means the maintainers haven’t
committed to a contract. Open an issue if you have a use case for
overriding one; it might warrant promotion to stable.
Tier counts at HEAD
$ find static/components -name "*.js" -exec grep -l "@stability stable" {} \; | wc -l
32
$ find static/components -name "*.js" -exec grep -l "@stability experimental" {} \; | wc -l
3
$ find static/components -name "*.js" -exec grep -l "@stability internal" {} \; | wc -l
20
Run these yourself to see the current split — the numbers shift as the inventory matures (an experimental module promoted to stable, internal helpers extracted from a stable module, etc.).
Why tiers matter for overlays
The override surface is every file in templates/ and static/ —
but the stability contract only covers public API on stable
modules. When you override a stable component (drop a replacement
toast.js), you’re forking a documented API; upstream commits to
not break your override silently.
When you override an internal module (drop a replacement h.js),
you’re forking plumbing — upstream may rename, restructure, or
delete it without warning. crap-cms templates status will tell you
when it happens, but your repair work is on you.
In practice: the public components you’d reasonably want to
customize are all stable. The internal modules are the
plumbing you’d never touch unless you were explicitly hacking on
the framework.
Promotion / demotion
Modules can move tiers between releases:
- Experimental → stable — when the API has settled and we’re willing to commit to it. Announced in the release notes.
- Stable → deprecated → removed — when we want to retire something. The deprecation goes through at least one minor cycle with a warning before the next major version drops it.
- Internal → stable — rare. Happens when an internal helper
ends up being so heavily depended on that we decide to promote
it. The Rust
pub(crate)→pubanalogue.
Tier transitions are always announced in the changelog under a “Public surface” heading.
How to lint your overlay against tiers
The drift-detection toolkit doesn’t currently distinguish overrides
by tier — crap-cms templates status reports drift uniformly. A
future crap-cms doctor command will flag overrides of
experimental or internal modules with a stronger warning, since
those are the ones most likely to break on upgrade.
In the meantime, the convention is:
- Override stable modules freely.
- Override experimental modules only with a version pin in your deployment.
- Don’t override internal modules unless you know exactly what you’re doing.
Database
Crap CMS supports two first-class database backends:
- SQLite (default) — zero configuration, single file, no server to manage, WAL mode for concurrent reads. The right choice for single-node deployments and the vast majority of workloads.
- PostgreSQL — enabled via
--features postgresat build time. Full feature parity with SQLite: schema sync, migrations, full-text search (viatsvector),_ref_countdelete protection, soft delete, atomic job claiming (FOR UPDATE SKIP LOCKED), and all query operators. No feature degradation — pick whichever matches your operational model.
The choice primarily comes down to your deployment topology:
- Single server, single writer → SQLite (simpler, one binary, one file to back up).
- Multi-server / high availability / dedicated job workers → PostgreSQL (shared writer across nodes).
See Multi-Server Deployment for the full multi-node setup. The rest of this page documents the schema conventions and sync behavior that apply to both backends; SQLite is used for the examples.
Configuration
[database]
path = "data/crap.db" # relative to config dir, or absolute
pool_max_size = 64 # connection pool size
cache_size = -16384 # page cache in KB (16MB)
mmap_size = 268435456 # memory-mapped I/O (256MB)
For PostgreSQL:
[database]
backend = "postgres"
url = "host=db.example.com user=crap dbname=crap_cms"
WAL Mode (SQLite)
The database runs in WAL (Write-Ahead Logging) mode for better concurrent read performance. This is set automatically when the connection pool is created.
Schema
Collection Tables
Each collection gets a table named after its slug:
CREATE TABLE posts (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
status TEXT DEFAULT 'draft',
content TEXT,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
Column types are determined by field types:
| Field Type | SQLite Type |
|---|---|
| text, textarea, richtext, select, date, email, json | TEXT |
| number | REAL |
| checkbox | INTEGER |
| relationship (has-one) | TEXT |
Auth collections also get a _password_hash TEXT column.
Global Tables
Named _global_{slug}, always have a single row with id = 'default':
CREATE TABLE _global_site_settings (
id TEXT PRIMARY KEY,
site_name TEXT,
tagline TEXT,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
Junction Tables
Has-many relationships and arrays use join tables:
-- Has-many relationship: posts_tags
CREATE TABLE posts_tags (
parent_id TEXT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
related_id TEXT NOT NULL,
_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (parent_id, related_id)
);
-- Array field: posts_slides
CREATE TABLE posts_slides (
id TEXT PRIMARY KEY,
parent_id TEXT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
_order INTEGER NOT NULL DEFAULT 0,
title TEXT,
image_url TEXT,
caption TEXT
);
Metadata Table
CREATE TABLE _crap_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT DEFAULT (datetime('now'))
);
Dynamic Schema Sync
On startup, Crap CMS compares Lua definitions against the database schema:
- Missing tables — created with all columns
- Missing columns — added via
ALTER TABLE ADD COLUMN - Missing junction tables — created for new has-many/array fields
- Removed columns — logged as warnings (not dropped)
- Missing
_password_hash— added to auth collections
Schema sync runs in a single transaction. If anything fails, all changes are rolled back.
Connection Pool
The r2d2 pool provides connections for both reads and writes:
- Read operations —
db/ops.rsgets a connection from the pool, callsquery::*functions - Write operations — callers get a connection, open a transaction, call
query::*, then commit - Hook CRUD — hooks share the caller’s transaction via the TxContext pattern
Transaction Pattern
All write operations follow this pattern:
1. Get connection from pool
2. Begin transaction
3. Run before-hooks (with transaction access)
4. Execute query (inside same transaction)
5. Run after-hooks (inside same transaction, errors roll back)
6. Commit transaction
Cache Backend
Crap CMS uses a pluggable cache backend for cross-request caching of populated relationship documents. The cache is cleared automatically on any write operation (create, update, delete) and optionally on a periodic timer.
Backends
Memory (default)
In-process DashMap with a configurable soft entry cap. Fast, zero infrastructure, but per-server — each instance has its own cache.
[cache]
backend = "memory"
max_entries = 10000
When to use: Single-server deployments, development, or when you don’t need cross-server cache coherence.
Redis
Shared cache via Redis. All servers read and write to the same cache, so a write on one server invalidates the cache for all. Requires building with --features redis.
[cache]
backend = "redis"
redis_url = "redis://redis.example.com:6379"
prefix = "crap:"
max_age_secs = 60
Keys are automatically prefixed with prefix for namespace isolation. When max_age_secs > 0, each key is set with a Redis TTL — expired keys are evicted by Redis automatically, and the periodic clear task also runs as a safety net.
When to use: Multi-server deployments where stale cache data across servers is unacceptable.
Authentication & TLS
Redis credentials and TLS are encoded directly into the connection URL — there is no separate [cache] password or [cache] tls key. The URL is passed straight through to the redis crate:
- Plain TCP, no auth:
redis://host:6379 - Plain TCP, password:
redis://:mypassword@host:6379(note the leading colon for password-only) - ACL user (Redis 6+):
redis://acl_user:acl_pass@host:6379 - TLS:
rediss://user:pass@host:6380(doubles—rediss, notredis) - Specific DB: append
/<db_number>, e.g.redis://host:6379/1
The same URL is reused by the rate-limit and live-update Redis backends unless they override it.
None
No-op backend. Cache operations are silently ignored. Each request’s relationship population runs fresh queries with no cross-request sharing.
[cache]
backend = "none"
When to use: When the database is modified outside the API (direct SQL, external tools) and stale reads are unacceptable, or when debugging cache-related issues.
Cache Stampede
There is no built-in singleflight / request coalescing on miss. Under concurrent load against a cold (or freshly-invalidated) key, every in-flight request independently hits the database until the first one completes and populates the cache. This is the classic “thundering herd” behavior.
Impact: CPU / DB spikes on cold-start, on cache flushes, and immediately after any write (since every write invalidates the cache globally).
Mitigations:
- Keep
max_age_secslong enough that steady-state hit rates are high — short TTLs compound the effect. - Put a CDN or front-proxy cache in front of public read endpoints so the origin isn’t the first line of defense.
- Rate-limit pathological clients at the edge (the load balancer or CDN), not the application, so stampedes can’t be induced externally.
This is a known limitation. Singleflight / request coalescing is a candidate future enhancement; until then, the design assumes the DB can absorb the worst-case fan-out of one uncached fetch per concurrent reader per invalidation event.
Cache Invalidation
The cache uses two invalidation strategies:
-
Write-through invalidation — every
Create,Update,Delete,Restore,UpdateMany,DeleteMany,UpdateGlobal, andRestoreVersionoperation clears the entire cache. This is the primary invalidation mechanism. -
Periodic full clear — when
max_age_secs > 0, a background task clears the entire cache on a timer. This handles external database mutations that bypass the API.
Configuration Reference
| Field | Type | Default | Description |
|---|---|---|---|
backend | string | "memory" | "memory", "redis", or "none" |
max_entries | integer | 10000 | Soft cap for memory backend. New keys are rejected at capacity; existing keys can still be updated. |
max_age_secs | integer | 0 | Periodic clear interval (seconds). 0 = disabled. For Redis, also sets per-key TTL. |
redis_url | string | "redis://127.0.0.1:6379" | Redis connection URL. |
prefix | string | "crap:" | Key prefix for Redis namespace isolation. |
API Surface Comparison
This document compares the three API surfaces — Admin UI, gRPC API, and Lua CRUD (hook local API) — to track feature consistency.
CREATE Lifecycle
| Step | Admin | gRPC | Lua CRUD |
|---|---|---|---|
| Access control (collection-level) | Yes | Yes | Yes (overrideAccess) |
| Field-level write stripping | Yes | Yes | Yes (overrideAccess) |
| Password extraction (auth) | Yes | Yes | Yes |
| before_validate (field + collection + registered) | Yes | Yes | Yes |
| Validation | Yes | Yes | Yes |
| before_change (field + collection + registered) | Yes | Yes | Yes |
| DB insert | Yes | Yes | Yes |
| Join table data (arrays, blocks, has-many) | Yes | Yes | Yes |
| Password hash + store | Yes | Yes | Yes |
| Versioning (status + snapshot + prune) | Yes | Yes | Yes |
| after_change (field + collection + registered) | Yes | Yes | Yes |
| Publish event (SSE/WebSocket) | Yes | Yes | No (in-transaction) |
| Verification email (auth + verify_email) | Yes | Yes | No |
UPDATE Lifecycle
| Step | Admin | gRPC | Lua CRUD |
|---|---|---|---|
| Access control (collection-level) | Yes | Yes | Yes (overrideAccess) |
| Field-level write stripping | Yes | Yes | Yes (overrideAccess) |
| Password extraction (auth) | Yes | Yes | Yes |
| Unpublish path | Yes | Yes | Yes |
| before_validate (field + collection + registered) | Yes | Yes | Yes |
| Validation | Yes | Yes | Yes |
| before_change (field + collection + registered) | Yes | Yes | Yes |
| DB update (or draft-only version save) | Yes | Yes | Yes |
| Join table data | Yes | Yes | Yes |
| Password hash + store (normal path) | Yes | Yes | Yes |
| Versioning (status + snapshot + prune) | Yes | Yes | Yes |
| after_change (field + collection + registered) | Yes | Yes | Yes |
| Publish event | Yes | Yes | No (in-transaction) |
DELETE Lifecycle
| Step | Admin | gRPC | Lua CRUD |
|---|---|---|---|
| Access control | Yes | Yes | Yes (overrideAccess) |
| before_delete (collection + registered) | Yes | Yes | Yes |
| DB delete | Yes | Yes | Yes |
| after_delete (collection + registered) | Yes | Yes | Yes |
| Upload file cleanup | Yes | Yes | Yes |
| Publish event | Yes | Yes | No (in-transaction) |
FIND Lifecycle
| Step | Admin | gRPC | Lua CRUD |
|---|---|---|---|
| Access control (collection-level) | Yes | Yes | Yes (overrideAccess) |
| Constraint filter merging | Yes | Yes | Yes |
| Draft-aware filtering | Yes | Yes | Yes |
| before_read hooks | Yes | Yes | Yes |
| DB query + count | Yes | Yes | Yes |
| Hydrate join tables | Yes | Yes | Yes |
| Upload sizes assembly | Yes | Yes | Yes |
| after_read hooks (field + collection + registered) | Yes | Yes | Yes |
| Relationship population (depth) | Yes | Yes | Yes |
| Select field stripping | Yes | Yes | Yes |
| Field-level read stripping | Yes | Yes | Yes (overrideAccess) |
FIND_BY_ID Lifecycle
| Step | Admin | gRPC | Lua CRUD |
|---|---|---|---|
| Access control (collection-level) | Yes | Yes | Yes (overrideAccess) |
| before_read hooks | Yes | Yes | Yes |
| Draft version overlay | Yes | Yes | Yes |
| Hydrate join tables | Yes | Yes | Yes |
| Upload sizes assembly | Yes | Yes | Yes |
| after_read hooks (field + collection + registered) | Yes | Yes | Yes |
| Relationship population (depth) | Yes | Yes | Yes |
| Select field stripping | Yes | Yes | Yes |
| Field-level read stripping | Yes | Yes | Yes (overrideAccess) |
Remaining By-Design Differences
| Feature | Admin | gRPC | Lua CRUD | Reason |
|---|---|---|---|---|
| Event publishing | Yes | Yes | No | Lua runs inside the caller’s transaction; event publishing is fire-and-forget after commit. The caller (admin/gRPC) publishes the event. |
| Upload file cleanup on delete | Yes | Yes | Yes | Lua CRUD reads ConfigDir from Lua app_data; admin/gRPC clean up after commit. |
| Verification email on create | Yes | Yes | No | Email sending is async, post-commit. |
| Locale from request | Yes | Yes | Explicit opt | Admin/gRPC infer from request; Lua passes explicitly via opts.locale. |
| Default depth | Varies | Config | 0 | Lua defaults to 0 to avoid N+1 in hooks. Callers pass depth explicitly. |
Single Server Deployment
The default and recommended deployment for most use cases. Everything runs on one machine with a single command.
Quick Start
crap-cms serve
That’s it. The server starts the admin UI, gRPC API, and background job scheduler. SQLite stores everything in a single file (data/crap.db).
Background Mode
crap-cms serve --detach # start in background
crap-cms serve --status # check if running
crap-cms serve --stop # graceful shutdown
crap-cms serve --restart # stop + start
Logs
When you run with --detach, file logging is auto-enabled — the child process no longer owns a terminal, so stdout / stderr are redirected to /dev/null and the log output instead goes to a rotating file in the log directory.
- Location:
<config_dir>/data/logs/by default (configurable via[logging] pathincrap.toml; absolute paths are respected). - Rotation: daily by default (
[logging] rotation:"daily"/"hourly"/"never"). Old files are pruned on startup based on[logging] max_files(default30). - Reading logs:
crap-cms logstails recent output,crap-cms logs -ffollows in real time,crap-cms logs cleardeletes rotated files. Or tail the files underdata/logs/directly with any tool of your choice. - Structured output: pass
--jsontocrap-cms serve(or setCRAP_LOG_FORMAT=json) for JSON lines suitable for log-aggregation pipelines (Loki, ELK, etc.).
Foreground crap-cms serve (no --detach) keeps logs on stdout by default — set [logging] file = true in crap.toml to also write to a file.
If the disk fills up, log writes silently fail; size the log directory to tolerate max_files × typical_rotation_size worst-case.
What You Get
- Admin UI on port 3000
- gRPC API on port 50051
- Job scheduler processing cron jobs and queued tasks
- Image processing for upload collections
- Live updates via SSE and gRPC streaming
When to Scale
A single server handles thousands of concurrent readers and hundreds of writes per second. This covers the vast majority of CMS workloads — content sites, editorial teams, headless API backends.
Consider scaling when you need:
- Multiple app servers behind a load balancer (high availability)
- 50+ simultaneous content editors (write throughput)
- Dedicated job processing (heavy background work separate from request handling)
See Multi-Server for scaling options.
Multi-Server Deployment
For high availability and dedicated job processing. Requires a shared database and shared file storage.
Most projects don’t need this. A single server handles thousands of concurrent users. See Single Server for the recommended default.
Architecture
┌─────────────┐ ┌─────────────┐
│ App Server │ │ App Server │
│ serve │ │ serve │
│ --no-sched │ │ --no-sched │
└──────┬───────┘ └──────┬───────┘
│ │
▼ ▼
┌──────────────────────────────────┐
│ Load Balancer │
└──────────────────────────────────┘
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ PostgreSQL │ │ S3 / MinIO │
│ (shared DB) │ │ (shared FS) │
└─────────────┘ └─────────────┘
▲
│
┌──────┴───────┐
│ Worker │
│ work │
└──────────────┘
Requirements
- Shared database — PostgreSQL (build with
--features postgres) - Shared file storage — S3-compatible object storage only (build with
--features s3-storage). Works with AWS S3, MinIO, Cloudflare R2, Backblaze B2, or any other S3-compatible backend. Shared filesystems (NFS, EFS, SMB) are NOT supported for multi-node —storage = "local"assumes a single writer and is not tested against the fsync / advisory-lock semantics of networked filesystems. Use object storage. - Shared rate limits (required for security) — Redis (build with
--features redis). Without it, per-IP login rate limits are per-node counters: an attacker that round-robins across nodes multiplies their allowance by the node count (e.g. a 5-attempt limit across 3 nodes becomes 15 attempts before any node throttles). This is a throttling bypass, not a performance tweak. - Shared cache (recommended) — Redis for cross-server cache invalidation
- Shared live-update transport (required if you rely on SSE or gRPC Subscribe across more than one node) — Redis pub/sub so mutation events and user-invalidation signals fan out to every server node. See Live Updates below.
Setup
1. Database
# crap.toml (all servers share the same config)
[database]
backend = "postgres"
url = "host=db.example.com user=crap dbname=crap_cms"
2. File Storage
S3-compatible object storage is the only supported multi-node option. storage = "local" is fine for single-node; across multiple nodes it breaks because each node writes to its own local disk. Do not substitute a shared filesystem (NFS, EFS, SMB) — the code isn’t tested against their fsync / locking semantics and silent data loss is the likely failure mode.
[upload]
storage = "s3"
[upload.s3]
bucket = "my-uploads"
endpoint = "https://s3.amazonaws.com"
access_key = "${AWS_ACCESS_KEY}"
secret_key = "${AWS_SECRET_KEY}"
Any S3-compatible backend works — AWS S3, MinIO, Cloudflare R2, Backblaze B2, etc. Point endpoint at the provider’s URL.
3. Cache
Without a shared cache, each server maintains its own in-memory populate cache. Writes on one server won’t invalidate another’s cache. Use Redis for shared cache invalidation:
[cache]
backend = "redis"
redis_url = "redis://redis.example.com:6379"
prefix = "crap:"
Alternatively, use max_age_secs with the memory backend to limit staleness:
[cache]
backend = "memory"
max_age_secs = 10
4. Rate Limits (required)
Without shared rate limits, each server tracks login attempts independently — an attacker who round-robins requests across nodes effectively multiplies their rate-limit budget by the node count. A 5-attempt-per-IP limit spread across 3 nodes means 15 attempts before any single node throttles. This is a security requirement, not a performance optimization: use Redis to enforce a global per-IP counter.
[auth]
rate_limit_backend = "redis"
# rate_limit_redis_url defaults to cache.redis_url if empty
5. Live Updates (SSE / gRPC Subscribe)
Two transports are available:
transport = "memory"(default) — events are broadcast on an in-processtokio::sync::broadcastchannel. A write on node A reaches only subscribers connected to node A. Acceptable for sticky-load-balanced setups where every subscriber is pinned to the node that serves every write they care about; insufficient for round-robin balancing or for a pure reader node watching writes from elsewhere.transport = "redis"— mutation events and user-invalidation signals (PermissionDeniedon lock / hard-delete) are published to Redis pub/sub and fan out to every node. Any subscriber on any node sees every event, regardless of which node published it. This is the correct choice as soon as you have more than one node.
[live]
transport = "redis"
# Reuses [cache] redis_url — no duplicate configuration
Both transports use the same Redis URL configured under [cache] redis_url (single source of truth — no separate [live] redis_url key). transport = "redis" requires --features redis at build time; if the feature is missing, startup aborts with an explicit error.
Events are JSON-encoded and published to the crap:events / crap:invalidations channels. The same send-timeout / lagged-subscriber drop semantics apply as for the in-process transport — a Redis reader that can’t keep up is force-dropped with RecvError::Lagged.
Sticky load balancing is still recommended for SSE and gRPC Subscribe streams even with transport = "redis": reconnects to a different node lose the in-flight subscription context (sequence position, filter state) and the client has to re-subscribe. See the Load Balancer Stickiness section below.
See also Live Updates Overview for the transport-selection rationale and caveats.
6. App Servers
Run without the scheduler — job processing is handled by dedicated workers.
crap-cms serve --no-scheduler
7. Workers
One or more dedicated job workers process queues.
# General worker (all queues)
crap-cms work --detach
# Specialized workers
crap-cms work --detach --queues email
crap-cms work --detach --queues heavy --concurrency 2
Workers support the same lifecycle management as the server:
crap-cms work --status
crap-cms work --stop
crap-cms work --restart
Job Queue Safety
The job queue is multi-server safe:
- Cron dedup — Cron jobs are deduplicated via the
_crap_cron_firedtable. Only one server fires each cron job per schedule window, regardless of how many instances run the scheduler. - Atomic claiming (Postgres) — Jobs are claimed using
FOR UPDATE SKIP LOCKED. Workers never claim the same job, and per-slug concurrency limits are enforced in the database. - Atomic claiming (SQLite) — Claims run inside IMMEDIATE transactions, serializing concurrent workers.
Multiple workers can safely run crap-cms work against the same database.
Configuration Notes
- All servers and workers share the same
crap.tomland config directory - Schema sync (
migrate up) only needs to run once — any server that starts first handles it on_inithooks run on every server/worker startup- Email uses the job queue automatically — password resets and verification emails are processed by workers with retries
Email Configuration
With dedicated workers, the webhook email provider is recommended over SMTP for better reliability:
[email]
provider = "webhook"
webhook_url = "https://api.sendgrid.com/v3/mail/send"
webhook_headers = { Authorization = "Bearer ${SENDGRID_API_KEY}" }
Emails are queued and processed by workers with automatic retries. Configure retry behavior:
[jobs.queues.email]
retries = 5
concurrency = 10 # cluster-wide cap on concurrent email sends
Load Balancer Stickiness
Not every request benefits from sticky sessions, and not every route can tolerate reconnects:
| Traffic | Stickiness | Why |
|---|---|---|
| gRPC unary / regular HTTP (find, create, update, login, admin pages) | Not required | Each request is stateless. Round-robin freely. |
| gRPC Subscribe / Admin SSE (long-lived streams) | Recommended | Reconnects to a different node lose the in-flight subscription state (sequence cursor, filter context). The client has to re-subscribe, which may miss events in the gap. |
With transport = "redis" for live updates, a reconnecting subscriber on a different node will still see all future events — but the state that was held on the original node (current sequence position, any pending-but-undelivered events buffered in the broadcast channel) is gone. Sticky sessions keep that state warm across the connection’s lifetime.
A reasonable default is sticky sessions for /api/* streaming routes and the admin SSE endpoint, round-robin for everything else.
Upgrading to alpha.9
This guide covers the upgrade path from alpha.8 (or earlier) to
alpha.9. It focuses on operator action items first; opt-in features
follow.
TL;DR
- Replace your binary, restart. DB schema migrations apply automatically (idempotent ALTER + CREATE INDEX IF NOT EXISTS).
- Update
crap.tomlif you used[jobs] image_concurrency— the field was removed; use[jobs.queues.images] concurrency = Ninstead. The framework auto-applies a default of2if you don’t set it. - Update
crap.tomlif you set[email] queue_*— the fourqueue_retries/queue_name/queue_timeout/queue_concurrencyfields were removed; use[jobs.queues.email] retries = N,timeout = "...",concurrency = Ninstead. Defaults are identical to alpha.8 (retries = 3,timeout = "30s",concurrency = 5), so you only need to migrate if you customized any of them. - Review multi-step Lua job handlers. Per-CRUD transactions are
now opened independently (pool-mode). Wrap multi-write atomic
sequences in
crap.transaction(fn). - Audit auth methods if you use strategy authentication —
is_locked/verify_emailchecks now apply uniformly across auth surfaces (closed a security gap).
Required action items
1. Remove [jobs] image_concurrency from crap.toml
If present, config load fails with unknown field "image_concurrency".
[jobs]
max_concurrent = 10
- image_concurrency = 4
+
+ [jobs.queues.images]
+ concurrency = 4
If you were happy with the previous default of 2, you can omit the
[jobs.queues.images] block entirely — the framework’s
apply_queue_defaults auto-applies concurrency = 2 to the images
queue when no operator config is present. The default is documented
in [jobs.queues]’s “Framework-supplied defaults” section.
1b. Remove [email] queue_* from crap.toml
If present, config load fails with unknown field "queue_retries"
(or queue_name / queue_timeout / queue_concurrency).
_system_email now reads the same [jobs.queues.<name>] table as
_system_image_convert — one config mechanism for every system job.
[email]
smtp_host = "smtp.example.com"
- queue_retries = 5
- queue_timeout = 60
- queue_concurrency = 8
- queue_name = "email"
+
+ [jobs.queues.email]
+ retries = 5
+ timeout = "1m"
+ concurrency = 8
If you were on alpha.8 defaults (queue_retries = 3,
queue_timeout = 30, queue_concurrency = 5), you can omit the
[jobs.queues.email] block entirely — the framework auto-applies
those exact values via apply_queue_defaults. Per-call overrides
still work: crap.email.queue{ retries = N } wins over the queue
default.
queue_name is dropped without replacement. _system_email
now always uses the queue named "email". If you previously set
[email] queue_name = "<other>" to route email jobs into a custom
queue, rename your [jobs.queues.<other>] block to
[jobs.queues.email].
2. Review multi-step Lua job handlers
Earlier alpha.9 builds wrapped every Lua job handler in a single
outer BEGIN DEFERRED transaction. That model hit
SQLITE_BUSY_SNAPSHOT errors when a handler’s read snapshot
collided with concurrent writers (admin edits, image queue, etc.).
The fix is pool-mode: each Lua CRUD call inside a job handler
opens its own short-lived BEGIN IMMEDIATE transaction. No more
snapshot conflicts. But this means multi-step writes in a single
handler are no longer atomic with each other by default.
If your handler depends on cross-CRUD atomicity:
function M.run(ctx)
+ crap.transaction(function()
crap.collections.posts.update(id_a, { count = 1 })
crap.collections.posts.update(id_b, { count = 2 })
+ end)
end
Most handlers don’t need this — they do a single CRUD op or write to a single document. Inspect handlers that do 2+ writes whose mutual rollback you depended on.
See Transactions in job handlers for the full pattern.
3. (Optional) Review hooks that used implicit cross-step atomicity
The pool-mode shift applies only to job handlers, not to hooks.
Hook code runs inside the parent operation’s write transaction (e.g.
after_change shares the document-update tx). No changes needed
for hooks.
If you’re not sure whether your code is a hook or a job handler —
hooks are registered via crap.hooks.register(...) or per-collection
{ hooks = { before_change = ... } }. Jobs are defined via
crap.jobs.define(...).
4. Security review (auth-related)
These are bug fixes for security gaps that existed in earlier alphas. Review:
- Strategy-authenticated users now pass
is_locked/verify_emailthe same way as bearer / cookie users. If you relied on a strategy hook bypassing these checks, that hole is closed. - Logout invalidates all JWTs for the user, not just the cookie. Active sessions across surfaces die on next request, not at JWT expiry.
Resolution::Invalid(Unaccepted)for cookies/tokens that decode cleanly but whosesession_cookiemethod has been removed from the collection’smethods. Browser cookies are cleared on redirect to login instead of looping.
See the ### Security section of the alpha.9 entry in
CHANGELOG.md at the project root for the full context.
Automatic migrations
The following happen on first startup with the new binary. No manual SQL required.
_crap_jobs schema additions
| Column | Purpose | Migration |
|---|---|---|
priority INTEGER NOT NULL DEFAULT 0 | Scheduling priority | ALTER TABLE ADD COLUMN |
unique_key TEXT | Dedup key for unique option | ALTER TABLE ADD COLUMN |
Plus new indexes: idx_crap_jobs_priority (priority claim ordering)
and idx_crap_jobs_unique_active (partial unique index for dedup).
Both created IF NOT EXISTS.
_crap_image_queue table dropped
The legacy _crap_image_queue table is drained into _crap_jobs as
_system_image_convert jobs, then DROPped. Idempotent — safe on
re-runs and on installs that never had the table.
Operator action if you upgraded a pre-fix alpha.9 build (i.e.
you saw Job definition '_system_image_convert' not found, marking as failed in the logs before this build): the drained jobs were
incorrectly marked failed. Reset them with:
crap-cms images retry --all -y
New uploads on the current build process normally.
Opt-in features (alpha.9)
Job priority
-- At define time (default for all enqueues of this slug):
crap.jobs.define("analytics_rollup", {
handler = "jobs.analytics.rollup",
schedule = "0 3 * * *",
priority = -5, -- run only when queue is otherwise idle
})
-- Per-enqueue override:
crap.jobs.queue("send_password_reset", { user_id = id }, { priority = 10 })
CLI: crap-cms jobs trigger <slug> --priority N.
gRPC: TriggerJobRequest.priority (optional int32).
Job delay
Defer a job’s earliest claim time:
crap.jobs.queue("send_welcome_email", { user_id = id }, { delay = "5m" })
-- or integer seconds:
crap.jobs.queue("send_welcome_email", { user_id = id }, { delay = 300 })
Reuses the existing retry_after column — no new schema. Combines
with priority and unique.
Unique jobs (dedup)
Don’t queue a duplicate if one is already pending or running:
local job_id = crap.jobs.queue(
"reindex_collection",
{ slug = "posts" },
{ unique = "reindex:posts" }
)
If another reindex_collection job with unique = "reindex:posts"
is already pending or running, queue() returns that job’s id —
not a new one. Completed and failed jobs don’t block re-enqueue.
Per-queue concurrency, timeout, and retry defaults
Throttle aggregate work and supply timeout / retry defaults for jobs in a queue independent of per-slug caps:
[jobs.queues]
emails = { concurrency = 4, timeout = "1m" }
images = { concurrency = 2 } # framework defaults: timeout = 5m, retries = 2
reports = { concurrency = 1, timeout = "30m", retries = 0 }
| Field | Meaning |
|---|---|
concurrency | Max concurrent runs in this queue. 0 = unlimited. |
timeout | Per-job wall-clock timeout for system jobs (_system_image_convert, _system_email) that lack their own JobDefinition. Accepts seconds or human-readable. |
retries | Default max_attempts for jobs in this queue, expressed as retries (total attempts = retries + 1). Used by system jobs AND by user Lua jobs that omit retries in crap.jobs.define. Explicit JobDefinition.retries (including retries = 0) overrides the queue default. crap.email.queue{ retries = N } overrides for that one call. |
Partial overrides merge field-by-field — supplying only concurrency
leaves the framework’s timeout / retries defaults intact. The
framework ships sensible images defaults (concurrency = 2,
timeout = "5m", retries = 2); operator config wins on a per-field
basis.
Concurrency caps are cluster-wide (counted from the shared DB),
composing with global max_concurrent and per-slug
JobDefinition::concurrency (strictest wins). See Concurrency model
in jobs.md.
Earlier alpha.9 builds hardcoded the image-convert timeout at 120s. Large originals on slow storage hit that ceiling. Upgrade and adjust
[jobs.queues.images] timeoutif your workload needs more (the new framework default is5m).
Reach for retries. Resolution at queue time, strictest-explicit
wins:
JobDefinition.retriesset explicitly incrap.jobs.define(any value, including0).[jobs.queues.<queue>] retriesfromcrap.tomlwhen (1) is omitted.0(one attempt) when neither is set.
So an operator who writes [jobs.queues.reports] retries = 5 and a
user who registers crap.jobs.define("rollup", { queue = "reports" })
without retries gets 6 total attempts per rollup — symmetric with how
system jobs inherit from [jobs.queues.email] /
[jobs.queues.images].
crap.email.queue{ retries = N } is the only per-call retry override
on the Lua surface; crap.jobs.queue for user jobs accepts
priority / delay / unique (no retries).
Reach for timeout. Applies to system jobs only —
_system_image_convert reads [jobs.queues.images] timeout,
_system_email reads [jobs.queues.email] timeout. User Lua jobs
use the timeout declared on their JobDefinition (60 if
omitted).
Priority decay (aging-based promotion)
Prevent backlog starvation of low-priority jobs:
[jobs]
priority_decay = "1m" # +1 effective priority per minute waiting
After enough wait time, an old low-priority job overtakes fresh
higher-priority jobs. 0 (default) disables decay — pure static
priority + FIFO.
crap.transaction(fn) for explicit atomicity
Already covered in Required action items. Use this when a job handler needs multi-step atomicity in pool-mode.
Notable changes (non-breaking)
- gRPC:
TriggerJobRequest.priority(optionalint32),GetJobRunResponse.priority(int32),GetJobRunResponse.unique_key(optionalstring). - CLI:
crap-cms jobs trigger <slug> --priority Ncrap-cms jobs status— newPriocolumncrap-cms images list— newPriocolumncrap-cms images retry --priority N
- Image conversion runs in the unified
_crap_jobsqueue as_system_image_convertsystem jobs (operator-visible viacrap-cms jobs status --slug _system_image_convertif needed, thoughcrap-cms images list / stats / retry / purgestill work unchanged). - Postgres + SQLite job-claim paths unified. Same observable behavior across backends; strict global priority ordering; identical per-slug and per-queue cap enforcement.
Reference
CHANGELOG.mdat the project root — the full alpha.9 entry with every change, including non-job-related items not covered here.- Jobs documentation
- crap.toml reference