Outline
TypeScript possesses the worldโs most powerful type system and the most expansive ecosystem.
The AI-powered no-code agent @autobe
generates backend applications written in TypeScript. The reason @autobe
adopted TypeScript is because of its powerful compiler support, plugin system capabilities, and vast ecosystem.
First, TypeScript has the most powerful and strict type system among existing backend languages, and itโs the only one in the world that can embed its compiler in applications and utilize it at the API level. When validating AI-generated code, being able to guarantee stability at the compiler level is extremely important. And this compiler must be available at the API level so that agents can continuously validate AI-written code and provide compilation errors as feedback to the LLM for improvement.
Second, TypeScriptโs plugin system enables powerful compiler extensions that are crucial for AI-driven development workflows. @autobe
extensively leverages AI function calling through complex AST (Abstract Syntax Tree) structures, and uses TypeScriptโs plugin system via the typia
library to automatically convert TypeScript types into AI function calling schemas. This eliminates the operational complexity of manually managing intricate JSON schemas for AI function calling.
Additionally, TypeScript (JavaScript) has the worldโs largest ecosystem. One language can develop backend servers, front/mobile/desktop applications, and even AI agents. In fact, @autobe
developed both its Agent system and Playground application entirely in TypeScript. Furthermore, @agentica
which transforms backend applications generated by @autobe
into AI chatbots, and @autoview
which converts them into frontend applications, were all developed based on the TypeScript language characteristics.
Powerful Type System
TypeScript possesses the most powerful type system among existing backend languages, providing the revolutionary advantage of ensuring backend server application stability at compile time to a significant degree. Without actually running the server and performing runtime tests, TypeScriptโs compiler can verify the type safety of code and discover potential errors in advance.
For no-code AI agents, this compile-time validation capability is absolutely critical. AI-generated code often contains subtle errors, inconsistencies, or type mismatches that would be difficult to detect through manual review. With TypeScriptโs compile-time verification, these issues can be caught immediately during the code generation process, allowing the AI agent to iteratively refine the code until it passes all type checks. This creates a tight feedback loop where the AI can learn from compilation errors and continuously improve the generated code quality without requiring expensive runtime testing or manual debugging sessions.
This difference becomes stark when compared to other backend languages. Languages like Java, Python, Ruby, and Go lack TypeScriptโs sophisticated type system, making it difficult to be confident that code is correctly written until actually running the server application and performing runtime tests in various scenarios. Particularly for dynamically typed languages like Python or Ruby, type-related errors are frequently discovered only in production environments.
TypeScriptโs type system can verify the correctness of complex business logic at compile time through advanced features such as Structural Typing, Conditional Types, Template Literal Types, and Mapped Types. This type system is so powerful that it has been proven to be Turing Complete, reaching a level where programming is possible at the type level.
For more detailed information about TypeScriptโs type system features, refer to the official documentation (https://www.typescriptlang.org/docs/handbook/2/types-from-types.htmlย ) and TypeScript Deep Dive (https://basarat.gitbook.io/typescript/ย ).
Most importantly, TypeScript fully exposes its compiler API for programmatic access. This enables real-time validation of AI-generated code and allows compilation errors to be provided as feedback to LLMs for code improvement. This characteristic is an essential feature for AI-based code generation tools like @autobe
, and represents a unique strength of TypeScript not found in other languages.
Plugin System
TypeScriptโs plugin system enables powerful compiler extensions that are crucial for AI-driven development workflows.
@autobe
extensively leverages AI function calling across all domains. Rather than having AI generate programming code as raw text, @autobe
employs a sophisticated approach where AI generates our custom-designed AST (Abstract Syntax Tree) structures through function calling. This AST data is then validated and used to provide feedback to the AI, with the final completed AST being transformed into Prisma/TypeScript code.
The AST structures used by @autobe
are incredibly deep and complex in their hierarchy, requiring extensive and intricate descriptions to help AI understand the context. Managing JSON schemas for AI function calling through traditional development methodologiesโwhether hand-written or duplicated through reflectionโwould be operationally unfeasible given this complexity.
AutoBePrisma.IApplication
: AST structure for Prisma database schema designAutoBeOpenApi.IDocument
: AST structure for RESTful API design
To solve this challenge, @autobe
utilizes TypeScriptโs plugin system through the typia
library, which extends compilation capabilities by automatically converting TypeScript types into AI function calling schemas. typia
analyzes TypeScript source code at the compiler level and automatically generates appropriate AI function calling schemas for each AST type.
This represents another decisive factor in why the WrtnLabs team chose TypeScript for @autobe
development.
Schema Generation
import { AutoBeOpenApi, AutoBePrisma } from "@autobe/prisma";
import { ILlmApplication } from "@samchon/openapi";
import typia from "typia";
const app: ILlmApplication<"chatgpt"> = typia.llm.application<
ICodeGenerator,
"chatgpt",
{ reference: true }
>();
console.log(app);
interface ICodeGenerator {
/**
* Generate Prisma AST application for database schema design.
*/
generatePrismaSchema(app: AutoBePrisma.IApplication): void;
/**
* Generate OpenAPI document for RESTful API design.
*/
generateOpenApiDocument(app: AutoBeOpenApi.IDocument): void;
}
undefined
import { tags } from "typia";
import { CamelPattern } from "../typings";
import { SnakePattern } from "../typings/SnakePattern";
/**
* AST type system for programmatic Prisma ORM schema generation through AI
* function calling.
*
* This namespace defines a comprehensive Abstract Syntax Tree structure that
* enables AI agents to construct complete Prisma schema files at the AST level.
* Each type corresponds to specific Prisma Schema Language (PSL) constructs,
* allowing precise control over generated database schemas while maintaining
* type safety and business logic accuracy.
*
* ## Core Purpose
*
* The system is designed for systematic generation where AI function calls
* build database schemas step-by-step, mapping business requirements to
* executable Prisma schema code. Instead of generating raw PSL strings, AI
* agents construct structured AST objects that represent:
*
* - Complete database schemas organized by business domains
* - Properly typed models with relationships and constraints
* - Performance-optimized indexes for common query patterns
* - Business-appropriate data types and validation rules
*
* ## Architecture Overview
*
* - **IApplication**: Root container representing the entire database schema
* - **IFile**: Domain-specific schema files organized by business functionality
* - **IModel**: Database tables representing business entities with full
* relationship mapping
* - **Fields**: Primary keys, foreign keys, and business data fields with proper
* typing
* - **Indexes**: Performance optimization through unique, regular, and full-text
* search indexes
*
* ## Domain-Driven Schema Organization
*
* Schemas are typically organized into multiple domain-specific files following
* DDD principles:
*
* - Core/System: Foundation entities and application configuration
* - Identity: User management, authentication, and authorization
* - Business Logic: Domain-specific entities and workflows
* - Transactions: Financial operations and payment processing
* - Communication: Messaging, notifications, and user interactions
* - Content: Media management, documentation, and publishing systems
* - Analytics: Reporting, metrics, and business intelligence data
*
* ## Database Design Patterns
*
* The generated schemas follow enterprise-grade patterns:
*
* - UUID primary keys for distributed system compatibility and security
* - Snapshot/versioning tables for audit trails and data history
* - Junction tables for many-to-many relationship management
* - Materialized views for performance optimization of complex queries
* - Soft deletion patterns with timestamp-based lifecycle management
* - Full-text search capabilities using PostgreSQL GIN indexes
*
* Each generated schema reflects real business workflows where entities
* maintain proper relationships, data integrity constraints, and performance
* characteristics suitable for production applications handling complex
* business logic and high query volumes.
*
* @author Samchon
*/
export namespace AutoBePrisma {
/**
* Root interface representing the entire Prisma application schema.
*
* Contains multiple schema files that will be generated, typically organized
* by business domain. Based on the uploaded schemas, applications usually
* contain 8-10 files covering different functional areas like user
* management, sales, orders, etc.
*/
export interface IApplication {
/**
* Array of Prisma schema files to be generated.
*
* Each file represents a specific business domain or functional area.
* Examples from uploaded schemas: systematic (channels/sections), actors
* (users/customers), sales (products/snapshots), carts, orders, coupons,
* coins (deposits/mileage), inquiries, favorites, and articles (BBS
* system).
*/
files: IFile[];
}
/**
* Interface representing a logical grouping of database tables organized by
* business domain for schema file generation.
*
* Components provide a systematic way to organize database tables into
* coherent groups following domain-driven design principles. Each component
* represents a specific business domain or functional area that will be
* generated as a separate Prisma schema file, ensuring maintainable and
* logically structured database architecture.
*
* This interface is primarily used during the database design phase when the
* Prisma agent analyzes requirements and determines the complete scope of
* tables needed, then organizes them into logical groups based on business
* relationships and functional dependencies.
*
* ## Usage in Schema Generation Process
*
* Components serve as the blueprint for generating multiple Prisma schema
* files:
*
* 1. **Requirements Analysis**: AI agent identifies all required tables from
* business requirements
* 2. **Domain Grouping**: Tables are organized into components based on business
* domains and functional relationships
* 3. **File Generation**: Each component becomes a separate .prisma file
* containing related models
* 4. **Dependency Management**: Components are ordered to handle cross-domain
* relationships properly
*
* ## Domain Organization Examples
*
* Based on typical business applications, components commonly include:
*
* - **Systematic**: Core system tables (channels, sections, configurations)
* - **Actors**: User management (customers, citizens, administrators)
* - **Sales**: Product catalog and sales entities
* - **Carts**: Shopping cart and item management
* - **Orders**: Order processing and fulfillment
* - **Coupons**: Discount and promotion systems
* - **Coins**: Digital currency and mileage systems
* - **Inquiries**: Customer support and FAQ systems
* - **Favorites**: User preference and wishlist management
* - **Articles**: Content management and BBS systems
*
* ## Relationship to {@link AutoBePrisma.IFile}
*
* Each IComponent serves as a blueprint for generating one IFile during the
* schema generation process. The component's metadata (filename, namespace,
* tables) is used to structure the actual Prisma schema file with proper
* models, relationships, and indexes.
*
* @see IFile For the actual schema file structure generated from components
* @see AutoBePrismaComponentsEvent For the event that delivers component
* organization results
*/
export interface IComponent {
/**
* Target filename for the Prisma schema file containing this component's
* tables.
*
* Follows the naming convention `schema-{number}-{domain}.prisma` where the
* number indicates dependency order and domain represents the business
* area.
*/
filename: string & tags.Pattern<"^[a-zA-Z0-9._-]+\\.prisma$">;
/**
* Business domain namespace that groups related models.
*
* Used in Prisma documentation comments as "@\namespace directive".
* Examples from uploaded schemas: "Systematic", "Actors", "Sales", "Carts",
* "Orders", "Coupons", "Coins", "Inquiries", "Favorites", "Articles"
*/
namespace: string;
/**
* Initial thoughts on why these tables belong together.
*
* **Example:**
*
* "These tables all relate to user management and authentication.
* They share common patterns like user identification and access control."
*/
thinking: string;
/**
* Review considerations for this component grouping.
*
* **Example:**
*
* "Reviewed relationships with other domains. While customers create orders,
* the customer entity itself is fundamentally about user identity, not sales."
*/
review: string;
/**
* Final rationale for this component's composition.
*
* **Example:**
*
* "This component groups all actor-related tables to maintain a clear
* separation between identity management and business transactions."
*/
rationale: string;
/**
* Array of table names that will be included in this component's schema
* file.
*
* Contains all database table names that belong to this business domain,
* ensuring logical grouping and proper organization of related data
* structures.
*/
tables: Array<string & SnakePattern> & tags.MinItems<1>;
}
/**
* Interface representing a single Prisma schema file within the application.
*
* Each file focuses on a specific business domain and contains related
* models. File organization follows domain-driven design principles as seen
* in the uploaded schemas.
*/
export interface IFile {
/**
* Name of the schema file to be generated.
*
* Should follow the naming convention: "schema-{number}-{domain}.prisma"
* Examples: "schema-02-systematic.prisma", "schema-03-actors.prisma" The
* number indicates the dependency order for schema generation.
*/
filename: string & tags.Pattern<"^[a-zA-Z0-9._-]+\\.prisma$">;
/**
* Business domain namespace that groups related models.
*
* Used in Prisma documentation comments as "@\namespace directive".
* Examples from uploaded schemas: "Systematic", "Actors", "Sales", "Carts",
* "Orders", "Coupons", "Coins", "Inquiries", "Favorites", "Articles"
*/
namespace: string;
/**
* Array of Prisma models (database tables) within this domain.
*
* Each model represents a business entity or concept within the namespace.
* Models can reference each other through foreign key relationships.
*/
models: IModel[] & tags.MinItems<1>;
}
/**
* Interface representing a single Prisma model (database table).
*
* Based on the uploaded schemas, models follow specific patterns:
*
* - Main business entities (e.g., shopping_sales, shopping_customers)
* - Snapshot/versioning entities for audit trails (e.g.,
* shopping_sale_snapshots)
* - Junction tables for M:N relationships (e.g.,
* shopping_cart_commodity_stocks)
* - Materialized views for performance (prefixed with mv_)
*/
export interface IModel {
/**
* Name of the Prisma model (database table name).
*
* MUST use snake_case naming convention. Examples: "shopping_customers",
* "shopping_sale_snapshots", "bbs_articles" Materialized views use "mv_"
* prefix: "mv_shopping_sale_last_snapshots"
*/
name: string & SnakePattern;
/**
* Detailed description explaining the business purpose and usage of the
* model.
*
* Should include:
*
* - Business context and purpose
* - Key relationships with other models
* - Important behavioral notes or constraints
* - References to related entities using "{@\link ModelName}" syntax
*
* **IMPORTANT**: Description must be written in English. Example: "Customer
* information, but not a person but a **connection** basis..."
*/
description: string;
/**
* Indicates whether this model represents a materialized view for
* performance optimization.
*
* Materialized views are read-only computed tables that cache complex query
* results. They're marked as "@\hidden" in documentation and prefixed with
* "mv_" in naming. Examples: mv_shopping_sale_last_snapshots,
* mv_shopping_cart_commodity_prices
*/
material: boolean;
/**
* Specifies the architectural stance of this model within the database
* system.
*
* This property defines how the table positions itself in relation to other
* tables and what role it plays in the overall data architecture,
* particularly for API endpoint generation and business logic
* organization.
*
* ## Values:
*
* ### `"primary"` - Main Business Entity
*
* Tables that represent core business concepts and serve as the primary
* subjects of user operations. These tables typically warrant independent
* CRUD API endpoints since users directly interact with these entities.
*
* **Key principle**: If users need to independently create, search, filter,
* or manage entities regardless of their parent context, the table should
* be primary stance.
*
* **API Requirements:**
*
* - Independent creation endpoints (POST /articles, POST /comments)
* - Search and filtering capabilities across all instances
* - Direct update and delete operations
* - List/pagination endpoints for browsing
*
* **Why `bbs_article_comments` is primary, not subsidiary:**
*
* Although comments belong to articles, they require independent
* management:
*
* - **Search across articles**: "Find all comments by user X across all
* articles"
* - **Moderation workflows**: "List all pending comments for review"
* - **User activity**: "Show all comments made by this user"
* - **Independent operations**: Users edit/delete their comments directly
* - **Notification systems**: "Alert when any comment is posted"
*
* If comments were subsidiary, these operations would be impossible or
* require inefficient nested queries through parent articles.
*
* **Characteristics:**
*
* - Represents tangible business concepts that users manage
* - Serves as reference points for other tables
* - Requires comprehensive API operations (CREATE, READ, UPDATE, DELETE)
* - Forms the backbone of the application's business logic
*
* **Examples:**
*
* - `bbs_articles` - Forum posts that users create, edit, and manage
* - `bbs_article_comments` - User comments that require independent
* management
*
* ### `"subsidiary"` - Supporting/Dependent Entity
*
* Tables that exist to support primary entities but are not independently
* managed by users. These tables are typically managed through their parent
* entities and may not need standalone API endpoints.
*
* **Characteristics:**
*
* - Depends on primary or snapshot entities for context
* - Often managed indirectly through parent entity operations
* - May have limited or no independent API operations
* - Provides supporting data or relationships
*
* **Examples:**
*
* - `bbs_article_snapshot_files` - Files attached to article snapshots
* - `bbs_article_snapshot_tags` - Tags associated with article snapshots
* - `bbs_article_comment_snapshot_files` - Files attached to comment
* snapshots
*
* ### `"snapshot"` - Historical/Versioning Entity
*
* Tables that capture point-in-time states of primary entities for audit
* trails, version control, or historical tracking. These tables record
* changes but are rarely modified directly by users.
*
* **Characteristics:**
*
* - Captures historical states of primary entities
* - Typically append-only (rarely updated or deleted)
* - Referenced for audit trails and change tracking
* - Usually read-only from user perspective
*
* **Examples:**
*
* - `bbs_article_snapshots` - Historical states of articles
* - `bbs_article_comment_snapshots` - Comment modification history
*
* ## API Generation Guidelines:
*
* The stance property guides automatic API endpoint generation:
*
* - **`"primary"`** โ Generate full CRUD endpoints based on business
* requirements
* - **`"subsidiary"`** โ Evaluate carefully; often managed through parent
* entities
* - **`"snapshot"`** โ Typically read-only endpoints for historical data
* access
*
* @example
* ```typescript
* // Primary business entity - needs full CRUD API
* {
* name: "bbs_articles",
* stance: "primary",
* description: "Forum articles that users create and manage independently"
* }
*
* // Another primary entity - despite being "child" of articles
* {
* name: "bbs_article_comments",
* stance: "primary",
* description: "User comments requiring independent search and management"
* }
*
* // Subsidiary entity - managed through snapshot operations
* {
* name: "bbs_article_snapshot_files",
* stance: "subsidiary",
* description: "Files attached to article snapshots, managed via snapshot APIs"
* }
*
* // Snapshot entity - read-only historical data
* {
* name: "bbs_article_snapshots",
* stance: "snapshot",
* description: "Historical states of articles for audit and versioning"
* }
* ```;
*/
stance: "primary" | "subsidiary" | "snapshot";
//----
// FIELDS
//----
/**
* The primary key field of the model.
*
* In all uploaded schemas, primary keys are always UUID type with "@\id"
* directive. Usually named "id" and marked with "@\db.Uuid" for PostgreSQL
* mapping.
*/
primaryField: IPrimaryField;
/**
* Array of foreign key fields that reference other models.
*
* These establish relationships between models and include Prisma relation
* directives. Can be nullable (optional relationships) or required
* (mandatory relationships). May have unique constraints for 1:1
* relationships.
*/
foreignFields: IForeignField[];
/**
* Array of regular data fields that don't reference other models.
*
* Include business data like names, descriptions, timestamps, flags,
* amounts, etc. Common patterns: created_at, updated_at, deleted_at for
* soft deletion and auditing.
*/
plainFields: IPlainField[];
//----
// INDEXES
//----
/**
* Array of unique indexes for enforcing data integrity constraints.
*
* Ensure uniqueness across single or multiple columns. Examples: unique
* email addresses, unique codes within a channel, unique combinations like
* (channel_id, nickname).
*/
uniqueIndexes: IUniqueIndex[];
/**
* Array of regular indexes for query performance optimization.
*
* Speed up common query patterns like filtering by foreign keys, date
* ranges, or frequently searched fields. Examples: indexes on created_at,
* foreign key fields, search fields.
*/
plainIndexes: IPlainIndex[];
/**
* Array of GIN (Generalized Inverted Index) indexes for full-text search.
*
* Used specifically for PostgreSQL text search capabilities using trigram
* operations. Applied to text fields that need fuzzy matching or partial
* text search. Examples: searching names, nicknames, titles, content
* bodies.
*/
ginIndexes: IGinIndex[];
}
/**
* Interface representing the primary key field of a Prisma model.
*
* All models in the uploaded schemas use UUID as primary key for better
* distributed system compatibility and security (no sequential ID exposure).
*/
export interface IPrimaryField {
/**
* Name of the primary key field.
*
* MUST use snake_case naming convention. Consistently named "id" across all
* models in the uploaded schemas. Represents the unique identifier for each
* record in the table.
*/
name: string & SnakePattern;
/**
* Data type of the primary key field.
*
* Always "uuid" in the uploaded schemas for better distributed system
* support and to avoid exposing sequential IDs that could reveal business
* information.
*/
type: "uuid";
/**
* Description of the primary key field's purpose.
*
* Standard description is "Primary Key." across all models. Serves as the
* unique identifier for the model instance.
*
* **IMPORTANT**: Description must be written in English.
*/
description: string;
}
/**
* Interface representing a foreign key field that establishes relationships
* between models.
*
* Foreign keys create associations between models, enabling relational data
* modeling. They can represent 1:1, 1:N, or participate in M:N relationships
* through junction tables.
*/
export interface IForeignField {
/**
* Name of the foreign key field.
*
* MUST use snake_case naming convention. Follows convention:
* "{target_model_name_without_prefix}_id" Examples: "shopping_customer_id",
* "bbs_article_id", "attachment_file_id" For self-references: "parent_id"
* (e.g., in hierarchical structures)
*/
name: string & SnakePattern;
/**
* Data type of the foreign key field.
*
* Always "uuid" to match the primary key type of referenced models. Ensures
* referential integrity and consistency across the schema.
*/
type: "uuid";
/**
* Description explaining the purpose and target of this foreign key
* relationship.
*
* Should reference the target model using format: "Target model's {@\link
* ModelName.id}" Examples: "Belonged customer's {@\link
* shopping_customers.id}" May include additional context about the
* relationship's business meaning.
*
* **IMPORTANT**: Description must be written in English.
*/
description: string;
/**
* Prisma relation configuration defining the association details.
*
* Specifies how this foreign key connects to the target model, including
* relation name, target model, and target field. This configuration is used
* to generate the appropriate Prisma relation directive in the schema.
*/
relation: IRelation;
/**
* Whether this foreign key has a unique constraint.
*
* True: Creates a 1:1 relationship (e.g., user profile, order publish
* details) false: Allows 1:N relationship (e.g., customer to multiple
* orders) Used for enforcing business rules about relationship
* cardinality.
*/
unique: boolean;
/**
* Whether this foreign key can be null (optional relationship).
*
* True: Relationship is optional, foreign key can be null false:
* Relationship is required, foreign key cannot be null Reflects business
* rules about mandatory vs optional associations.
*/
nullable: boolean;
}
/**
* Interface representing a Prisma relation configuration between models.
*
* This interface defines how foreign key fields establish relationships with
* their target models. It provides the necessary information for Prisma to
* generate appropriate relation directives (@relation) in the schema,
* enabling proper relational data modeling and ORM functionality.
*
* The relation configuration is essential for:
*
* - Generating correct Prisma relation syntax
* - Establishing bidirectional relationships between models
* - Enabling proper type-safe querying through Prisma client
* - Supporting complex relationship patterns (1:1, 1:N, M:N)
*/
export interface IRelation {
/**
* Name of the relation property in the Prisma model.
*
* This becomes the property name used to access the related model instance
* through the Prisma client. Should be descriptive and reflect the business
* relationship being modeled.
*
* Examples:
*
* - "customer" for shopping_customer_id field
* - "channel" for shopping_channel_id field
* - "parent" for parent_id field in hierarchical structures
* - "snapshot" for versioning relationships
* - "article" for bbs_article_id field
*
* Naming convention: camelCase, descriptive of the relationship's business
* meaning
*/
name: string & CamelPattern;
/**
* Name of the target model being referenced by this relation.
*
* Must exactly match an existing model name in the schema. This is used by
* Prisma to establish the foreign key constraint and generate the
* appropriate relation mapping.
*
* Examples:
*
* - "shopping_customers" for customer relationships
* - "shopping_channels" for channel relationships
* - "bbs_articles" for article relationships
* - "attachment_files" for file attachments
*
* The target model should exist in the same schema or be accessible through
* the Prisma schema configuration.
*/
targetModel: string;
/**
* Optional explicit mapping name for complex relationship scenarios.
*
* Used internally by Prisma to handle advanced relationship patterns such
* as:
*
* - Self-referential relationships with multiple foreign keys
* - Complex many-to-many relationships through junction tables
* - Relationships that require custom naming to avoid conflicts
*
* When not specified, Prisma automatically generates appropriate mapping
* names based on the model names and field names. This field should only be
* used when the automatic naming conflicts with other relationships or when
* specific naming is required for business logic.
*
* Examples:
*
* - "ParentChild" for hierarchical self-references
* - "CustomerOrder" for customer-order relationships
* - "UserProfile" for user-profile 1:1 relationships
*
* @internal This field is primarily used by the code generation system
* and should not be modified unless dealing with complex relationship patterns.
*/
mappingName?: string;
}
/**
* Interface representing a regular data field that stores business
* information.
*
* These fields contain the actual business data like names, amounts,
* timestamps, flags, descriptions, and other domain-specific information.
*/
export interface IPlainField {
/**
* Name of the field in the database table.
*
* MUST use snake_case naming convention. Common patterns from uploaded
* schemas:
*
* - Timestamps: created_at, updated_at, deleted_at, opened_at, closed_at
* - Identifiers: code, name, nickname, title
* - Business data: value, quantity, price, volume, balance
* - Flags: primary, required, exclusive, secret, multiplicative
*/
name: string & SnakePattern;
/**
* Data type of the field for Prisma schema generation.
*
* Maps to appropriate Prisma/PostgreSQL types:
*
* - Boolean: Boolean flags and yes/no values
* - Int: Integer numbers, quantities, sequences
* - Double: Decimal numbers, prices, monetary values, percentages
* - String: Text data, names, descriptions, codes
* - Uri: URL/URI fields for links and references
* - Uuid: UUID fields (for non-foreign-key UUIDs)
* - Datetime: Timestamp fields with date and time
*/
type: "boolean" | "int" | "double" | "string" | "uri" | "uuid" | "datetime";
/**
* Description explaining the business purpose and usage of this field.
*
* Should clearly explain:
*
* - What business concept this field represents
* - Valid values or constraints if applicable
* - How it relates to business processes
* - Any special behavioral notes
*
* **IMPORTANT**: Description must be written in English. Example: "Amount
* of cash payment." or "Whether the unit is required or not."
*/
description: string;
/**
* Whether this field can contain null values.
*
* True: Field is optional and can be null (e.g., middle name, description)
* false: Field is required and cannot be null (e.g., creation timestamp,
* name) Reflects business rules about mandatory vs optional data.
*/
nullable: boolean;
}
/**
* Interface representing a unique index constraint on one or more fields.
*
* Unique indexes enforce data integrity by ensuring no duplicate values exist
* for the specified field combination. Essential for business rules that
* require uniqueness like email addresses, codes, or composite keys.
*/
export interface IUniqueIndex {
/**
* Array of field names that together form the unique constraint.
*
* Can be single field (e.g., ["email"]) or composite (e.g., ["channel_id",
* "code"]). All field names must exist in the model. Order matters for
* composite indexes. Examples: ["code"], ["shopping_channel_id",
* "nickname"], ["email"]
*/
fieldNames: string[] & tags.MinItems<1> & tags.UniqueItems;
/**
* Explicit marker indicating this is a unique index.
*
* Always true to distinguish from regular indexes. Used by code generator
* to emit "@@unique" directive in Prisma schema instead of "@@index".
*/
unique: true;
}
/**
* Interface representing a regular (non-unique) index for query performance.
*
* Regular indexes speed up database queries by creating optimized data
* structures for common search patterns. Essential for foreign keys, date
* ranges, and frequently filtered fields.
*/
export interface IPlainIndex {
/**
* Array of field names to include in the performance index.
*
* Can be single field (e.g., ["created_at"]) or composite (e.g.,
* ["customer_id", "created_at"]). All field names must exist in the model.
* Order matters for composite indexes and should match common query
* patterns. Examples: ["created_at"], ["shopping_customer_id",
* "created_at"], ["ip"]
*/
fieldNames: string[] & tags.MinItems<1> & tags.UniqueItems;
}
/**
* Interface representing a GIN (Generalized Inverted Index) for full-text
* search.
*
* GIN indexes enable advanced PostgreSQL text search capabilities including
* fuzzy matching and partial text search using trigram operations. Essential
* for user-facing search features on text content.
*/
export interface IGinIndex {
/**
* Name of the text field to index for full-text search capabilities.
*
* Must be a string field in the model that contains searchable text.
* Examples from uploaded schemas: "nickname", "title", "body", "name" Used
* with PostgreSQL gin_trgm_ops for trigram-based fuzzy text search.
*/
fieldName: string;
}
}
undefined
import { tags } from "typia";
import { CamelPattern } from "../typings/CamelPattern";
/**
* AST type system for programmatic OpenAPI specification generation through AI
* function calling.
*
* This namespace defines a comprehensive Abstract Syntax Tree structure that
* enables AI agents to construct complete OpenAPI v3.1 specification documents
* at the AST level. Each type corresponds to specific OpenAPI specification
* constructs, allowing precise control over generated API documentation while
* maintaining type safety and business logic accuracy.
*
* LANGUAGE REQUIREMENT: All description fields throughout this type system
* (including operation descriptions, summaries, parameter descriptions, schema
* descriptions, etc.) MUST be written exclusively in English. This is a strict
* requirement for API documentation consistency and international
* compatibility.
*
* ## Core Purpose
*
* The system is designed for systematic generation where AI function calls
* build API specifications step-by-step, mapping business requirements to
* executable OpenAPI documents. Instead of generating raw OpenAPI JSON/YAML
* strings, AI agents construct structured AST objects that represent:
*
* - Complete REST API specifications with proper operation definitions
* - Comprehensive type schemas aligned with database structures
* - Detailed parameter and response body specifications
* - Consistent naming conventions and documentation standards
*
* ## Architecture Overview
*
* - **IDocument**: Root container representing the entire OpenAPI specification
* - **IOperation**: Individual API endpoints with HTTP methods, paths, and data
* structures
* - **IComponents**: Reusable schema definitions and security configurations
* - **IJsonSchema**: Type system following OpenAPI v3.1 JSON Schema specification
* - **Parameters & Bodies**: Request/response structures with validation rules
*
* ## OpenAPI v3.1 Compliance
*
* This implementation follows the OpenAPI v3.1 specification but is streamlined
* to:
*
* - Remove ambiguous and duplicated expressions for improved clarity
* - Enhance AI generation capabilities through simplified type structures
* - Maintain developer understanding with consistent patterns
* - Support comprehensive API documentation with detailed descriptions
*
* ## Design Principles
*
* The generated specifications follow enterprise-grade patterns:
*
* - Consistent RESTful API design with standard HTTP methods
* - Comprehensive CRUD operation coverage for all business entities
* - Type-safe request/response schemas with validation constraints
* - Detailed documentation with multi-paragraph descriptions
* - Reusable component schemas for maintainability and consistency
* - Security-aware design with authorization considerations
*
* Each generated OpenAPI document reflects real business workflows where API
* operations provide complete access to underlying data models, maintain proper
* REST conventions, and include comprehensive documentation suitable for
* developer consumption and automated tooling integration.
*
* @author Samchon
*/
export namespace AutoBeOpenApi {
/* -----------------------------------------------------------
DOCUMENT
----------------------------------------------------------- */
/**
* Document of the Restful API operations.
*
* This interface serves as the root document for defining Restful API
* {@link operations} and {@link components}. It corresponds to the top-level
* structure of an OpenAPI specification document, containing all API
* operations and reusable components.
*
* This simplified version focuses only on the operations and components,
* omitting other OpenAPI elements like info, servers, security schemes, etc.
* to keep the structure concise for AI-based code generation.
*
* IMPORTANT: When creating this document, you MUST ensure that:
*
* 1. The API operations and component schemas directly correspond to the Prisma
* DB schema
* 2. All entity types and their properties reference and incorporate the
* description comments from the related Prisma DB schema tables and
* columns
* 3. Descriptions are detailed and organized into multiple paragraphs
* 4. The API fully represents all entities and relationships defined in the
* Prisma schema
* 5. EVERY SINGLE TABLE in the Prisma DB schema MUST have corresponding API
* operations for CRUD actions (Create, Read, Update, Delete) as
* applicable
* 6. NO TABLE should be omitted from the API design - all tables require API
* coverage
*
* ## Type Naming Conventions
*
* When defining component schemas, follow these naming conventions for
* consistency:
*
* - **Main Entity Types**: Use `IEntityName` format for main entity with
* detailed information (e.g., `IShoppingSale`)
*
* - These MUST directly correspond to entity tables in the Prisma schema
* - Their descriptions MUST incorporate the table description comments from the
* Prisma schema
* - Each property MUST reference the corresponding column description from the
* Prisma schema
* - Entity types should represent the full, detailed version of domain entities
* - **Related Operation Types**: Use `IEntityName.IOperation` format with these
* common suffixes:
*
* - `IEntityName.ICreate`: Request body for creation operations (POST)
*
* - Should include all required fields from the Prisma schema entity
* - `IEntityName.IUpdate`: Request body for update operations (PUT)
*
* - Should include updatable fields as defined in the Prisma schema
* - `IEntityName.ISummary`: Simplified response version with essential
* properties
* - `IEntityName.IRequest`: Request parameters for list operations (often with
* search/pagination)
* - `IEntityName.IInvert`: Alternative view of an entity from a different
* perspective
* - `IPageIEntityName`: Paginated results container with `pagination` and
* `data` properties
*
* These consistent naming patterns create a predictable and self-documenting
* API that accurately reflects the underlying Prisma schema, making it easier
* for developers to understand the purpose of each schema and its
* relationship to the database model.
*/
export interface IDocument {
/**
* List of API operations.
*
* This array contains all the API endpoints with their HTTP methods,
* descriptions, parameters, request/response structures, etc. Each
* operation corresponds to an entry in the paths section of an OpenAPI
* document.
*
* CRITICAL: This array MUST include operations for EVERY TABLE defined in
* the Prisma schema. The AI generation MUST NOT skip or omit any tables
* when creating operations. The operations array MUST be complete and
* exhaustive, covering all database entities without exception.
*
* IMPORTANT: For each API operation, ensure that:
*
* 1. EVERY independent entity table in the Prisma schema has corresponding API
* operations for basic CRUD functions (at minimum)
* 2. ALL TABLES from the Prisma schema MUST have at least one API operation,
* no matter how many tables are in the schema
* 3. DO NOT STOP generating API operations until ALL tables have been
* addressed
* 4. The description field refers to and incorporates the description comments
* from the related DB schema tables and columns
* 5. The description must be VERY detailed and organized into MULTIPLE
* PARAGRAPHS separated by line breaks, not just a single paragraph
* 6. The description should explain the purpose, functionality, and any
* relationships to other entities in the database schema
*
* Note that, combination of {@link AutoBeOpenApi.IOperation.path} and
* {@link AutoBeOpenApi.IOperation.method} must be unique.
*
* Also, never forget any specification that is listed on the requirement
* analysis report and DB design documents. Every feature must be
* implemented in the API operations.
*
* @minItems 1
*/
operations: AutoBeOpenApi.IOperation[];
/**
* Reusable components of the API operations.
*
* This contains schemas, parameters, responses, and other reusable elements
* referenced throughout the API operations. It corresponds to the
* components section in an OpenAPI document.
*
* CRITICAL: Components MUST include type definitions for EVERY TABLE in the
* Prisma schema. The AI generation process MUST create schema components
* for ALL database entities without exception, regardless of how many
* tables are in the database.
*
* IMPORTANT: For all component types and their properties:
*
* 1. EVERY component MUST have a detailed description that references the
* corresponding Prisma DB schema table's description comments
* 2. EACH property within component types MUST have detailed descriptions that
* reference the corresponding column description comments in the Prisma
* DB schema
* 3. All descriptions MUST be organized into MULTIPLE PARAGRAPHS (separated by
* line breaks) based on different aspects of the entity
* 4. Descriptions should be comprehensive enough that anyone who reads them
* can understand the purpose, functionality, and relationships of the
* type
* 5. ALL TABLES from the Prisma schema MUST have corresponding schema
* components, no matter how many tables are in the schema
*
* All request and response bodies must reference named types defined in
* this components section. This ensures consistency and reusability across
* the API.
*
* ## Type Naming Conventions in Components
*
* When defining schema components, follow these standardized naming
* patterns for consistency and clarity:
*
* ### Main Entity Types
*
* - `IEntityName`
*
* - Primary entity objects (e.g., `IShoppingSale`, `IShoppingOrder`)
* - These represent the full, detailed version of domain entities
*
* ### Operation-Specific Types
*
* - `IEntityName.ICreate`
*
* - Request body schemas for creation operations (POST)
* - Contains all fields needed to create a new entity
* - `IEntityName.IUpdate`
*
* - Request body schemas for update operations (PUT)
* - Contains fields that can be modified on an existing entity
* - `IEntityName.IRequest`
*
* - Parameters for search/filter/pagination in list operations
* - Often contains `search`, `sort`, `page`, and `limit` properties
*
* ### View Types
*
* - `IEntityName.ISummary`
*
* - Simplified view of entities for list operations
* - Contains essential properties only, omitting detailed nested objects
* - `IEntityName.IAbridge`: Intermediate view with more details than Summary
* but less than full entity
* - `IEntityName.IInvert`: Alternative representation of an entity from a
* different perspective
*
* ### Container Types
*
* - `IPageIEntityName`
*
* - Paginated results container
* - Usually contains `pagination` and `data` properties
*
* These naming conventions create a self-documenting API where the purpose
* of each schema is immediately clear from its name. This helps both
* developers and AI tools understand and maintain the API structure.
*/
components: AutoBeOpenApi.IComponents;
}
/**
* Operation of the Restful API.
*
* This interface defines a single API endpoint with its HTTP {@link method},
* {@link path}, {@link parameters path parameters},
* {@link requestBody request body}, and {@link responseBody} structure. It
* corresponds to an individual operation in the paths section of an OpenAPI
* document.
*
* Each operation requires a detailed explanation of its purpose through the
* reason and description fields, making it clear why the API was designed and
* how it should be used.
*
* All request bodies and responses for this operation must be object types
* and must reference named types defined in the components section. The
* content-type is always `application/json`. For file upload/download
* operations, use `string & tags.Format<"uri">` in the appropriate schema
* instead of binary data formats.
*
* In OpenAPI, this might represent:
*
* ```json
* {
* "/shoppings/customers/orders": {
* "post": {
* "description": "Create a new order application from shopping cart...",
* "parameters": [...],
* "requestBody": {...},
* "responses": {...}
* }
* }
* }
* ```
*/
export interface IOperation extends IEndpoint {
/**
* Specification of the API operation.
*
* Before defining the API operation interface, please describe what you're
* planning to write in this `specification` field.
*
* The specification must be fully detailed and clear, so that anyone can
* understand the purpose and functionality of the API operation and its
* related components (e.g., {@link path}, {@link parameters},
* {@link requestBody}).
*
* IMPORTANT: The specification MUST identify which Prisma DB table this
* operation is associated with, helping ensure complete coverage of all
* database entities.
*/
specification: string;
/**
* Authorization type of the API operation.
*
* - `"login"`: User login operations that validate credentials
* - `"join"`: User registration operations that create accounts
* - `"refresh"`: Token refresh operations that renew access tokens
* - `null`: All other operations (CRUD, business logic, etc.)
*
* Use authentication values only for credential validation, user
* registration, or token refresh operations. Use `null` for all other
* business operations.
*
* Examples:
*
* - `/auth/login` โ `"login"`
* - `/auth/register` โ `"join"`
* - `/auth/refresh` โ `"refresh"`
* - `/auth/validate` โ `null`
* - `/users/{id}`, `/shoppings/customers/sales/cancel`, โ `null`
*/
authorizationType: "login" | "join" | "refresh" | null;
/**
* Detailed description about the API operation.
*
* IMPORTANT: This field MUST be extensively detailed and MUST reference the
* description comments from the related Prisma DB schema tables and
* columns. The description should be organized into MULTIPLE PARAGRAPHS
* separated by line breaks to improve readability and comprehension.
*
* For example, include separate paragraphs for:
*
* - The purpose and overview of the API operation
* - Security considerations and user permissions
* - Relationship to underlying database entities
* - Validation rules and business logic
* - Related API operations that might be used together with this one
* - Expected behavior and error handling
*
* When writing the description, be sure to incorporate the corresponding DB
* schema's description comments, matching the level of detail and style of
* those comments. This ensures consistency between the API documentation
* and database structure.
*
* If there's a dependency to other APIs, please describe the dependency API
* operation in this field with detailed reason. For example, if this API
* operation needs a pre-execution of other API operation, it must be
* explicitly described.
*
* - `GET /shoppings/customers/sales` must be pre-executed to get entire list
* of summarized sales. Detailed sale information would be obtained by
* specifying the sale ID in the path parameter.
*
* **CRITICAL WARNING about soft delete keywords**: DO NOT use terms like
* "soft delete", "soft-delete", or similar variations in this description
* UNLESS the operation actually implements soft deletion. These keywords
* trigger validation logic that expects a corresponding soft_delete_column
* to be specified. Only use these terms when you intend to implement soft
* deletion (marking records as deleted without removing them from the
* database).
*
* Example of problematic description: โ "This would normally be a
* soft-delete, but we intentionally perform permanent deletion here" - This
* triggers soft delete validation despite being a hard delete operation.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
/**
* Short summary of the API operation.
*
* This should be a concise description of the API operation, typically one
* sentence long. It should provide a quick overview of what the API does
* without going into too much detail.
*
* This summary will be used in the OpenAPI documentation to give users a
* quick understanding of the API operation's purpose.
*
* IMPORTANT: The summary should clearly indicate which Prisma DB table this
* operation relates to, helping to ensure all tables have API coverage.
*
* **CRITICAL WARNING about soft delete keywords**: DO NOT use terms like
* "soft delete", "soft-delete", or similar variations in this summary
* UNLESS the operation actually implements soft deletion. These keywords
* trigger validation logic that expects a corresponding soft_delete_column
* to be specified. Only use these terms when you intend to implement soft
* deletion (marking records as deleted without removing them from the
* database).
*
* > MUST be written in English. Never use other languages
*/
summary: string;
/**
* List of path parameters.
*
* Note that, the {@link AutoBeOpenApi.IParameter.name identifier name} of
* path parameter must be corresponded to the
* {@link path API operation path}.
*
* For example, if there's an API operation which has {@link path} of
* `/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}`,
* its list of {@link AutoBeOpenApi.IParameter.name path parameters} must be
* like:
*
* - `saleId`
* - `questionId`
* - `commentId`
*/
parameters: AutoBeOpenApi.IParameter[];
/**
* Request body of the API operation.
*
* Defines the payload structure for the request. Contains a description and
* schema reference to define the expected input data.
*
* Should be `null` for operations that don't require a request body, such
* as most "get" operations.
*/
requestBody: AutoBeOpenApi.IRequestBody | null;
/**
* Response body of the API operation.
*
* Defines the structure of the successful response data. Contains a
* description and schema reference for the returned data.
*
* Should be null for operations that don't return any data.
*/
responseBody: AutoBeOpenApi.IResponseBody | null;
/**
* Authorization role required to access this API operation.
*
* This field specifies which user role is allowed to access this endpoint.
* The role name must correspond exactly to the actual roles defined in your
* system's Prisma schema.
*
* ## Naming Convention
*
* Role names MUST use camelCase.
*
* ## Role-Based Path Convention
*
* When authorizationRole is specified, it should align with the path
* structure:
*
* - If authorizationRole is "admin" โ path might be "/admin/resources/{id}"
* - If authorizationRole is "seller" โ path might be "/seller/products"
* - Special case: For user's own resources, use path prefix "/my/" regardless
* of role
*
* ## Important Guidelines
*
* - Set to `null` for public endpoints that require no authentication
* - Set to specific role string for role-restricted endpoints
* - The role name MUST match exactly with the user type/role defined in the
* database
* - This role will be used by the Realize Agent to generate appropriate
* decorator and authorization logic in the provider functions
* - The controller will apply the corresponding authentication decorator
* based on this role
*
* ## Examples
*
* - `null` - Public endpoint, no authentication required
* - `"user"` - Any authenticated user can access
* - `"admin"` - Only admin users can access
* - `"seller"` - Only seller users can access
* - `"moderator"` - Only moderator users can access
*
* Note: The actual authentication/authorization implementation will be
* handled by decorators at the controller level, and the provider function
* will receive the authenticated user object with the appropriate type.
*/
authorizationRole: (string & CamelPattern & tags.MinLength<1>) | null;
/**
* Functional name of the API endpoint.
*
* This is a semantic identifier that represents the primary function or
* purpose of the API endpoint. It serves as a canonical name that can be
* used for code generation, SDK method names, and internal references.
*
* ## Reserved Word Restrictions
*
* CRITICAL: The name MUST NOT be a TypeScript/JavaScript reserved word, as
* it will be used as a class method name in generated code. Avoid names
* like:
*
* - `delete`, `for`, `if`, `else`, `while`, `do`, `switch`, `case`, `break`
* - `continue`, `function`, `return`, `with`, `in`, `of`, `instanceof`
* - `typeof`, `void`, `var`, `let`, `const`, `class`, `extends`, `import`
* - `export`, `default`, `try`, `catch`, `finally`, `throw`, `new`
* - `super`, `this`, `null`, `true`, `false`, `async`, `await`
* - `yield`, `static`, `private`, `protected`, `public`, `implements`
* - `interface`, `package`, `enum`, `debugger`
*
* Instead, use alternative names for these operations:
*
* - Use `erase` instead of `delete`
* - Use `iterate` instead of `for`
* - Use `when` instead of `if`
* - Use `cls` instead of `class`
*
* ## Standard Endpoint Names
*
* Use these conventional names based on the endpoint's primary function:
*
* - **`index`**: List/search operations that return multiple entities
*
* - Typically used with PATCH method for complex queries
* - Example: `PATCH /users` โ `name: "index"`
* - **`at`**: Retrieve a specific entity by identifier
*
* - Typically used with GET method on single resource
* - Example: `GET /users/{userId}` โ `name: "at"`
* - **`create`**: Create a new entity
*
* - Typically used with POST method
* - Example: `POST /users` โ `name: "create"`
* - **`update`**: Update an existing entity
*
* - Typically used with PUT method
* - Example: `PUT /users/{userId}` โ `name: "update"`
* - **`erase`**: Delete/remove an entity (NOT `delete` - reserved word!)
*
* - Typically used with DELETE method
* - Example: `DELETE /users/{userId}` โ `name: "erase"`
*
* ## Custom Endpoint Names
*
* For specialized operations beyond basic CRUD, use descriptive verbs:
*
* - **`activate`**: Enable or turn on a feature/entity
* - **`deactivate`**: Disable or turn off a feature/entity
* - **`approve`**: Approve a request or entity
* - **`reject`**: Reject a request or entity
* - **`publish`**: Make content publicly available
* - **`archive`**: Move to archived state
* - **`restore`**: Restore from archived/deleted state
* - **`duplicate`**: Create a copy of an entity
* - **`transfer`**: Move ownership or change assignment
* - **`validate`**: Validate data or state
* - **`process`**: Execute a business process or workflow
* - **`export`**: Generate downloadable data
* - **`import`**: Process uploaded data
*
* ## Naming Guidelines
*
* - MUST use camelCase naming convention
* - Use singular verb forms
* - Be concise but descriptive
* - Avoid abbreviations unless widely understood
* - Ensure the name clearly represents the endpoint's primary action
* - For nested resources, focus on the action rather than hierarchy
* - NEVER use JavaScript/TypeScript reserved words
*
* Valid Examples:
*
* - `index`, `create`, `update`, `erase` (single word)
* - `updatePassword`, `cancelOrder`, `publishArticle` (camelCase)
* - `validateEmail`, `generateReport`, `exportData` (camelCase)
*
* Invalid Examples:
*
* - `update_password` (snake_case not allowed)
* - `UpdatePassword` (PascalCase not allowed)
* - `update-password` (kebab-case not allowed)
*
* Path to Name Examples:
*
* - `GET /shopping/orders/{orderId}/items` โ `name: "index"` (lists items)
* - `POST /shopping/orders/{orderId}/cancel` โ `name: "cancel"`
* - `PUT /users/{userId}/password` โ `name: "updatePassword"`
*
* ## Uniqueness Rule
*
* The `name` must be unique within the API's accessor namespace. The
* accessor is formed by combining the path segments (excluding parameters)
* with the operation name.
*
* Accessor formation:
*
* 1. Extract non-parameter segments from the path (remove `{...}` parts)
* 2. Join segments with dots
* 3. Append the operation name
*
* Examples:
*
* - Path: `/shopping/sale/{saleId}/review/{reviewId}`, Name: `at` โ Accessor:
* `shopping.sale.review.at`
* - Path: `/users/{userId}/posts`, Name: `index` โ Accessor:
* `users.posts.index`
* - Path: `/auth/login`, Name: `signIn` โ Accessor: `auth.login.signIn`
*
* Each accessor must be globally unique across the entire API. This ensures
* operations can be uniquely identified in generated SDKs and prevents
* naming conflicts.
*/
name: string & CamelPattern;
}
/**
* Authorization - Authentication and user type information
*
* This field defines how the API authenticates the request and restricts
* access to specific user types.
*
* โ
Only the `Authorization` HTTP header is used for authentication. The
* expected format is:
*
* Authorization: Bearer <access_token>
*
* The token must be a bearer token (e.g., JWT or similar), and when parsed,
* it is guaranteed to include at least the authenticated actor's `id` field.
* No other headers or cookie-based authentication methods are supported.
*/
export interface IAuthorization {
/**
* Allowed user types for this API
*
* Specifies which user types are permitted to access this API.
*
* This is not a permission level or access control role. Instead, it
* describes **who** the user is โ their type within the service's domain
* model. It must correspond 1:1 with how the user is represented in the
* database.
*
* MUST use camelCase naming convention.
*
* โ ๏ธ Important: Each `role` must **exactly match a table name defined in
* the database schema**. This is not merely a convention or example โ it is
* a strict requirement.
*
* A valid role must meet the following criteria:
*
* - It must uniquely map to a user group at the database level, represented
* by a dedicated table.
* - It must not overlap semantically with other roles โ for instance, both
* `admin` and `administrator` must not exist to describe the same type.
*
* Therefore, if a user type cannot be clearly and uniquely distinguished in
* the database, It **cannot** be used as a valid `role` here.
*/
name: string & CamelPattern;
/**
* Detailed description of the authorization role
*
* Provides a comprehensive explanation of:
*
* - The purpose and scope of this authorization role
* - Which types of users are granted this role
* - What capabilities and permissions this role enables
* - Any constraints or limitations associated with the role
* - How this role relates to the underlying database schema
* - Examples of typical use cases for this role
*
* This description should be detailed enough for both API consumers to
* understand the role's purpose and for the system to properly enforce
* access controls.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
}
/**
* Path parameter information for API routes.
*
* This interface defines a path parameter that appears in the URL of an API
* endpoint. Path parameters are enclosed in curly braces in the
* {@link AutoBeOpenApi.IOperation.path operation path} and must be defined
* with their types and descriptions.
*
* For example, if API operation path is
* `/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}`,
* the path parameters should be like below:
*
* ```json
* {
* "path": "/shoppings/customers/sales/{saleId}/questions/${questionId}/comments/${commentId}",
* "method": "get",
* "parameters": [
* {
* "name": "saleId",
* "in": "path",
* "schema": { "type": "string", "format": "uuid" },
* "description": "Target sale's ID"
* },
* {
* "name": "questionId",
* "in": "path",
* "schema": { "type": "string", "format": "uuid" },
* "description": "Target question's ID"
* },
* {
* "name": "commentId",
* "in": "path",
* "schema": { "type": "string", "format": "uuid" },
* "description": "Target comment's ID"
* }
* ]
* }
* ```
*/
export interface IParameter {
/**
* Identifier name of the path parameter.
*
* This name must match exactly with the parameter name in the route path.
* It must be corresponded to the
* {@link AutoBeOpenApi.IOperation.path API operation path}.
*
* MUST use camelCase naming convention.
*/
name: string & CamelPattern;
/**
* Description about the path parameter.
*
* Make short, concise and clear description about the path parameter.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
/**
* Type schema of the path parameter.
*
* Path parameters are typically primitive types like
* {@link AutoBeOpenApi.IJsonSchema.IString strings},
* {@link AutoBeOpenApi.IJsonSchema.IInteger integers},
* {@link AutoBeOpenApi.IJsonSchema.INumber numbers}.
*
* If you need other types, please use request body instead with object type
* encapsulation.
*/
schema:
| AutoBeOpenApi.IJsonSchema.IInteger
| AutoBeOpenApi.IJsonSchema.INumber
| AutoBeOpenApi.IJsonSchema.IString;
}
/**
* Request body information of OpenAPI operation.
*
* This interface defines the structure for request bodies in API routes. It
* corresponds to the requestBody section in OpenAPI specifications, providing
* both a description and schema reference for the request payload.
*
* The content-type for all request bodies is always `application/json`. Even
* when file uploading is required, don't use `multipart/form-data` or
* `application/x-www-form-urlencoded` content types. Instead, just define an
* URI string property in the request body schema.
*
* Note that, all body schemas must be transformable to a
* {@link AutoBeOpenApi.IJsonSchema.IReference reference} type defined in the
* {@link AutoBeOpenApi.IComponents.schemas components section} as an
* {@link AutoBeOpenApi.IJsonSchema.IObject object} type.
*
* In OpenAPI, this might represent:
*
* ```json
* {
* "requestBody": {
* "description": "Creation info of the order",
* "content": {
* "application/json": {
* "schema": {
* "$ref": "#/components/schemas/IShoppingOrder.ICreate"
* }
* }
* }
* }
* }
* ```
*/
export interface IRequestBody {
/**
* Description about the request body.
*
* Make short, concise and clear description about the request body.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
/**
* Request body type name.
*
* This specifies the data structure expected in the request body, that will
* be transformed to {@link AutoBeOpenApi.IJsonSchema.IReference reference}
* type in the {@link AutoBeOpenApi.IComponents.schemas components section}
* as an {@link AutoBeOpenApi.IJsonSchema.Object object} type.
*
* Here is the naming convention for the request body type:
*
* - `IEntityName.ICreate`: Request body for creation operations (POST)
* - `IEntityName.IUpdate`: Request body for update operations (PUT)
* - `IEntityName.IRequest`: Request parameters for list operations (often
* with search/pagination)
*
* What you write:
*
* ```json
* {
* "typeName": "IShoppingOrder.ICreate"
* }
* ```
*
* Transformed to:
*
* ```json
* {
* "schema": {
* "$ref": "#/components/schemas/IShoppingOrder.ICreate"
* }
* }
* ```
*/
typeName: string;
}
/**
* Response body information for OpenAPI operation.
*
* This interface defines the structure of a successful response from an API
* operation. It provides a description of the response and a schema reference
* to define the returned data structure.
*
* The content-type for all responses is always `application/json`. Even when
* file downloading is required, don't use `application/octet-stream` or
* `multipart/form-data` content types. Instead, just define an URI string
* property in the response body schema.
*
* In OpenAPI, this might represent:
*
* ```json
* {
* "responses": {
* "200": {
* "description": "Order information",
* "content": {
* "application/json": {
* "schema": { "$ref": "#/components/schemas/IShoppingOrder" }
* }
* }
* }
* }
* }
* ```
*/
export interface IResponseBody {
/**
* Description about the response body.
*
* Make short, concise and clear description about the response body.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
/**
* Response body's data type.
*
* Specifies the structure of the returned data (response body), that will
* be transformed to {@link AutoBeOpenApi.IJsonSchema.IReference} type in the
* {@link AutoBeOpenApi.IComponents.schemas components section} as an
* {@link AutoBeOpenApi.IJsonSchema.IObject object} type.
*
* Here is the naming convention for the response body type:
*
* - `IEntityName`: Main entity with detailed information (e.g.,
* `IShoppingSale`)
* - `IEntityName.ISummary`: Simplified response version with essential
* properties
* - `IEntityName.IInvert`: Alternative view of an entity from a different
* perspective
* - `IPageIEntityName`: Paginated results container with `pagination` and
* `data` properties
*
* What you write:
*
* ```json
* {
* "typeName": "IShoppingOrder"
* }
* ```
*
* Transformed to:
*
* ```json
* {
* "schema": {
* "$ref": "#/components/schemas/IShoppingOrder"
* }
* }
* ```
*/
typeName: string;
}
/* -----------------------------------------------------------
JSON SCHEMA
----------------------------------------------------------- */
/**
* Reusable components in OpenAPI.
*
* A storage of reusable components in OpenAPI document.
*
* In other words, it is a storage of named DTO schemas and security schemes.
*/
export interface IComponents {
/**
* An object to hold reusable DTO schemas.
*
* In other words, a collection of named JSON schemas.
*
* IMPORTANT: For each schema in this collection:
*
* 1. EVERY schema MUST have a detailed description that references and aligns
* with the description comments from the corresponding Prisma DB schema
* tables
* 2. EACH property within the schema MUST have detailed descriptions that
* reference and align with the description comments from the
* corresponding DB schema columns
* 3. All descriptions MUST be organized into MULTIPLE PARAGRAPHS (separated by
* line breaks) when appropriate
* 4. Descriptions should be comprehensive enough that anyone reading them can
* understand the purpose, functionality, and constraints of each type
* and property without needing to reference other documentation
*/
schemas: Record<string, IJsonSchemaDescriptive>;
/** Whether includes `Authorization` header or not. */
authorization: IAuthorization[];
}
/**
* Type schema info.
*
* `AutoBeOpenApi.IJsonSchema` is a type schema info of the OpenAPI
* Generative.
*
* `AutoBeOpenApi.IJsonSchema` basically follows the JSON schema specification
* of OpenAPI v3.1, but a little bit shrunk to remove ambiguous and duplicated
* expressions of OpenAPI v3.1 for the convenience, clarity, and AI
* generation.
*
* ## CRITICAL: Union Type Expression
*
* In this type system, union types (including nullable types) MUST be
* expressed using the `IOneOf` structure. NEVER use array notation in the
* `type` field.
*
* โ **FORBIDDEN** - Array notation in type field:
*
* ```typescript
* {
* "type": ["string", "null"] // NEVER DO THIS!
* }
* ```
*
* โ
**CORRECT** - Using IOneOf for unions:
*
* ```typescript
* // For nullable string:
* {
* oneOf: [{ type: "string" }, { type: "null" }];
* }
*
* // For string | number union:
* {
* oneOf: [{ type: "string" }, { type: "number" }];
* }
* ```
*
* The `type` field in any schema object is a discriminator that identifies
* the schema type and MUST contain exactly one string value.
*/
export type IJsonSchema =
| IJsonSchema.IConstant
| IJsonSchema.IBoolean
| IJsonSchema.IInteger
| IJsonSchema.INumber
| IJsonSchema.IString
| IJsonSchema.IArray
| IJsonSchema.IObject
| IJsonSchema.IReference
| IJsonSchema.IOneOf
| IJsonSchema.INull;
export namespace IJsonSchema {
/** Constant value type. */
export interface IConstant {
/** The constant value. */
const: boolean | number | string;
}
/** Boolean type info. */
export interface IBoolean extends ISignificant<"boolean"> {}
/** Integer type info. */
export interface IInteger extends ISignificant<"integer"> {
/**
* Minimum value restriction.
*
* @type int64
*/
minimum?: number;
/**
* Maximum value restriction.
*
* @type int64
*/
maximum?: number;
/** Exclusive minimum value restriction. */
exclusiveMinimum?: number;
/** Exclusive maximum value restriction. */
exclusiveMaximum?: number;
/**
* Multiple of value restriction.
*
* @type uint64
* @exclusiveMinimum 0
*/
multipleOf?: number;
}
/** Number (double) type info. */
export interface INumber extends ISignificant<"number"> {
/** Minimum value restriction. */
minimum?: number;
/** Maximum value restriction. */
maximum?: number;
/** Exclusive minimum value restriction. */
exclusiveMinimum?: number;
/** Exclusive maximum value restriction. */
exclusiveMaximum?: number;
/**
* Multiple of value restriction.
*
* @exclusiveMinimum 0
*/
multipleOf?: number;
}
/** String type info. */
export interface IString extends ISignificant<"string"> {
/** Format restriction. */
format?:
| "binary"
| "byte"
| "password"
| "regex"
| "uuid"
| "email"
| "hostname"
| "idn-email"
| "idn-hostname"
| "iri"
| "iri-reference"
| "ipv4"
| "ipv6"
| "uri"
| "uri-reference"
| "uri-template"
| "url"
| "date-time"
| "date"
| "time"
| "duration"
| "json-pointer"
| "relative-json-pointer"
| (string & {});
/** Pattern restriction. */
pattern?: string;
/** Content media type restriction. */
contentMediaType?: string;
/**
* Minimum length restriction.
*
* @type uint64
*/
minLength?: number;
/**
* Maximum length restriction.
*
* @type uint64
*/
maxLength?: number;
}
/** Array type info. */
export interface IArray extends ISignificant<"array"> {
/**
* Items type info.
*
* The `items` means the type of the array elements. In other words, it is
* the type schema info of the `T` in the TypeScript array type
* `Array<T>`.
*/
items: IJsonSchema;
/**
* Unique items restriction.
*
* If this property value is `true`, target array must have unique items.
*/
uniqueItems?: boolean;
/**
* Minimum items restriction.
*
* Restriction of minimum number of items in the array.
*
* @type uint64
*/
minItems?: number;
/**
* Maximum items restriction.
*
* Restriction of maximum number of items in the array.
*
* @type uint64
*/
maxItems?: number;
}
/** Object type info. */
export interface IObject extends ISignificant<"object"> {
/**
* Properties of the object.
*
* The `properties` means a list of key-value pairs of the object's
* regular properties. The key is the name of the regular property, and
* the value is the type schema info.
*
* IMPORTANT: Each property in this object MUST have a detailed
* description that references and aligns with the description comments
* from the corresponding Prisma DB schema column.
*
* If you need additional properties that is represented by dynamic key,
* you can use the {@link additionalProperties} instead.
*/
properties: Record<string, IJsonSchemaDescriptive>;
/**
* Additional properties' info.
*
* The `additionalProperties` means the type schema info of the additional
* properties that are not listed in the {@link properties}.
*
* If the value is `false`, it means that the additional properties are
* not specified. Otherwise, if the value is {@link IJsonSchema} type, it
* means that the additional properties must follow the type schema info.
*
* - `false`: No additional properties
* - `IJsonSchema`: `Record<string, T>`
*/
additionalProperties?: false | IJsonSchema;
/**
* List of key values of the required properties.
*
* The `required` means a list of the key values of the required
* {@link properties}. If some property key is not listed in the `required`
* list, it means that property is optional. Otherwise some property key
* exists in the `required` list, it means that the property must be
* filled.
*
* Below is an example of the {@link properties} and `required`.
*
* ```typescript
* interface SomeObject {
* id: string;
* email: string;
* name?: string;
* }
* ```
*
* As you can see, `id` and `email` {@link properties} are {@link required},
* so that they are listed in the `required` list.
*
* ```json
* {
* "type": "object",
* "properties": {
* "id": { "type": "string" },
* "email": { "type": "string" },
* "name": { "type": "string" }
* },
* "required": ["id", "email"]
* }
* ```
*/
required: string[];
}
/** Reference type directing named schema. */
export interface IReference {
/**
* Reference to the named schema.
*
* The `ref` is a reference to the named schema. Format of the `$ref` is
* following the JSON Pointer specification. In the OpenAPI, the `$ref`
* starts with `#/components/schemas/` which means the type is stored in
* the {@link AutoBeOpenApi.IComponents.schemas} object.
*
* - `#/components/schemas/SomeObject`
* - `#/components/schemas/AnotherObject`
*/
$ref: string;
}
/**
* Union type.
*
* `IOneOf` represents an union type of the TypeScript (`A | B | C`).
*
* For reference, even though your Swagger (or OpenAPI) document has defined
* `anyOf` instead of the `oneOf`, {@link AutoBeOpenApi} forcibly converts it
* to `oneOf` type.
*/
export interface IOneOf {
/** List of the union types. */
oneOf: Exclude<IJsonSchema, IJsonSchema.IOneOf>[];
/** Discriminator info of the union type. */
discriminator?: IOneOf.IDiscriminator;
}
export namespace IOneOf {
/** Discriminator info of the union type. */
export interface IDiscriminator {
/** Property name for the discriminator. */
propertyName: string;
/**
* Mapping of the discriminator value to the schema name.
*
* This property is valid only for {@link IReference} typed
* {@link IOneOf.oneof} elements. Therefore, `key` of `mapping` is the
* discriminator value, and `value` of `mapping` is the schema name like
* `#/components/schemas/SomeObject`.
*/
mapping?: Record<string, string>;
}
}
/** Null type. */
export interface INull extends ISignificant<"null"> {}
interface ISignificant<Type extends string> {
/**
* Discriminator value of the type.
*
* CRITICAL: This MUST be a SINGLE string value, NOT an array. The type
* field identifies the JSON Schema type and must be exactly one of:
* "boolean", "integer", "number", "string", "array", "object", or
* "null".
*
* โ INCORRECT: type: ["string", "null"] // This is WRONG! โ
CORRECT:
* type: "string" // For nullable string, use oneOf instead
*
* If you need to express a nullable type (e.g., string | null), you MUST
* use the `IOneOf` structure:
*
* ```typescript
* {
* "oneOf": [{ "type": "string" }, { "type": "null" }]
* }
* ```
*
* NEVER use array notation in the type field. The type field is a
* discriminator that accepts only a single string value.
*/
type: Type;
}
}
/**
* Descriptive type schema info.
*
* `AutoBeOpenApi.IJsonSchemaDescriptive` is a type schema info of the OpenAPI
* Generative, but it has a `description` property which is required.
*
* `AutoBeOpenApi.IJsonSchemaDescriptive` basically follows the JSON schema
* specification of OpenAPI v3.1, but a little bit shrunk to remove ambiguous
* and duplicated expressions of OpenAPI v3.1 for the convenience, clarity,
* and AI generation.
*
* CRITICAL INSTRUCTIONS FOR OPTIMAL AI GENERATION:
*
* When creating descriptions for components, types, and properties:
*
* 1. ALWAYS refer to and incorporate the description comments from the
* corresponding Prisma DB schema tables and columns. The descriptions
* should match the style, level of detail, and terminology used in the
* Prisma schema.
* 2. ALL descriptions MUST be organized into MULTIPLE PARAGRAPHS separated by
* line breaks. Single-paragraph descriptions should be avoided.
* 3. Descriptions should comprehensively cover:
*
* - The purpose and business meaning of the type or property
* - Relationships to other entities
* - Validation rules, constraints, and edge cases
* - Usage context and examples when helpful
* 4. For each property of an object type, ensure its description reflects the
* corresponding column description in the Prisma DB schema, maintaining
* the same level of detail and terminology
* 5. Descriptions should be so detailed and clear that anyone reading them can
* fully understand the type or property without needing to reference any
* other documentation
*/
export type IJsonSchemaDescriptive =
| IJsonSchemaDescriptive.IConstant
| IJsonSchemaDescriptive.IBoolean
| IJsonSchemaDescriptive.IInteger
| IJsonSchemaDescriptive.INumber
| IJsonSchemaDescriptive.IString
| IJsonSchemaDescriptive.IArray
| IJsonSchemaDescriptive.IObject
| IJsonSchemaDescriptive.IReference
| IJsonSchemaDescriptive.IOneOf
| IJsonSchemaDescriptive.INull;
export namespace IJsonSchemaDescriptive {
/** Constant value type. */
export interface IConstant extends IJsonSchema.IConstant, IDescriptive {}
/** Boolean type info. */
export interface IBoolean extends IJsonSchema.IBoolean, IDescriptive {}
/** Integer type info. */
export interface IInteger extends IJsonSchema.IInteger, IDescriptive {}
/** Number (double) type info. */
export interface INumber extends IJsonSchema.INumber, IDescriptive {}
/** String type info. */
export interface IString extends IJsonSchema.IString, IDescriptive {}
/** Array type info. */
export interface IArray extends IJsonSchema.IArray, IDescriptive {}
/** Object type info. */
export interface IObject extends IJsonSchema.IObject, IDescriptive {}
/** Reference type directing named schema. */
export interface IReference extends IJsonSchema.IReference, IDescriptive {}
/**
* Union type.
*
* `IOneOf` represents an union type of the TypeScript (`A | B | C`).
*
* For reference, even though your Swagger (or OpenAPI) document has defined
* `anyOf` instead of the `oneOf`, {@link AutoBeOpenApi} forcibly converts it
* to `oneOf` type.
*/
export interface IOneOf extends IJsonSchema.IOneOf, IDescriptive {}
/** Null type. */
export interface INull extends IJsonSchema.INull, IDescriptive {}
interface IDescriptive {
/**
* Description about the type.
*
* CRITICAL: This description MUST be extensively detailed and MUST
* reference and align with the description comments from the
* corresponding Prisma DB schema tables and columns.
*
* The description MUST be organized into MULTIPLE PARAGRAPHS (separated
* by line breaks) based on different aspects of the type:
*
* - The purpose and business meaning of the type
* - Relationships to other entities in the system
* - Validation rules, constraints, and edge cases
* - Usage context and examples when helpful
*
* This structured approach improves readability and helps readers better
* understand the type's various characteristics and use cases. The
* description should be so comprehensive that anyone reading it can fully
* understand the type without needing to reference other documentation.
*
* > MUST be written in English. Never use other languages.
*/
description: string;
}
}
/* -----------------------------------------------------------
BACKGROUNDS
----------------------------------------------------------- */
/** API endpoint information. */
export interface IEndpoint {
/**
* HTTP path of the API operation.
*
* The URL path for accessing this API operation, using path parameters
* enclosed in curly braces (e.g., `/shoppings/customers/sales/{saleId}`).
*
* It must be corresponded to the {@link parameters path parameters}.
*
* The path structure should clearly indicate which database entity this
* operation is manipulating, helping to ensure all entities have
* appropriate API coverage.
*
* Path validation rules:
*
* - Must start with a forward slash (/)
* - Can contain only: letters (a-z, A-Z), numbers (0-9), forward slashes (/),
* curly braces for parameters ({paramName}), hyphens (-), and underscores
* (_)
* - Parameters must be enclosed in curly braces: {paramName}
* - Resource names should be in camelCase
* - No quotes, spaces, or invalid special characters allowed
* - No domain or role-based prefixes
*
* Valid examples:
*
* - "/users"
* - "/users/{userId}"
* - "/articles/{articleId}/comments"
* - "/attachmentFiles"
* - "/orders/{orderId}/items/{itemId}"
*
* Invalid examples:
*
* - "'/users'" (contains quotes)
* - "/user profile" (contains space)
* - "/users/[userId]" (wrong bracket format)
* - "/admin/users" (role prefix)
* - "/api/v1/users" (API prefix)
*/
path: string & tags.Pattern<"^\\/[a-zA-Z0-9\\/_{}.-]*$">;
/**
* HTTP method of the API operation.
*
* **IMPORTANT**: Methods must be written in lowercase only (e.g., "get",
* not "GET").
*
* Note that, if the API operation has {@link requestBody}, method must not
* be `get`.
*
* Also, even though the API operation has been designed to only get
* information, but it needs complicated request information, it must be
* defined as `patch` method with {@link requestBody} data specification.
*
* - `get`: get information
* - `patch`: get information with complicated request data
* ({@link requestBody})
* - `post`: create new record
* - `put`: update existing record
* - `delete`: remove record
*/
method: "get" | "post" | "put" | "delete" | "patch";
}
}
Expansive Ecosystem
TypeScript is the only programming language that enables development of backend servers, frontend web applications, mobile apps, desktop applications, and even AI agents with a single language. This versatility goes beyond mere possibility, recording overwhelming market share in each field.
In the web frontend field, JavaScript/TypeScript holds virtually 100% market share, and backend development through Node.js has become mainstream technology adopted by 43% of Fortune 500 companies. In mobile application development, React Native powers apps with billions of users including Facebook, Instagram, and Discord, while in desktop applications, Electron-based VS Code, Slack, and Discord have established themselves as leading applications in their respective fields. Even in AI agent development, major frameworks like Vercel AI SDK and LangChain.js have adopted TypeScript as their primary language, showing rapid growth.
The NPM ecosystem holds over 2.5 million packages and records 184 billion downloads monthly, making it the worldโs largest software repository - larger than all other programming language package managers combined. According to GitHub statistics, TypeScript is the third most used language as of 2024, with 78% of JavaScript developers using TypeScript.
This ecosystemโs vastness and integration had a decisive impact on building WrtnLabsโ no-code ecosystem. @autobe
developed both its Agent system and Playground UI application in TypeScript as a single language, providing significant advantages in code sharing, type safety, and development efficiency. Furthermore, @agentica
, which transforms backend applications generated by @autobe
into AI chatbots, and @autoview
, which converts them into frontend applications, were all developed based on TypeScript.
Itโs no coincidence that the entire no-code ecosystem developed by the WrtnLabs team was built on TypeScript. TypeScriptโs powerful type system ensures the stability of AI-generated code, its vast ecosystem enables immediate utilization of all necessary features, and the ability to develop the entire stack with a single language significantly reduces development complexity. This demonstrates that TypeScript was an indispensable choice in realizing WrtnLabsโ vision that โanyone who can converse can become a full-stack developer.โ