Introduction & Language Tour
TypeSpec (.tsp) is a concise, declarative API and data modeling language that feels natural to Dart and Flutter developers. Aegil compiles these high-level specifications directly into Serverpod PostgreSQL tables, zero-trust authorization filters, cross-stack validation logic, and reactive Flutter BLoCs.
The Specification Language guide
Section titled “The Specification Language guide”Explore the complete language reference:
- Types, Nullability & Enums: Primitive scalars, nullability syntax (
?), and enums. - Models, Entities & Relations: Database tables, primary keys, and foreign keys.
- Operations: Queries, Mutations & Streams:
@autoQuery,@autoMutation,@autoStream, and@mutation. - Validation & Constraints: Field bounds (
minLength,max, regex patterns). - Access Control & CEL Policies: Row-level security rules and CEL expressions.
- State Machines & Lifecycle: Finite state machines and lifecycle transitions.
- Platforms & Permissions: Native platform shells and device permissions.
- Keywords & Decorators Reference: Full syntax reference table.
Why TypeSpec? (The Dart perspective)
Section titled “Why TypeSpec? (The Dart perspective)”Dart developers are accustomed to strong typing, sound null safety, and expressive metadata annotations (@override, @immutable, @JsonSerializable).
TypeSpec brings that exact clarity to full-stack modeling. Instead of writing verbose YAML schemas or repetitive ORM classes in multiple languages, you write clean, declarative declarations in specs/<feature>/*.tsp.
namespace Helpdesk;
@entity({ table: "tickets" })model Ticket { @pk id: uuid;
@owner reporterId: uuid;
@validate({ minLength: 5, maxLength: 100 }) title: string;
status: TicketStatus = TicketStatus.Open;
createdAt: utcDateTime;}If you can write a Dart class, you already understand TypeSpec.
Feature folder organization (specs/<feature>/*.tsp)
Section titled “Feature folder organization (specs/<feature>/*.tsp)”Aegil organizes domain specifications into modular feature folders:
specs/ app.tsp # Project identity and global metadata platforms.tsp # Target platforms (@platform) & device permissions (@permission) helpdesk/ # Feature folder helpdesk.tsp # Ticket model, queries, mutations comments.tsp # Optional sub-domain models for helpdesk billing/ # Another feature folder subscriptions.tsp # Invoices, plans, billing operationsThe root boundary rule: Only root configuration (
app.tspandplatforms.tsp) may live directly inspecs/. All domain models, queries, and mutations must be placed inside a feature subfolder (e.g.specs/helpdesk/helpdesk.tsp). Placing domain specs directly atspecs/tickets.tspwill be rejected by the compiler withERR_SPEC_MISPLACED.
Type mappings: TypeSpec to Dart and PostgreSQL
Section titled “Type mappings: TypeSpec to Dart and PostgreSQL”Aegil maps TypeSpec types directly to idiomatic Dart types and PostgreSQL database columns:
| TypeSpec Type | Dart Type (package:uuid, dart:core) |
PostgreSQL Column Type | Example Value |
|---|---|---|---|
string |
String |
text |
"Hello world" |
int / int32 |
int |
integer |
42 |
int64 |
int |
bigint |
9007199254740991 |
float / float64 |
double |
double precision |
3.14159 |
boolean |
bool |
boolean |
true, false |
uuid |
UuidValue (or String representation) |
uuid |
"123e4567-e89b-12d3-a456-426614174000" |
utcDateTime |
DateTime |
timestamp with time zone |
DateTime.now().toUtc() |
T? |
T? (nullable) |
nullable column | null |
T[] |
List<T> |
jsonb array or relation target |
["dart", "flutter"] |
Page<T> |
Page<T> (cursor pagination) |
query result with next cursor | Page(items: [...], nextCursor: "...") |
enum |
Dart enum (lowerCamelCase values) |
text (serialized by name) |
TicketStatus.open |
Models and Entities
Section titled “Models and Entities”In TypeSpec, model defines a structured data type. Decorating a model with @entity({ table: "..." }) tells Aegil that this model is backed by a PostgreSQL database table:
@entity({ table: "tickets" })model Ticket { @pk id: uuid;
@owner reporterId: uuid;
@index assignedAgentId?: uuid;
@validate({ minLength: 3, maxLength: 80 }) title: string;
description?: string;
createdAt: utcDateTime;}What Aegil generates from this model:
Section titled “What Aegil generates from this model:”- Serverpod Server Model: A
.spy.yamlfile and Dart model class with table mapping, foreign keys, and indexes. - PostgreSQL Migration: DDL statements creating the
ticketstable with primary keys, indexes, and nullability constraints. - Client Protocol Model: A typed Dart class in
package:<app>_flutter/api.dartwithfromJson,toJson, and copy methods. - Validation Logic: Both client-side and server-side checks enforcing that
titleis between 3 and 80 characters.
Decorators as Dart annotations
Section titled “Decorators as Dart annotations”In Dart, you use annotations like @override or @JsonKey(name: 'first_name') to attach metadata for the compiler or code generators. In TypeSpec, decorators (starting with @) serve the exact same role.
| TypeSpec Decorator | Equivalent Concept in Dart / Serverpod | What it tells Aegil |
|---|---|---|
@entity({ table: "name" }) |
Serverpod table model (table: name) |
Back this model with a PostgreSQL table. |
@pk |
Primary key (id: uuid or id: int32) |
Use this field as the primary key. |
@owner |
Owner identification | Designates caller ownership field for zero-trust security checks. |
@index |
Serverpod database index | Create a PostgreSQL index for fast querying. |
@validate({ minLength, maxLength, min, max }) |
Custom validator or assert | Generate boundary assertions on both client and server. |
@relation({ name, target, kind }) |
Foreign key relationship | Establish a oneToMany or manyToOne relationship. |
@policy({ read, write, delete }) |
Row-Level Security (RLS) | Restrict data access via CEL expressions compiled into SQL WHERE clauses. |
@stateMachine({ field, states, transitions }) |
Finite State Machine (FSM) | Enforce valid state transitions and guard rules. |
@public |
Public API endpoint | Bypass session authentication checks. |
@health({ path }) |
Health check route | Expose a lightweight HTTP liveness check route (e.g. /health). |
Enums: TypeSpec vs. Dart
Section titled “Enums: TypeSpec vs. Dart”Enums are declared cleanly in TypeSpec and compile to idiomatic Dart enums with lowerCamelCase member names:
enum TicketStatus { Open, InProgress, Resolved, Closed,}In Dart, this generates:
enum TicketStatus { open, inProgress, resolved, closed;}Aegil configures Serverpod to serialize enums by name (serialized: byName), keeping your database readable and portable.
Declaring Operations (op)
Section titled “Declaring Operations (op)”In traditional development, creating an endpoint requires defining route paths, HTTP verbs, payload serializers, error handlers, and client methods.
In TypeSpec, you declare operations as concise function signatures:
1. Automatic Queries with Cursor Pagination (@autoQuery)
Section titled “1. Automatic Queries with Cursor Pagination (@autoQuery)”@autoQuery({ entity: "Ticket", paginate: "cursor", filterBy: ["status", "assignedAgentId"], sortBy: ["createdAt"]})op listTickets(limit?: int, status?: TicketStatus): Page<Ticket>;2. Automatic Mutations (@autoMutation)
Section titled “2. Automatic Mutations (@autoMutation)”@autoMutation({ entity: "Ticket", action: "create", touches: ["Ticket"] })op createTicket(title: string, description?: string): Ticket;
@autoMutation({ entity: "Ticket", action: "update", touches: ["Ticket"] })op updateTicket(id: uuid, title?: string, description?: string): Ticket;
@autoMutation({ entity: "Ticket", action: "delete", touches: ["Ticket"] })op deleteTicket(id: uuid): boolean;3. Custom Business Mutations (@mutation)
Section titled “3. Custom Business Mutations (@mutation)”@mutation({ touches: ["Ticket"] })op escalateTicket(ticketId: uuid, assignedAgentId: string): Ticket;Aegil marks this operation as an agentTask in the Action Manifest and generates a hook interface in hooks/escalate_ticket_hook.dart for you or your AI agent to implement.
What could go wrong?
Section titled “What could go wrong?”| What you see | Why | What to do |
|---|---|---|
ERR_SPEC_MISPLACED |
A domain spec file was placed in specs/ root rather than specs/<feature>/. |
Move domain specs into specs/<feature>/<feature>.tsp. Only app.tsp and platforms.tsp belong at root. |
ERR_NAMESPACE_MISMATCH |
The namespace declared in .tsp does not match aegil.yaml. |
Ensure every .tsp file uses the exact namespace configured in aegil.yaml. |
ERR_DUPLICATE_DECLARATION |
Two models, enums, or operations share the same name across .tsp files. |
Rename one of the declarations to be unique. |
ERR_VALIDATION_SYNTAX |
A @validate decorator has invalid bounds (e.g. min > max or minLength < 0). |
Correct the validation arguments in the .tsp file. |
Next steps
Section titled “Next steps”- Learn Models, Entities & Relations.
- Learn Field Validation & Bounds.
- Learn Row-Level Security & Policies.
- Learn State Machines & Workflows.
- Learn Native Platforms & Device Permissions.