CLI Reference
mantle — Serverless TypeScript framework CLI.
npx mantle <command> [flags]
# or install globally: pnpm add -g @mantleframework/cliBuild & Deploy
mantle build
Bundle Lambda functions with esbuild.
| Flag | Description |
|---|---|
-w, --watch | Watch for changes and rebuild |
-f, --function <name> | Build a specific function only |
--analyze | Generate bundle analysis metafiles |
--sourcemap | Generate source maps |
--no-minify | Skip minification |
Scans src/lambdas/, outputs build/lambdas/<Name>/index.mjs. Target: Node.js 24 / ESM.
mantle dev
Start a local development server with hot reload. Watches src/lambdas/, simulates API Gateway routing locally.
mantle deploy
Deploy via OpenTofu.
mantle deploy --stage staging
mantle deploy --stage production| Flag | Description |
|---|---|
--stage <env> | Target stage — required (dev, staging, production) |
Runs tofu init, tofu plan, tofu apply. Requires AWS credentials. Never run without --stage — dev has no tfvars and prompts interactively.
Generate
Alias: mantle g <subcommand>
mantle generate infra
Generate OpenTofu configuration from project structure and mantle.config.ts.
| Flag | Description |
|---|---|
--modules-path <path> | Path to mantle modules (auto-detected if omitted) |
Scans src/lambdas/, derives API routes from filesystem, auto-wires env vars from getRequiredEnv() / getOptionalEnv() calls. Safe to run repeatedly — skips ejected files.
mantle generate permissions
Extract @RequiresTable metadata and generate least-privilege DSQL permissions.
| Flag | Default | Description |
|---|---|---|
--entity-dir <dir> | src/entities/queries | Entity queries directory |
--output-dir <dir> | build | Build output directory |
--terraform-dir <dir> | infra | Terraform output directory |
--permissions-dir <dir> | permissions | Permissions output directory |
mantle generate openapi
Generate an OpenAPI 3.1 specification from defineApiHandler metadata. Resolves Zod request/response schemas end-to-end via esbuild bundling and sibling extraction, producing fully-typed components/schemas with $ref operation bodies. Error responses are derived from each handler's auth mode and emitted as $refs to Models.ErrorResponse / Models.UnauthorizedError / Models.ForbiddenError / Models.InternalServerError when those schemas are sibling-extracted.
| Flag | Default | Description |
|---|---|---|
--output <path> | openapi.json | Output file path. Extension controls format — .json emits JSON, .yaml/.yml emits YAML. |
--title <title> | API | API title |
--version <version> | 1.0.0 | API version |
--server-url <url> | — | Optional server URL in info.servers[0].url |
--schema-prefix <prefix> | — | Prepend a namespace to every component name (e.g., Models.). The Schema suffix is stripped first, so fileListResponseSchema becomes Models.FileListResponse. Preserves TypeSpec-era naming for iOS/Swift consumers. |
--html <path> | — | Also write a Redoc HTML docs bundle to the given path. Uses @redocly/cli build-docs under the hood (auto-installed via npx). |
--verbose | false | Print per-schema resolution diagnostics — which schemas resolved, which fell back to placeholders, and which inline handler-body schemas were promoted. |
Default error response behavior
buildOperation computes the default error set from the handler's auth mode:
| Auth mode | Status codes emitted |
|---|---|
none (or unset) | 200, 400, 500 |
bearer | 200, 400, 401, 500 |
session | 200, 400, 401, 500 |
authorizer | 200, 400, 401, 403, 500 |
Each error code is only emitted when its matching component schema is present in the resolved schema set, so instances without an api-schema/schemas.ts barrel degrade gracefully to 200-only responses instead of producing broken $refs. The component name mapping is fixed:
400→ErrorResponse401→UnauthorizedError403→ForbiddenError500→InternalServerError
Per-handler error override
Any handler may override the auth-derived defaults via openapi.errors:
const api = defineApiHandler({
auth: 'bearer',
openapi: {
summary: 'Fetch by ID',
errors: [400, 404, 500] // omits 401 even though auth is bearer
}
})The extractor parses the array literal via ts-morph; only integer literals are supported. Unknown codes (those without a ERROR_RESPONSES mapping) are silently dropped — useful for documenting non-standard codes in prose without producing broken refs.
Query parameters
defineApiHandler({ querySchema: MyQuerySchema }) emits OpenAPI parameters: [{in: 'query', ...}] — not requestBody. Each top-level property of the resolved query schema becomes a separate query parameter entry with its constraints (type, enum, minLength, etc.). Query parameters are appended after any path parameters on the same operation.
$ref promotion
After resolving all schemas to JSON Schema, the generator promotes inlined sub-schemas to $ref pointers when they are structurally identical to a top-level component. This produces clean Swift types (e.g., [HealthQuantity] instead of [HealthSyncRequestPayload.QuantitiesItem]). Self-matches are skipped — a component never $refs itself.
Schema resolution notes
- Sibling extraction: schemas imported via
import * as allsurface every exported Zod schema in the module, so barrel files likesrc/types/api-schema/schemas.tsexpose sub-schemas as named components even when no handler references them directly. - Inline handler schemas:
const Schema = z.object(...)declared inside a handler body is promoted toexport constat bundle time and resolved as a top-level component. - Zod identity: the generator bundles each schema together with its
toJSONSchema()call via esbuild to avoid cross-packageinstanceofmismatches between different Zod copies. Do notimport { z } from 'zod'directly in handler files — use@mantleframework/validation's re-export so all schemas share one Zod instance. format: date-time: Zod 4'sz.string().datetime()natively emitsformat: "date-time"viatoJSONSchema(). Use.datetime()on timestamp schema fields to get proper date formatting in the spec.
mantle generate handler <Name>
Scaffold a new Lambda handler with matching test file.
| Flag | Default | Description |
|---|---|---|
--trigger <type> | api | Trigger type: api, sqs, s3, schedule, authorizer |
mantle generate entity <name>
Scaffold a Drizzle entity schema.
| Flag | Description |
|---|---|
--fields <fields> | Comma-separated name:type pairs (types: string, number, boolean, timestamp, uuid) |
--queries | Also generate entity query class with @RequiresTable methods |
mantle generate migration <name>
Create a timestamped migration SQL file in migrations/.
mantle generate graph
Generate file-level dependency graph to build/graph.json. Auto-run during mantle build.
mantle generate graph:knowledge
Generate GraphRAG knowledge graph to graphrag/knowledge-graph.json.
mantle generate hooks
Generate Husky git hooks.
| Flag | Description |
|---|---|
--no-pre-commit | Skip pre-commit hook |
--no-pre-push | Skip pre-push hook |
mantle generate ci-templates
Generate GitHub Actions CI/CD workflow files (.github/workflows/).
| Flag | Description |
|---|---|
--node-version <version> | Node.js version |
mantle generate agents
Generate AGENTS.md for AI assistants. Preserves content between <!-- CUSTOM:START --> and <!-- CUSTOM:END --> markers.
mantle generate repomix
Generate repomix.config.json for AI context packing (XML format, tree-sitter compression).
mantle generate deps-config
Generate .dependency-cruiser.cjs with Mantle architecture rules.
mantle generate integration-tests
Generate integration test scaffold with Docker Compose (LocalStack + PostgreSQL).
mantle generate knip-config
Generate knip.config.ts with Mantle-aware entry points for dead code detection.
Database
mantle db migrate
Run pending migrations using the Mantle migration runner.
| Flag | Default | Description |
|---|---|---|
--folder <path> | ./migrations | Migrations folder |
--provider <type> | auto-detected | aurora-dsql, aurora-serverless-v2, neon |
--endpoint <url> | DSQL_ENDPOINT env | DSQL cluster endpoint |
--connection-string <url> | DATABASE_URL env | Connection string (non-DSQL) |
--region <region> | AWS_REGION env | AWS region |
--no-lock | — | Skip migration lock |
Auto-detects endpoint and region from Terraform state when infra/ is initialized.
mantle db generate
Generate migration file from schema diff (wraps drizzle-kit generate).
| Flag | Description |
|---|---|
--name <name> | Migration file name |
--custom | Generate empty migration for manual SQL |
--prefix <type> | File prefix: index, timestamp, unix, none |
mantle db check-dsql
Classify migration statements for Aurora DSQL compatibility.
| Flag | Default | Description |
|---|---|---|
--migrations-dir <path> | ./migrations | Migrations directory |
Output labels: OK (compatible), INDEX (auto-converted to ASYNC), STRIP (skipped — DSQL-unsupported), RECREATION (requires table recreation).
mantle db apply-permissions
Apply DSQL role permissions from permissions/ folder.
| Flag | Default | Description |
|---|---|---|
--folder <path> | ./permissions | Permissions folder |
--endpoint <url> | DSQL_ENDPOINT env | DSQL endpoint |
--region <region> | AWS_REGION env | AWS region |
mantle db push
Push schema directly to the database (dev only, wraps drizzle-kit push).
mantle db studio
Open Drizzle Studio (wraps drizzle-kit studio).
Quality
mantle ci
Run the full local CI pipeline.
| Flag | Description |
|---|---|
--full | Add integration tests and extended quality checks |
--step <number> | Run a specific step only |
Phases: Setup → Build → Validate → Test → Quality → Integration (full only). Exits non-zero on any CRITICAL or HIGH failure. Missing tools (ShellCheck, tofu) are skipped gracefully.
mantle check
Validate codebase against 20 convention rules via ts-morph.
| Flag | Description |
|---|---|
--fast | CRITICAL rules only |
--severity <level> | Minimum severity: CRITICAL, HIGH, MEDIUM |
--rule <name> | Run one specific rule |
mantle check deps
Enforce dependency architecture rules (no handler-to-handler imports, no circular deps, entity/service isolation).
mantle check bundles
Check Lambda bundle sizes against thresholds.
| Flag | Default | Description |
|---|---|---|
--threshold <bytes> | 5000000 | Max bundle size in bytes |
--json | — | JSON output for CI |
mantle check dead-code
Detect unused exports via Knip. Generate config first with mantle generate knip-config.
mantle check test-output [file]
Validate test output for problematic patterns (EMF metrics on stdout, unhandled rejections, deprecation warnings). Reads from stdin if no file given.
MCP Server
mantle mcp-server
Start the Model Context Protocol server for AI-assisted development (Claude Code, Cursor, etc.).
Provides 19 tools across Validation, Infrastructure, Reference, Workflow, Data Queries, and Performance categories.