Prompt Histories
undefined
import { AutoBeAgent } from "@autobe/agent";
import { AutoBeCompiler } from "@autobe/compiler";
import { AutoBeHistory } from "@autobe/interface";
import OpenAI from "openai";
declare function getHistories(): Promise<AutoBeHistory[]>;
declare function archiveHistories(histories: AutoBeHistory[]): Promise<void>;
const agent = new AutoBeAgent({
model: "chatgpt",
vendor: {
api: new OpenAI({ apiKey: "********" }),
model: "gpt-4.1",
},
compiler: new AutoBeCompiler(),
histories: await getHistories(),
});
await agent.conversate(`
I want to create a political/economic discussion board.
Since I'm not familiar with programming,
please write a requirements analysis report as you see fit.
`);
await archiveHistories(agent.getHistories());
undefined
import { AutoBeAnalyzeHistory } from "./AutoBeAnalyzeHistory";
import { AutoBeAssistantMessageHistory } from "./AutoBeAssistantMessageHistory";
import { AutoBeInterfaceHistory } from "./AutoBeInterfaceHistory";
import { AutoBePrismaHistory } from "./AutoBePrismaHistory";
import { AutoBeRealizeHistory } from "./AutoBeRealizeHistory";
import { AutoBeTestHistory } from "./AutoBeTestHistory";
import { AutoBeUserMessageHistory } from "./AutoBeUserMessageHistory";
/**
* Union type representing all possible history records in the vibe coding
* system.
*
* This comprehensive union encompasses both message histories that track
* conversation flow and development histories that monitor progress through
* various phases of the automated development pipeline. Each history type
* captures specific aspects of the user interaction and agent activities that
* transform conversations into working software.
*
* The union design enables type-safe handling of different history records
* while maintaining a unified interface for storing, retrieving, and processing
* the complete development timeline from initial requirements gathering to
* final code generation.
*
* @author Samchon
*/
export type AutoBeHistory =
| AutoBeUserMessageHistory
| AutoBeAssistantMessageHistory
| AutoBeAnalyzeHistory
| AutoBePrismaHistory
| AutoBeInterfaceHistory
| AutoBeTestHistory
| AutoBeRealizeHistory;
export namespace AutoBeHistory {
/**
* Type alias for extracting the discriminator union from history records.
*
* Provides a convenient way to reference all possible history type values
* including "userMessage", "assistantMessage", "analyze", "prisma",
* "interface", "test", and "realize". This type is useful for type guards,
* switch statements, and other type-safe operations that need to handle
* different history categories.
*/
export type Type = AutoBeHistory["type"];
/**
* Type mapping interface that associates each history type string with its
* corresponding history record interface.
*
* Enables type-safe access to specific history record types based on their
* discriminator values. This mapper is particularly useful for generic
* functions, type narrowing operations, and ensuring compile-time type safety
* when working with history records in a type-dependent manner.
*
* The mapper provides a clean abstraction for converting between type strings
* and their corresponding TypeScript interfaces, facilitating robust history
* management and processing throughout the system.
*/
export interface Mapper {
userMessage: AutoBeUserMessageHistory;
assistantMessage: AutoBeAssistantMessageHistory;
analyze: AutoBeAnalyzeHistory;
prisma: AutoBePrismaHistory;
interface: AutoBeInterfaceHistory;
test: AutoBeTestHistory;
realize: AutoBeRealizeHistory;
}
}
When creating an AutoBeAgent
, you can start from previous conversations by specifying the histories
property. Additionally, you can retrieve the conversation histories of the current AutoBeAgent
by calling the AutoBeAgent.getHistories()
method.
All history types in @autobe
are collected into the AutoBeHistory
type as a union. Each history type represents:
AutoBeUserMessageHistory
AutoBeAssistantMessageHistory
AutoBeAnalyzeHistory
AutoBePrismaHistory
AutoBeInterfaceHistory
AutoBeTestHistory
AutoBeRealizeHistory
Message Histories
undefined
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
import { AutoBeUserMessageContent } from "./contents/AutoBeUserMessageContent";
/**
* History record generated when a user sends a message during the conversation
* flow.
*
* User messages support comprehensive multimodal capabilities, allowing not
* only text input but also image attachments, document file uploads, and voice
* input. This flexibility enables users to communicate requirements, provide
* visual references, share existing documentation, and interact naturally
* through multiple input modalities.
*
* The multimodal support enhances the vibe coding experience by allowing users
* to express their needs through the most appropriate medium, whether that's
* describing requirements in text, showing examples through images, or
* providing specifications through document uploads.
*
* @author Samchon
*/
export interface AutoBeUserMessageHistory
extends AutoBeAgentHistoryBase<"userMessage"> {
/**
* Array of content items that comprise the user's message.
*
* Contains the multimodal content of the user's message, which can include
* various types of {@link AutoBeUserMessageContent} such as text, images,
* document files, and audio inputs. Each content item represents a different
* modality or attachment within the same message.
*
* The array structure allows users to combine multiple content types in a
* single message, such as text description accompanied by reference images or
* documents. This multimodal approach provides rich context for the AI
* assistant to better understand user requirements and generate more accurate
* development artifacts.
*/
contents: AutoBeUserMessageContent[];
}
undefined
import { tags } from "typia";
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
/**
* History record generated when the AI assistant sends a message to the user
* during the conversation flow.
*
* The assistant communicates exclusively through text messages, providing
* responses to user queries, explanations of development processes, progress
* updates, and guidance throughout the vibe coding workflow. Unlike user
* messages which support multimodal content, assistant messages are limited to
* text-only communication.
*
* These message histories serve as a complete record of the assistant's
* contributions to the conversation, enabling conversation replay, context
* understanding, and interaction analysis for improving the development
* experience.
*
* @author Samchon
*/
export interface AutoBeAssistantMessageHistory
extends AutoBeAgentHistoryBase<"assistantMessage"> {
/**
* The text content of the assistant's message.
*
* Contains the complete text response from the AI assistant, which may
* include explanations, progress updates, development guidance, error
* descriptions, or answers to user questions. The assistant uses this text
* communication to guide users through the development process and provide
* context about ongoing operations.
*
* Unlike user messages that support various content types (text, images,
* files, audio), assistant responses are constrained to text-only format for
* consistency and clarity in the conversation flow.
*/
text: string;
/**
* ISO 8601 timestamp indicating when the assistant message was completed.
*
* Marks the exact moment when the AI assistant finished generating and
* sending the response message. This timestamp is essential for maintaining
* proper conversation chronology, tracking response times, and understanding
* the temporal flow of the development conversation.
*/
completed_at: string & tags.Format<"date-time">;
}
undefined
//----------------------------------------
// File: AutoBeUserMessageContent.ts
//----------------------------------------
import { AutoBeUserMessageAudioContent } from "./AutoBeUserMessageAudioContent";
import { AutoBeUserMessageFileContent } from "./AutoBeUserMessageFileContent";
import { AutoBeUserMessageImageContent } from "./AutoBeUserMessageImageContent";
import { AutoBeUserMessageTextContent } from "./AutoBeUserMessageTextContent";
/**
* Union type representing all possible content types within a user message.
*
* This comprehensive multimodal union enables users to communicate through
* various input modalities including text descriptions, visual references
* through images, documentation through file uploads, and natural voice
* interaction through audio. The multimodal approach enhances the vibe coding
* experience by allowing users to express requirements using the most
* appropriate medium for their needs.
*
* Each content type is designed to provide rich context to the AI assistant,
* enabling more accurate understanding of user requirements and generating
* better development artifacts. Users can combine multiple content types within
* a single message to provide comprehensive specification of their needs.
*
* @author Samchon
*/
export type AutoBeUserMessageContent =
| AutoBeUserMessageAudioContent
| AutoBeUserMessageFileContent
| AutoBeUserMessageImageContent
| AutoBeUserMessageTextContent;
export namespace AutoBeUserMessageContent {
/**
* Type alias for extracting the discriminator union from user message content
* types.
*
* Provides a convenient way to reference all possible content type values
* including "audio", "file", "image", and "text". This type is essential for
* type guards, content processing logic, and multimodal input handling
* throughout the conversation system.
*/
export type Type = AutoBeUserMessageContent["type"];
/**
* Type mapping interface that associates each content type string with its
* corresponding content interface.
*
* Enables type-safe processing of different content modalities based on their
* discriminator values. This mapper facilitates robust multimodal content
* handling, ensuring that each content type is processed according to its
* specific characteristics and requirements in the vibe coding pipeline.
*
* The mapper provides compile-time type safety when working with
* heterogeneous content arrays and enables efficient content type-specific
* processing logic.
*/
export interface Mapper {
audio: AutoBeUserMessageAudioContent;
file: AutoBeUserMessageFileContent;
image: AutoBeUserMessageImageContent;
text: AutoBeUserMessageTextContent;
}
}
//----------------------------------------
// File: AutoBeUserMessageAudioContent.ts
//----------------------------------------
import { AutoBeUserMessageContentBase } from "./AutoBeUserMessageContentBase";
/**
* Content type representing audio input from users in the conversation.
*
* Enables natural voice interaction by allowing users to communicate
* requirements, ask questions, and provide specifications through spoken input.
* Voice input enhances the vibe coding experience by providing a more natural
* and efficient way to express complex requirements, especially when describing
* workflows, business processes, or detailed specifications.
*
* The audio content is processed through speech-to-text capabilities, allowing
* the AI assistant to understand and respond to voice-based requirements just
* as effectively as text input. This multimodal approach makes the development
* conversation more accessible and user-friendly.
*
* @author Samchon
*/
export interface AutoBeUserMessageAudioContent
extends AutoBeUserMessageContentBase<"audio"> {
/**
* Base64 encoded audio data containing the user's voice input.
*
* The audio data is encoded in Base64 format to ensure safe transmission and
* storage within the message system. This encoding allows the voice input to
* be processed by speech-to-text services and integrated seamlessly into the
* conversation flow alongside other content types.
*
* The encoded audio maintains the original quality necessary for accurate
* speech recognition while being compatible with standard data transmission
* and storage protocols.
*/
data: string;
/**
* The format of the encoded audio data.
*
* Specifies the audio codec and container format used for the voice input.
* Currently supports "wav" for uncompressed high-quality audio and "mp3" for
* compressed audio with smaller file sizes. The format information ensures
* proper decoding and processing of the audio content.
*
* Different formats may be preferred based on quality requirements, file size
* constraints, and compatibility with speech recognition services.
*/
format: "wav" | "mp3";
}
//----------------------------------------
// File: AutoBeUserMessageFileContent.ts
//----------------------------------------
import { AutoBeUserMessageContentBase } from "./AutoBeUserMessageContentBase";
/**
* User message content for file uploads.
*
* Handles file attachments in user messages, supporting both direct file data
* and file references. Used when users need to share documents, specifications,
* code files, or other resources as part of their development requirements.
*
* @author Samchon
*/
export interface AutoBeUserMessageFileContent
extends AutoBeUserMessageContentBase<"file"> {
/**
* File content data.
*
* Either base64-encoded file data or a reference ID to a previously uploaded
* file.
*/
file: AutoBeUserMessageFileContent.IBase64 | AutoBeUserMessageFileContent.IId;
}
export namespace AutoBeUserMessageFileContent {
/** Direct file upload with base64-encoded data. */
export interface IBase64 {
/** Discriminator indicating this contains direct file data. */
type: "base64";
/** Original filename. */
name: string;
/** Base64-encoded file content. */
data: string;
}
/** File reference by ID. */
export interface IId {
/** Discriminator indicating this is a file reference. */
type: "id";
/** File ID for retrieving previously uploaded file. */
id: string;
}
}
//----------------------------------------
// File: AutoBeUserMessageImageContent.ts
//----------------------------------------
import { tags } from "typia";
import { AutoBeUserMessageContentBase } from "./AutoBeUserMessageContentBase";
/**
* User message content for image uploads.
*
* Handles image attachments in user messages, supporting both base64-encoded
* images and URL references. Used for sharing UI mockups, diagrams,
* screenshots, and other visual materials.
*
* @author Samchon
*/
export interface AutoBeUserMessageImageContent
extends AutoBeUserMessageContentBase<"image"> {
/**
* Image content data.
*
* Either base64-encoded image data or a URL reference.
*/
image:
| AutoBeUserMessageImageContent.IBase64
| AutoBeUserMessageImageContent.IUrl;
/**
* Image analysis detail level.
*
* - "auto": Automatic detail selection
* - "high": Detailed analysis for complex images
* - "low": Fast processing for simple images
*/
detail?: "auto" | "high" | "low" | undefined;
}
export namespace AutoBeUserMessageImageContent {
/** Direct image upload with base64-encoded data. */
export interface IBase64 {
/** Discriminator for base64 type. */
type: "base64";
/** Base64-encoded image data. */
data: string;
}
/** Image reference by URL. */
export interface IUrl {
/** Discriminator for URL type. */
type: "url";
/** Image URL with format validation. */
url: string & tags.Format<"url">;
}
}
//----------------------------------------
// File: AutoBeUserMessageTextContent.ts
//----------------------------------------
import { AutoBeUserMessageContentBase } from "./AutoBeUserMessageContentBase";
/**
* Content type representing textual input from users in the conversation.
*
* Serves as the primary communication medium for expressing requirements,
* asking questions, providing clarifications, and engaging in detailed
* discussions about development needs. Text content remains the most
* fundamental and versatile way for users to communicate complex business
* logic, technical specifications, and nuanced requirements in the vibe coding
* process.
*
* While the system supports multimodal input including audio, images, and
* files, text content provides the precision and clarity needed for detailed
* requirement specification and iterative refinement of development goals. It
* enables users to articulate complex business processes, technical
* constraints, and specific implementation preferences with the detail
* necessary for accurate code generation.
*
* @author Samchon
*/
export interface AutoBeUserMessageTextContent
extends AutoBeUserMessageContentBase<"text"> {
/**
* The textual content of the user's message.
*
* Contains the user's written communication including requirements
* descriptions, questions, feedback, clarifications, or any other textual
* input that guides the development process. This text serves as the primary
* source of business logic understanding and technical requirement
* specification.
*
* The text content can range from simple queries to comprehensive requirement
* documents, architectural decisions, feature specifications, or detailed
* business process descriptions that inform the entire vibe coding pipeline
* from analysis through implementation.
*/
text: string;
}
Message histories are divided into user conversation history AutoBeUserMessageHistory
and assistant conversation history AutoBeAssistantMessageHistory
.
For users, multimodal capabilities are supported, allowing not only text but also image/document file attachments and voice input, which results in different content types. The assistant communicates only through text, so its content type is limited to string
.
Development Histories
AutoBeAnalyzeHistory
import { tags } from "typia";
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
import { AutoBeAnalyzeFile } from "./contents/AutoBeAnalyzeFile";
import { AutoBeAnalyzeRole } from "./contents/AutoBeAnalyzeRole";
/**
* History record generated when the Analyze agent and user have completed all
* discussions regarding requirements, and a comprehensive analysis report has
* been issued.
*
* The Analyze agent follows a structured workflow from initial drafting to
* final completion, producing multiple markdown documents that capture business
* requirements, technical specifications, and architectural decisions. This
* analysis serves as the foundation for all subsequent development phases
* including database design and API specification.
*
* The requirements analysis process transforms user conversations and business
* needs into structured documentation that guides the entire vibe coding
* pipeline, ensuring that technical implementation accurately reflects business
* intentions.
*
* @author Samchon
*/
export interface AutoBeAnalyzeHistory
extends AutoBeAgentHistoryBase<"analyze"> {
/**
* Reason why the Analyze agent was activated through function calling.
*
* Explains the specific circumstances that triggered the AI chatbot to invoke
* the Analyze agent via function calling. This could include reasons such as
* initial project requirements gathering, requests for requirement
* clarification, updates to existing requirements based on user feedback, or
* revision requests for the analysis report.
*/
reason: string;
/**
* Iteration number of this requirements analysis report.
*
* Indicates which revision of the requirements analysis this represents. A
* value of 0 means this is the initial requirements analysis, while higher
* values represent subsequent revisions based on user feedback or additional
* requirements gathering.
*
* If other development artifacts (Prisma, Interface, Test histories) have
* step values lower than this value, it means those artifacts have not been
* updated to reflect the latest requirements and may need regeneration.
*/
step: number;
/**
* Project alias prefix that will be applied to all generated artifacts.
*
* A short project identifier that will be consistently used as a prefix for
* database table names, API function names, and DTO type names throughout the
* entire codebase. This ensures consistent naming conventions and helps avoid
* naming conflicts in larger systems.
*
* For example, if the prefix is "shopping", generated artifacts might include
* tables like `shopping_customers` and DTOs like `IShoppingCartCommodity`.
*/
prefix: string;
/**
* Generated requirements analysis report files as key-value pairs.
*
* Contains the complete set of markdown documents that comprise the
* requirements analysis report. Each key represents the filename and each
* value contains the actual markdown content. The report typically includes
* business context, functional requirements, technical specifications,
* architectural decisions, and implementation guidelines.
*
* These documents serve as the authoritative source for understanding project
* requirements and guide all subsequent development phases in the vibe coding
* pipeline.
*/
files: AutoBeAnalyzeFile[];
/**
* ISO 8601 timestamp indicating when the requirements analysis was completed.
*
* Marks the exact moment when the Analyze agent finished the complete
* analysis workflow including drafting, review, amendments, and finalization.
* This timestamp is crucial for tracking the development timeline and
* determining which development artifacts need updating based on requirement
* changes.
*/
completed_at: string & tags.Format<"date-time">;
/**
* List of roles identified during the requirements analysis process.
*
* Contains the various user roles, personas, or stakeholder types that were
* identified and analyzed during the requirements gathering phase. These
* roles help define different user perspectives, access levels, and
* functional requirements needed for the system being developed.
*/
roles: AutoBeAnalyzeRole[];
}
AutoBeAnalyzeHistory
is a history generated when the @autobe
agent and user have completed all discussions regarding requirements, and a report has been issued. The report consists of multiple markdown documents, which are stored in the files
property.
The step
property indicates which iteration of the requirements analysis report this represents. If this value is not 0, it means the requirements analysis report has been revised that many times. If the step
value of other histories is lower than AutoBeAnalyzeHistory.step
, it means those histories have not been reflected in the latest requirements analysis report.
AutoBePrismaHistory
undefined
import { tags } from "typia";
import { IAutoBePrismaCompileResult } from "../compiler";
import { IAutoBePrismaValidation } from "../prisma";
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
/**
* History record generated when the Prisma agent analyzes the requirements
* specification and completes the database design.
*
* The Prisma agent constructs data of type {@link AutoBePrisma.IApplication}
* through AI function calling, validates it, and then generates prisma schema
* files. This history captures the complete database design process including
* validation results, generated schema files, and compilation outcomes.
*
* The database design process follows a sophisticated three-tier compiler
* infrastructure that transforms business requirements into validated database
* architectures through AST (Abstract Syntax Tree) manipulation, ensuring 100%
* syntactic correctness while maintaining semantic integrity.
*
* @author Samchon
*/
export interface AutoBePrismaHistory extends AutoBeAgentHistoryBase<"prisma"> {
/**
* Validation results of the constructed {@link AutoBePrisma.IApplication}
* data.
*
* Contains the outcome of validating the AST structures generated through AI
* function calling. The Prisma agent generally creates valid
* {@link AutoBePrisma.IApplication} data through a validation feedback
* process, but when using very small AI models, this result might have
* `success := false`.
*
* The validation includes:
*
* - Relationship graph analysis to detect circular dependencies
* - Business logic validation for constraint compliance
* - Performance optimization analysis for query patterns
* - Security constraint enforcement for data access patterns
*/
result: IAutoBePrismaValidation;
/**
* Generated Prisma schema files as key-value pairs.
*
* Each key represents the filename (following the pattern
* `schema-{number}-{domain}.prisma`) and each value contains the actual
* Prisma schema content. These files are organized by business domains
* following domain-driven design principles.
*
* The schemas are generated through deterministic code generation that
* transforms validated AST structures into production-ready Prisma schema
* files with comprehensive documentation, optimal indexes, and proper
* constraints.
*/
schemas: Record<string, string>;
/**
* Results of compiling the generated Prisma schema files.
*
* Contains the compilation outcome when the generated schemas are processed
* by the Prisma compiler. This should always compile successfully since the
* schemas are generated from validated AST structures. If compilation fails,
* it would be a bug in the system and should be reported as an issue.
*
* The compilation process includes validation of syntax, relationships, and
* database-specific constraints to ensure the schemas will work correctly in
* the target database environment.
*/
compiled: IAutoBePrismaCompileResult;
/**
* Reason why the Prisma agent was activated through function calling.
*
* Explains the specific circumstances that triggered the AI chatbot to invoke
* the Prisma agent via function calling. This could include reasons such as
* new requirements that require database schema changes, updates to existing
* requirements that affect data models, or initial database design requests
* from the user conversation.
*/
reason: string;
/**
* Iteration number of the requirements analysis report this database design
* was performed for.
*
* Indicates which version of the requirements analysis this database design
* reflects. If this value is lower than {@link AutoBeAnalyzeHistory.step}, it
* means the database design has not yet been updated to reflect the latest
* requirements and may need to be regenerated.
*
* A value of 0 indicates the initial database design, while higher values
* represent subsequent revisions based on updated requirements.
*/
step: number;
/**
* ISO 8601 timestamp indicating when the database design process was
* completed.
*
* Marks the exact moment when the Prisma schema generation, validation, and
* compilation process finished successfully. This timestamp is crucial for
* tracking the development timeline and determining the currency of the
* database design relative to other development artifacts.
*/
completed_at: string & tags.Format<"date-time">;
}
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 { AutoBePrisma } from "./AutoBePrisma";
/**
* Union type representing the result of Prisma schema validation.
*
* This type encapsulates the outcome of validating an AutoBePrisma.IApplication
* structure against Prisma schema rules and business constraints. The
* validation process checks for structural integrity, referential consistency,
* naming conventions, and compliance with the established schema generation
* rules.
*
* The validation can result in either complete success (all rules satisfied) or
* failure with detailed error information for precise error resolution.
*
* @author Samchon
*/
export type IAutoBePrismaValidation =
| IAutoBePrismaValidation.ISuccess
| IAutoBePrismaValidation.IFailure;
/**
* Namespace containing all interfaces for Prisma schema validation results.
*
* This namespace defines the structure for validation responses from the schema
* validation system, providing detailed feedback about schema correctness and
* specific error locations when validation fails.
*/
export namespace IAutoBePrismaValidation {
/**
* Interface representing a successful validation result.
*
* This interface is returned when the AutoBePrisma.IApplication structure
* passes all validation rules including:
*
* - No duplicate model names across all files
* - No duplicate field names within any model
* - No duplicate relation names within any model
* - All foreign key references point to existing models
* - All field types are valid and properly configured
* - All indexes follow the established rules (no single foreign key indexes)
* - All naming conventions are properly applied (plural models, snake_case
* fields)
* - All business constraints are satisfied
*/
export interface ISuccess {
/**
* Validation success indicator.
*
* Always true for successful validation results. This discriminator
* property allows TypeScript to properly narrow the union type and provides
* runtime type checking for validation result processing.
*/
success: true;
/**
* The validated and approved AutoBePrisma application structure.
*
* This contains the complete, validation-passed schema definition that can
* be safely passed to the code generator for Prisma schema file creation.
* All models, fields, relationships, and indexes in this structure have
* been verified for correctness and compliance with schema rules.
*
* Important: This may not be identical to the original input application.
* The validation process can apply automatic corrections to resolve
* validation issues such as removing duplicates or fixing structural
* problems. These corrections preserve the original business intent while
* ensuring schema consistency and data integrity.
*/
data: AutoBePrisma.IApplication;
}
/**
* Interface representing a failed validation result with detailed error
* information.
*
* This interface is returned when the AutoBePrisma.IApplication structure
* contains one or more validation errors. It provides both the original
* (potentially flawed) application structure and a comprehensive list of
* specific errors that need to be resolved.
*
* The error information is structured to enable precise error location
* identification and targeted fixes without affecting unrelated parts of the
* schema.
*/
export interface IFailure {
/**
* Validation failure indicator.
*
* Always false for failed validation results. This discriminator property
* allows TypeScript to properly narrow the union type and indicates that
* the errors array contains specific validation issues that must be
* resolved.
*/
success: false;
/**
* The original AutoBePrisma application structure that failed validation.
*
* This contains the complete schema definition as it was submitted for
* validation, including all the elements that caused validation errors.
* This structure serves as the baseline for error analysis and correction,
* allowing error-fixing systems to understand the full context of the
* schema while addressing specific validation issues.
*/
data: AutoBePrisma.IApplication;
/**
* Array of specific validation errors found in the application structure.
*
* Each error provides precise location information (file path, model name,
* field name) and detailed error descriptions to enable targeted fixes.
* Errors are ordered by severity and location to facilitate systematic
* resolution. The array will never be empty when success is false.
*
* Common error categories include:
*
* - Duplication errors (duplicate models, fields, relations)
* - Reference errors (invalid foreign key targets, missing models)
* - Type validation errors (invalid field types, constraint violations)
* - Index configuration errors (invalid field references, forbidden single FK
* indexes)
* - Naming convention violations (non-plural models, invalid field names)
*/
errors: IError[];
}
/**
* Interface representing a specific validation error with precise location
* information.
*
* This interface provides detailed information about individual validation
* errors, including exact location within the schema structure and
* comprehensive error descriptions. The location information enables
* error-fixing systems to pinpoint exactly where problems occur without
* manual search or guesswork.
*
* Each error represents a specific violation of schema rules that must be
* resolved for successful validation.
*/
export interface IError {
/**
* File path where the validation error occurs.
*
* Specifies the exact schema file within the
* AutoBePrisma.IApplication.files array where this error was detected. This
* corresponds to the filename property of the IFile interface and enables
* targeted file-level error resolution.
*
* Examples: "schema-01-articles.prisma", "schema-03-actors.prisma"
*
* This path information allows error-fixing systems to:
*
* - Navigate directly to the problematic file
* - Understand cross-file reference issues
* - Apply fixes within the correct file context
* - Maintain proper file organization during error resolution
*/
path: string;
/**
* Name of the model (database table) where the validation error occurs.
*
* Specifies the exact model within the identified file that contains the
* validation error. This corresponds to the name property of the IModel
* interface and enables targeted model-level error resolution.
*
* Examples: "shopping_customers", "bbs_articles",
* "mv_shopping_sale_last_snapshots"
*
* When null, indicates file-level errors such as:
*
* - Duplicated file names
* - Invalid file names
*
* This model information allows error-fixing systems to:
*
* - Navigate directly to the problematic model definition
* - Understand model-specific constraint violations
* - Apply fixes within the correct model context
* - Resolve cross-model relationship issues
*/
table: string | null;
/**
* Name of the specific field (column) where the validation error occurs.
*
* Specifies the exact field within the identified model that contains the
* validation error, or null for model-level errors that don't relate to a
* specific field. This corresponds to field names in primaryField,
* foreignFields, or plainFields arrays of the IModel interface.
*
* Examples: "shopping_customer_id", "created_at", "name", null
*
* When null, indicates model-level errors such as:
*
* - Duplicate model names across files
* - Missing primary key definitions
* - Invalid model naming conventions
* - Model-level constraint violations
*
* When string, indicates field-level errors such as:
*
* - Duplicate field names within the model
* - Invalid field types or constraints
* - Invalid foreign key configurations
* - Field naming convention violations
*
* This field information allows error-fixing systems to:
*
* - Navigate directly to the problematic field definition
* - Distinguish between model-level and field-level issues
* - Apply targeted fixes without affecting other fields
* - Resolve field-specific constraint violations
*/
field: string | null;
/**
* Detailed human-readable description of the validation error.
*
* Provides comprehensive information about what validation rule was
* violated, why it's problematic, and often hints at how to resolve the
* issue. The message is designed to be informative enough for both
* automated error-fixing systems and human developers to understand and
* address the problem.
*
* Message format typically includes:
*
* - Clear description of what rule was violated
* - Specific details about the problematic element
* - Context about why this causes validation failure
* - Sometimes suggestions for resolution approaches
*
* This message information allows error-fixing systems to:
*
* - Understand the exact nature of the validation failure
* - Implement appropriate resolution strategies
* - Provide meaningful feedback to developers
* - Log detailed error information for debugging
* - Make informed decisions about fix approaches
*/
message: string;
}
}
undefined
/**
* Result of compiling and processing Prisma schema files through the custom
* Prisma Compiler.
*
* This union type represents all possible outcomes when the Prisma Compiler
* transforms validated {@link AutoBePrisma.IApplication} AST structures into
* production-ready artifacts. The compilation process includes schema
* validation, documentation generation, ERD diagram creation, and dependency
* resolution.
*
* The compiler should always produce successful results since it operates on
* pre-validated AST structures. Failure cases typically indicate issues with
* the compilation environment or unexpected edge cases that should be reported
* as bugs.
*
* @author Samchon
*/
export type IAutoBePrismaCompileResult =
| IAutoBePrismaCompileResult.ISuccess
| IAutoBePrismaCompileResult.IFailure
| IAutoBePrismaCompileResult.IException;
export namespace IAutoBePrismaCompileResult {
/**
* Successful compilation result containing all generated artifacts.
*
* Represents the ideal outcome where the Prisma schema compilation completed
* without errors and produced all expected outputs including documentation,
* diagrams, and dependency files ready for deployment.
*/
export interface ISuccess {
/** Discriminator indicating successful compilation. */
type: "success";
/**
* Generated comprehensive documentation for the database schema.
*
* Contains detailed markdown documentation automatically synthesized from
* AST descriptions, including business context, technical constraints, and
* operational characteristics for every model and field. This documentation
* becomes an integral part of the codebase for ongoing maintenance.
*/
document: string;
/**
* Generated Entity Relationship Diagrams as key-value pairs.
*
* Each key represents the diagram filename and each value contains the
* diagram content (typically in Mermaid or other visualization format).
* These diagrams are automatically generated through integration with
* [`prisma-markdown`](https://github.com/samchon/prisma-markdown|prisma-markdown)
* and provide visual documentation that stays synchronized with
* implementation.
*/
diagrams: Record<string, string>;
/**
* Final Prisma schema files optimized for production deployment.
*
* Contains the definitive schema files with all optimizations applied,
* including automatically generated indexes, constraints, and performance
* enhancements. These schemas are ready for immediate deployment to the
* target database environment.
*/
schemas: Record<string, string>;
/**
* Generated Node.js dependency files and configurations.
*
* Includes package.json configurations, TypeScript definitions, and other
* Node.js ecosystem files required for proper integration with the
* generated Prisma schemas. Ensures seamless compatibility with existing
* development and deployment workflows.
*/
nodeModules: Record<string, string>;
}
/**
* Compilation failure with detailed error information.
*
* Represents cases where the compilation process encountered logical or
* semantic errors that prevented successful generation of artifacts. This
* should be rare since compilation operates on pre-validated AST structures.
*/
export interface IFailure {
/** Discriminator indicating compilation failure. */
type: "failure";
/**
* Detailed explanation of why the compilation failed.
*
* Provides specific information about the error condition, including
* context about which part of the compilation process failed and potential
* remediation steps. This information is crucial for debugging and
* improving the compilation process.
*/
reason: string;
}
/**
* Unexpected exception during compilation process.
*
* Represents cases where the compilation process encountered an unexpected
* runtime error or system exception. These cases indicate potential bugs in
* the compiler implementation that should be investigated and reported.
*/
export interface IException {
/** Discriminator indicating compilation exception. */
type: "exception";
/**
* The raw error or exception that occurred during compilation.
*
* Contains the original error object or exception details for debugging
* purposes. This information helps developers identify the root cause of
* unexpected compilation failures and improve system reliability.
*/
error: unknown;
}
}
AutoBePrismaHistory
is a history generated when @autobe
analyzes the requirements specification and completes the database design.
@autobe
constructs data of type AutoBePrisma.IApplication
through AI function calling, validates it, and then generates prisma schema files. The validation results are stored in the result
property as type IAutoBePrismaValidation
, and the results of converting this to prisma schema files (code generation) are stored in the schemas
property.
Note that @autobe
generally creates valid AutoBePrisma.IApplication
data through a validation feedback process. However, when using very small AI models, the IAutoBePrismaValidation
result might have success := false
. Additionally, the results of compiling the prisma schema files are stored in the compiled
property as type IAutoBePrismaCompileResult
, which should always compile successfully. If compilation fails, it would be a bug in @autobe
, so please report it as an issue.
The step
property indicates which requirements analysis report iteration the database design was performed for. If the AutoBePrismaHistory.step
value is lower than AutoBeAnalyzeHistory.step
, it means the database design has not yet been updated to reflect the latest requirements.
AutoBeInterfaceHistory
undefined
import { tags } from "typia";
import { AutoBeOpenApi } from "../openapi/AutoBeOpenApi";
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
import { AutoBeInterfaceAuthorization } from "./contents";
/**
* History record generated when the Interface agent completes RESTful API
* design based on the previous requirements analysis report and database
* design.
*
* The Interface agent constructs data of type {@link AutoBeOpenApi.IDocument}
* through AI function calling, validates it, and stores it in the document
* property. This is then converted to a formal OpenAPI document, and NestJS API
* controllers, DTOs, and e2e test code are generated through the sophisticated
* multi-stage transformation pipeline.
*
* The Interface agent operates on the same vibe coding principles as other
* agents, ensuring that API designs are syntactically perfect and semantically
* aligned with business requirements before any code generation occurs.
*
* @author Samchon
*/
export interface AutoBeInterfaceHistory
extends AutoBeAgentHistoryBase<"interface"> {
/**
* The constructed OpenAPI document containing the complete API specification.
*
* Contains the validated {@link AutoBeOpenApi.IDocument} AST structure that
* defines all API endpoints, operations, schemas, and business logic. This
* document serves as the source of truth for API generation and ensures
* perfect alignment between database schemas and API interfaces.
*
* The document includes comprehensive business logic integration, type safety
* bridges with Prisma schemas, and security pattern validation to ensure
* enterprise-grade API specifications.
*/
document: AutoBeOpenApi.IDocument;
/**
* JWT-based authentication and authorization operations generated for each
* user role.
*
* Contains role-specific authentication API operations including essential
* flows (join, login, validate, changePassword, refresh) plus additional
* operations based on Prisma schema capabilities like email verification and
* password reset. These operations are generated by analyzing the database
* schema to determine which authentication features are supported for each
* role.
*/
authorizations: AutoBeInterfaceAuthorization[];
/**
* Reason why the Interface agent was activated through function calling.
*
* Explains the specific circumstances that triggered the AI chatbot to invoke
* the Interface agent via function calling. This could include reasons such
* as completing initial API design after database schema creation, updating
* API specifications due to requirement changes, or regenerating interfaces
* to reflect modified data models.
*/
reason: string;
/**
* Iteration number of the requirements analysis report this API design was
* performed for.
*
* Indicates which version of the requirements analysis this API design
* reflects. If this value is lower than {@link AutoBeAnalyzeHistory.step}, it
* means the API design has not yet been updated to reflect the latest
* requirements and may need to be regenerated.
*
* A value of 0 indicates the initial API design, while higher values
* represent subsequent revisions based on updated requirements or database
* schema changes.
*/
step: number;
/**
* ISO 8601 timestamp indicating when the API design process was completed.
*
* Marks the exact moment when the Interface agent finished the complete
* transformation pipeline from AST construction through OpenAPI validation to
* NestJS code generation. This timestamp is crucial for tracking the
* development timeline and determining the currency of the API design
* relative to other development artifacts.
*/
completed_at: string & tags.Format<"date-time">;
}
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";
}
}
undefined
import { OpenApiV3 } from "./OpenApiV3";
import { OpenApiV3_1 } from "./OpenApiV3_1";
import { SwaggerV2 } from "./SwaggerV2";
import { OpenApiV3Downgrader } from "./converters/OpenApiV3Downgrader";
import { OpenApiV3Upgrader } from "./converters/OpenApiV3Upgrader";
import { OpenApiV3_1Emender } from "./converters/OpenApiV3_1Emender";
import { SwaggerV2Downgrader } from "./converters/SwaggerV2Downgrader";
import { SwaggerV2Upgrader } from "./converters/SwaggerV2Upgrader";
import { IJsonSchemaAttribute } from "./structures/IJsonSchemaAttribute";
/**
* Emended OpenAPI v3.1 definition used by `typia` and `nestia`.
*
* `OpenApi` is a namespace containing functions and interfaces for emended
* OpenAPI v3.1 specification. The keyword "emended" means that `OpenApi` is not
* a direct OpenAPI v3.1 specification ({@link OpenApiV3_1}), but a little bit
* shrunk to remove ambiguous and duplicated expressions of OpenAPI v3.1 for the
* convenience of `typia` and `nestia`.
*
* For example, when representing nullable type, OpenAPI v3.1 supports three
* ways. In that case, `OpenApi` remains only the third way, so that makes
* `typia` and `nestia` (especially `@nestia/editor`) to be simple and easy to
* implement.
*
* 1. `{ type: ["string", "null"] }`
* 2. `{ type: "string", nullable: true }`
* 3. `{ oneOf: [{ type: "string" }, { type: "null" }] }`
*
* Here is the entire list of differences between OpenAPI v3.1 and emended
* `OpenApi`.
*
* - Operation
*
* - Merge {@link OpenApiV3_1.IPath.parameters} to
* {@link OpenApi.IOperation.parameters}
* - Resolve {@link OpenApi.IJsonSchema.IReference references} of
* {@link OpenApiV3_1.IOperation} members
* - Escape references of {@link OpenApiV3_1.IComponents.examples}
* - JSON Schema
*
* - Decompose mixed type: {@link OpenApiV3_1.IJsonSchema.IMixed}
* - Resolve nullable property:
* {@link OpenApiV3_1.IJsonSchema.__ISignificant.nullable}
* - Array type utilizes only single {@link OpenApi.IJsonSchema.IArray.items}
* - Tuple type utilizes only {@link OpenApi.IJsonSchema.ITuple.prefixItems}
* - Merge {@link OpenApiV3_1.IJsonSchema.IAllOf} to
* {@link OpenApi.IJsonSchema.IObject}
* - Merge {@link OpenApiV3_1.IJsonSchema.IAnyOf} to
* {@link OpenApi.IJsonSchema.IOneOf}
* - Merge {@link OpenApiV3_1.IJsonSchema.IRecursiveReference} to
* {@link OpenApi.IJsonSchema.IReference}
*
* @author Jeongho Nam - https://github.com/samchon
*/
export namespace OpenApi {
/** Method of the operation. */
export type Method =
| "get"
| "post"
| "put"
| "delete"
| "options"
| "head"
| "patch"
| "trace";
/**
* Convert Swagger or OpenAPI document into emended OpenAPI v3.1 document.
*
* @param input Swagger or OpenAPI document to convert
* @returns Emended OpenAPI v3.1 document
*/
export function convert(
input:
| SwaggerV2.IDocument
| OpenApiV3.IDocument
| OpenApiV3_1.IDocument
| OpenApi.IDocument,
): IDocument {
if (OpenApiV3_1.is(input))
return OpenApiV3_1Emender.convert(input) as IDocument;
else if (OpenApiV3.is(input))
return OpenApiV3Upgrader.convert(input) as IDocument;
else if (SwaggerV2.is(input))
return SwaggerV2Upgrader.convert(input) as IDocument;
throw new TypeError("Unrecognized Swagger/OpenAPI version.");
}
/**
* Downgrade to Swagger v2.0 document.
*
* Downgrade the given document (emended OpenAPI v3.1) into Swagger v2.0.
*
* @param document Emended OpenAPI v3.1 document to downgrade
* @param version Version to downgrade
* @returns Swagger v2.0 document
*/
export function downgrade(
document: IDocument,
version: "2.0",
): SwaggerV2.IDocument;
/**
* Downgrade to OpenAPI v3.0 document.
*
* Downgrade the given document (emended OpenAPI v3.1) into OpenAPI v3.0.
*
* @param document Emended OpenAPI v3.1 document to downgrade
* @param version Version to downgrade
* @returns OpenAPI v3.0 document
*/
export function downgrade(
document: IDocument,
version: "3.0",
): OpenApiV3.IDocument;
/** @internal */
export function downgrade(
document: IDocument,
version: string,
): SwaggerV2.IDocument | OpenApiV3.IDocument {
if (version === "2.0") return SwaggerV2Downgrader.downgrade(document);
else if (version === "3.0") return OpenApiV3Downgrader.downgrade(document);
throw new TypeError("Unrecognized Swagger/OpenAPI version.");
}
/* -----------------------------------------------------------
PATH ITEMS
----------------------------------------------------------- */
/**
* OpenAPI document.
*
* `OpenApi.IDocument` represents an OpenAPI document of emended OpenAPI v3.1.
*
* In other words, `OpenApi.IDocument` is a structure of `swagger.json` file
* of OpenAPI v3.1 specification, but a little bit shrunk to remove ambiguous
* and duplicated expressions of OpenAPI v3.1 for the convenience and
* clarity.
*/
export interface IDocument {
/** OpenAPI version number. */
openapi: `3.1.${number}`;
/** List of servers that provide the API. */
servers?: IServer[];
/** Information about the API. */
info?: IDocument.IInfo;
/**
* An object to hold reusable data structures.
*
* It stores both DTO schemas and security schemes.
*
* For reference, `nestia` defines every object and alias types as reusable
* DTO schemas. The alias type means that defined by `type` keyword in
* TypeScript.
*/
components: IComponents;
/**
* The available paths and operations for the API.
*
* The 1st key is the path, and the 2nd key is the HTTP method.
*/
paths?: Record<string, IPath>;
/**
* An object to hold Webhooks.
*
* Its structure is the same as {@link paths}, so the first key is the path,
* and the second key is the HTTP method.
*/
webhooks?: Record<string, IPath>;
/**
* A declaration of which security mechanisms can be used across the API.
*
* When this property is configured, it will be overwritten in every API
* route.
*
* For reference, the key means the name of the security scheme and the value means the
* `scopes`. The `scopes` can be used only when the target security scheme is
* `oauth2` type, especially for
* {@link ISwaggerSecurityScheme.IOAuth2.IFlow.scopes} property.
*/
security?: Record<string, string[]>[];
/**
* List of tag names with descriptions.
*
* It is possible to omit this property or skip some tag names even if the
* tag name is used in the API routes. In that case, the tag name will be
* displayed (in Swagger-UI) without description.
*/
tags?: IDocument.ITag[];
/** Flag for indicating this document is emended by `@samchon/openapi` v4. */
"x-samchon-emended-v4": true;
}
export namespace IDocument {
/** Information about the API. */
export interface IInfo {
/** The title of the API. */
title: string;
/** A short summary of the API. */
summary?: string;
/** A full description of the API. */
description?: string;
/** A URL to the Terms of Service for the API. */
termsOfService?: string;
/** The contact information for the exposed API. */
contact?: IContact;
/** The license information for the exposed API. */
license?: ILicense;
/** Version of the API. */
version: string;
}
/**
* OpenAPI tag information.
*
* It is possible to skip composing this structure, even if some tag names
* are registered in the API routes ({@link OpenApi.IOperation.tags}). In
* that case, the tag name will be displayed in Swagger-UI without
* description.
*
* However, if you want to describe the tag name, you can compose this
* structure and describe the tag name in the {@link description} property.
*/
export interface ITag {
/** The name of the tag. */
name: string;
/** An optional string describing the tag. */
description?: string;
}
/** Contact information for the exposed API. */
export interface IContact {
/** The identifying name of the contact person/organization. */
name?: string;
/** The URL pointing to the contact information. */
url?: string;
/**
* The email address of the contact person/organization.
*
* @format email
*/
email?: string;
}
/** License information for the exposed API. */
export interface ILicense {
/** The license name used for the API. */
name: string;
/**
* Identifier for the license used for the API.
*
* Example: MIT
*/
identifier?: string;
/** A URL to the license used for the API. */
url?: string;
}
}
/** The remote server that provides the API. */
export interface IServer {
/** A URL to the target host. */
url: string;
/** An optional string describing the target server. */
description?: string;
/**
* A map between a variable name and its value.
*
* When the server {@link url} is a template type, this property will be
* utilized to fill the template with actual values.
*/
variables?: Record<string, IServer.IVariable>;
}
export namespace IServer {
/** A variable for the server URL template. */
export interface IVariable {
/** Default value to use for substitution. */
default: string;
/** List of available values for the variable. */
enum?: string[];
/** An optional description for the server variable. */
description?: string;
}
}
/* -----------------------------------------------------------
OPERATORS
----------------------------------------------------------- */
/**
* Path item.
*
* `OpenApi.IPath` represents a path item of emended OpenAPI v3.1, collecting
* multiple method operations under a single path.
*/
export interface IPath extends Partial<Record<Method, IOperation>> {
/** Servers that provide the path operations. */
servers?: IServer[];
/** Summary of the path. */
summary?: string;
/** Description of the path. */
description?: string;
}
/**
* Remote operation information.
*
* `OpenApi.IOperation` represents a RESTful API operation provided by the
* remote server.
*/
export interface IOperation {
/** Unique string used to identify the operation. */
operationId?: string;
/** List of parameters that are applicable for this operation. */
parameters?: IOperation.IParameter[];
/** The request body applicable for this operation. */
requestBody?: IOperation.IRequestBody;
/**
* The list of possible responses as they are returned from executing this
* operation. Its key is the HTTP status code, and the value is the metadata
* of the response in the HTTP status code.
*/
responses?: Record<string, IOperation.IResponse>;
/** A list of servers providing this API operation. */
servers?: IServer[];
/** A short summary of what the operation does. */
summary?: string;
/** A verbose explanation of the operation behavior. */
description?: string;
/**
* List of securities and their scopes that are required for execution.
*
* When this property is configured, the RESTful API operation requires the
* matching security value for execution. Its key means the security key matching
* {@link OpenApi.IDocument.security}.
*
* The value means scopes required for the security key when the security
* type is {@link OpenApi.ISecurityScheme.IOAuth2}. Otherwise, if the target
* security type is not {@link OpenApi.ISecurityScheme.IOAuth2}, the value
* will be an empty array.
*/
security?: Record<string, string[]>[];
/** Tags for API documentation control. */
tags?: string[];
/** Flag for indicating this operation is deprecated. */
deprecated?: boolean;
/**
* Flag for indicating this operation is human-only.
*
* If this property value is `true`, the {@link HttpLlm.application} function
* will not convert this operation schema into the LLM function calling
* schema that is represented by the {@link IHttpLlmFunction} interface.
*/
"x-samchon-human"?: boolean;
/**
* Accessor of the operation.
*
* If you configure this property, the assigned value will be used as
* {@link IHttpMigrateRoute.accessor}. Also, it can be used as the
* {@link IHttpLlmFunction.name} by joining with `.` character in the LLM
* function calling application.
*
* Note that the `x-samchon-accessor` value must be unique in the entire
* OpenAPI document operations. If there are duplicated `x-samchon-accessor`
* values, {@link IHttpMigrateRoute.accessor} will ignore all duplicated
* `x-samchon-accessor` values and generate the
* {@link IHttpMigrateRoute.accessor} by itself.
*/
"x-samchon-accessor"?: string[];
/**
* Controller of the operation.
*
* If you configure this property, the assigned value will be utilized as
* the controller name in the OpenAPI generator library like
* [`@nestia/editor`](https://nestia.io/docs/editor/) and
* [`@nestia/migrate`](https://nestia.io/docs/migrate/).
*
* Also, if {@link x-samchon-accessor} has been configured, its last element
* will be used as the controller method (function) name. Of course, the
* OpenAPI document generator `@nestia/sdk` fills both of them.
*/
"x-samchon-controller"?: string;
}
export namespace IOperation {
/** Parameter of the operation. */
export interface IParameter {
/**
* Representative name of the parameter.
*
* In most cases, the `name` is equivalent to the parameter variable name.
* Therefore, the `name` must be filled with the significant variable name
* of the parameter.
*
* Note: Only when the {@link in} property is `path`, the `name` can
* be omitted. In that case, the `name` is automatically deduced from the
* URL path's positional template argument analysis.
*/
name?: string;
/**
* Location of the parameter.
*
* The `in` property is a string that determines the location of the
* parameter.
*
* - `path`: parameter is part of the path of the URL.
* - `query`: parameter is part of the query string.
* - `header`: parameter is part of the header.
* - `cookie`: parameter is part of the cookie.
*/
in: "path" | "query" | "header" | "cookie";
/** Type info of the parameter. */
schema: IJsonSchema;
/**
* Whether the parameter is required for execution or not.
*
* If the parameter is required, the value must be filled. Otherwise, it
* is possible to skip the parameter when executing the API operation.
*
* For reference, the `required` property must always be `true` when the
* {@link in} property is `path`. Otherwise, the `required` property can be
* any of these values: `true`, `false`, or `undefined`.
*/
required?: boolean;
/** Short title of the parameter. */
title?: string;
/** Verbose explanation of the parameter. */
description?: string;
/** Example value of the parameter. */
example?: any;
/** Collection of example values of the parameter with keys. */
examples?: Record<string, IExample>;
}
/** Request body of the operation. */
export interface IRequestBody {
content?: IContent;
description?: string;
required?: boolean;
"x-nestia-encrypted"?: boolean;
}
/** Response of the operation. */
export interface IResponse {
headers?: Record<string, IOperation.IParameter>;
content?: IContent;
description?: string;
"x-nestia-encrypted"?: boolean;
}
/** List of content types supported in request/response body. */
export interface IContent
extends Partial<Record<ContentType, IMediaType>> {}
/** Media type of a request/response body. */
export interface IMediaType {
schema?: IJsonSchema;
example?: any;
examples?: Record<string, IExample>;
}
/** List of supported content media types. */
export type ContentType =
| "text/plain"
| "application/json"
| "application/x-www-form-url-encoded"
| "multipart/form-data"
| "*/*"
| (string & {});
}
/** Example of the operation parameter or response. */
export interface IExample {
summary?: string;
description?: string;
value?: any;
externalValue?: string;
}
/* -----------------------------------------------------------
SCHEMA DEFINITIONS
----------------------------------------------------------- */
/**
* 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.
*/
schemas?: Record<string, IJsonSchema>;
/**
* An object to hold reusable security schemes.
*
* In other words, a collection of named security schemes.
*/
securitySchemes?: Record<string, ISecurityScheme>;
}
/**
* Type schema information.
*
* `OpenApi.IJsonSchema` is a type schema info for OpenAPI.
*
* `OpenApi.IJsonSchema` basically follows the JSON schema definition of
* OpenAPI v3.1, but is refined to remove ambiguous and duplicated
* expressions of OpenAPI v3.1 for convenience and clarity.
*
* - Decompose mixed type: {@link OpenApiV3_1.IJsonSchema.IMixed}
* - Resolve nullable property:
* {@link OpenApiV3_1.IJsonSchema.__ISignificant.nullable}
* - Array type utilizes only single {@link OpenAPI.IJsonSchema.IArray.items}
* - Tuple type utilizes only {@link OpenApi.IJsonSchema.ITuple.prefixItems}
* - Merge {@link OpenApiV3_1.IJsonSchema.IAllOf} to
* {@link OpenApi.IJsonSchema.IObject}
* - Merge {@link OpenApiV3_1.IJsonSchema.IAnyOf} to
* {@link OpenApi.IJsonSchema.IOneOf}
* - Merge {@link OpenApiV3_1.IJsonSchema.IRecursiveReference} to
* {@link OpenApi.IJsonSchema.IReference}
*/
export type IJsonSchema =
| IJsonSchema.IConstant
| IJsonSchema.IBoolean
| IJsonSchema.IInteger
| IJsonSchema.INumber
| IJsonSchema.IString
| IJsonSchema.IArray
| IJsonSchema.ITuple
| IJsonSchema.IObject
| IJsonSchema.IReference
| IJsonSchema.IOneOf
| IJsonSchema.INull
| IJsonSchema.IUnknown;
export namespace IJsonSchema {
/** Constant value type. */
export interface IConstant extends IJsonSchemaAttribute {
/** The constant value. */
const: boolean | number | string;
}
/** Boolean type info. */
export interface IBoolean extends IJsonSchemaAttribute.IBoolean {
/** The default value of the boolean type. */
default?: boolean;
}
/** Integer type info. */
export interface IInteger extends IJsonSchemaAttribute.IInteger {
/**
* Default value of the integer type.
*
* @type int64
*/
default?: number;
/**
* 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 IJsonSchemaAttribute.INumber {
/** Default value of the number type. */
default?: 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 IJsonSchemaAttribute.IString {
/** Default value of the string type. */
default?: 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 IJsonSchemaAttribute.IArray {
/**
* 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;
}
/** Tuple type info. */
export interface ITuple extends IJsonSchemaAttribute {
/**
* Discriminator value of the type.
*
* Note that, the tuple type cannot be distinguished with {@link IArray}
* type just by this `discriminator` property.
*
* To check whether the type is tuple or array, you have to check the
* existence of {@link IArray.items} or {@link ITuple.prefixItems}
* properties.
*/
type: "array";
/**
* Prefix items.
*
* The `prefixItems` means the type schema info of the prefix items in the
* tuple type. In the TypeScript, it is expressed as `[T1, T2]`.
*
* If you want to express `[T1, T2, ...TO[]]` type, you can configure the
* `...TO[]` through the {@link additionalItems} property.
*/
prefixItems: IJsonSchema[];
/**
* Additional items.
*
* The `additionalItems` means the type schema info of the additional
* items after the {@link prefixItems}. In the TypeScript, if there's a
* type `[T1, T2, ...TO[]]`, the `...TO[]` is represented by the
* `additionalItems`.
*
* By the way, if you configure the `additionalItems` as `true`, it means
* the additional items are not restricted. They can be any type, so that
* it is equivalent to the TypeScript type `[T1, T2, ...any[]]`.
*
* Otherwise configure the `additionalItems` as the {@link IJsonSchema}, it
* means the additional items must follow the type schema info. Therefore,
* it is equivalent to the TypeScript type `[T1, T2, ...TO[]]`.
*/
additionalItems?: boolean | IJsonSchema;
/**
* Unique items restriction.
*
* If this property value is `true`, target tuple must have unique items.
*/
uniqueItems?: boolean;
/**
* Minimum items restriction.
*
* Restriction of minimum number of items in the tuple.
*
* @type uint64
*/
minItems?: number;
/**
* Maximum items restriction.
*
* Restriction of maximum number of items in the tuple.
*
* @type uint64
*/
maxItems?: number;
}
/** Object type info. */
export interface IObject extends IJsonSchemaAttribute.IObject {
/**
* 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.
*
* If you need additional properties that is represented by dynamic key,
* you can use the {@link additionalProperties} instead.
*/
properties?: Record<string, IJsonSchema>;
/**
* 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 `true`, it means that the additional properties are not
* restricted. They can be any type. Otherwise, if the value is
* {@link IJsonSchema} type, it means that the additional properties must
* follow the type schema info.
*
* - `true`: `Record<string, any>`
* - `IJsonSchema`: `Record<string, T>`
*/
additionalProperties?: boolean | 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<Key = string> extends IJsonSchemaAttribute {
/**
* 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 OpenApi.IComponents.schemas} object.
*
* - `#/components/schemas/SomeObject`
* - `#/components/schemas/AnotherObject`
*/
$ref: Key;
}
/**
* 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 OpenApi} forcibly converts it to
* `oneOf` type.
*/
export interface IOneOf extends IJsonSchemaAttribute {
/** 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 IJsonSchemaAttribute.INull {
/** Default value of the `null` type. */
default?: null;
}
/** Unknown, the `any` type. */
export interface IUnknown extends IJsonSchemaAttribute.IUnknown {
/** Default value of the `any` type. */
default?: any;
}
/**
* Significant attributes that can be applied to the most types.
*
* @ignore
* @deprecated
*/
export interface __ISignificant<Type extends string>
extends IJsonSchemaAttribute {
/** Discriminator value of the type. */
type: Type;
}
/**
* Common attributes that can be applied to all types.
*
* @ignore
* @deprecated
*/
export type __IAttribute = IJsonSchemaAttribute;
}
/**
* Security scheme of Swagger Documents.
*
* `OpenApi.ISecurityScheme` is a data structure representing content of
* `securitySchemes` in `swagger.json` file. It is composed with 5 types of
* security schemes as an union type like below.
*
* @reference https://swagger.io/specification/#security-scheme-object
*/
export type ISecurityScheme =
| ISecurityScheme.IApiKey
| ISecurityScheme.IHttpBasic
| ISecurityScheme.IHttpBearer
| ISecurityScheme.IOAuth2
| ISecurityScheme.IOpenId;
export namespace ISecurityScheme {
/** Normal API key type. */
export interface IApiKey {
type: "apiKey";
in?: "header" | "query" | "cookie";
name?: string;
description?: string;
}
/** HTTP basic authentication type. */
export interface IHttpBasic {
type: "http";
scheme: "basic";
description?: string;
}
/** HTTP bearer authentication type. */
export interface IHttpBearer {
type: "http";
scheme: "bearer";
bearerFormat?: string;
description?: string;
}
/** OAuth2 authentication type. */
export interface IOAuth2 {
type: "oauth2";
flows: IOAuth2.IFlowSet;
description?: string;
}
export interface IOpenId {
type: "openIdConnect";
openIdConnectUrl: string;
description?: string;
}
export namespace IOAuth2 {
export interface IFlowSet {
authorizationCode?: IFlow;
implicit?: Omit<IFlow, "tokenUrl">;
password?: Omit<IFlow, "authorizationUrl">;
clientCredentials?: Omit<IFlow, "authorizationUrl">;
}
export interface IFlow {
authorizationUrl?: string;
tokenUrl?: string;
refreshUrl?: string;
scopes?: Record<string, string>;
}
}
}
}
AutoBeInterfaceHistory
is a history generated when the RESTful API design is completed based on the previous requirements analysis report and database design.
@autobe
constructs data of type AutoBeOpenApi.IDocument
through AI function calling, validates it, and stores it in the document
property. This is then converted to a formal OpenAPI document (OpenApi.IDocument), and NestJS API controllers, DTOs, and e2e test code are generated (code generation), with the results stored in the files
property.
The step
property indicates which requirements analysis report iteration the API design was performed for. If the AutoBeInterfaceHistory.step
value is lower than AutoBeAnalyzeHistory.step
, it means the API design has not yet been updated to reflect the latest requirements.
AutoBeTestHistory
undefined
import { tags } from "typia";
import { IAutoBeTypeScriptCompileResult } from "../compiler/IAutoBeTypeScriptCompileResult";
import { AutoBeAgentHistoryBase } from "./AutoBeHistoryBase";
import { AutoBeTestFile } from "./contents/AutoBeTestFile";
/**
* History record generated when the Test agent writes e2e test code based on
* the previous requirements analysis, database design, and RESTful API
* specification.
*
* The Test agent conceives multiple use case scenarios for each API endpoint
* and implements them as test programs. These test programs are composed of one
* TypeScript file and a standalone function for each scenario, providing
* comprehensive coverage of the API functionality and business logic
* validation.
*
* When the AI occasionally writes incorrect TypeScript code, the system
* provides compilation error messages as feedback, allowing the AI to
* self-correct. This feedback process usually works correctly, so test code
* written by AI almost always compiles successfully, ensuring robust and
* reliable test suites.
*
* @author Samchon
*/
export interface AutoBeTestHistory extends AutoBeAgentHistoryBase<"test"> {
/**
* Collection of generated e2e test files with detailed scenario metadata.
*
* Contains an array of test file objects where each file represents a
* specific testing scenario with its location, content, and associated
* scenario information. Each test file includes standalone functions that
* implement particular use case scenarios for API endpoints, providing
* comprehensive end-to-end testing coverage with rich contextual
* information.
*
* Unlike simple key-value pairs, this structure allows for detailed tracking
* of test scenarios, their purposes, and their relationships to specific API
* endpoints and business requirements. The test files are designed to
* validate both technical functionality and business rule implementation,
* ensuring that the generated APIs work correctly under realistic operational
* conditions.
*/
files: AutoBeTestFile[];
/**
* Results of compiling the generated test code using the embedded TypeScript
* compiler.
*
* Contains the compilation outcome of the test files built through the
* TypeScript compiler. The feedback process usually works correctly, so this
* should typically indicate successful compilation. However, when using very
* small AI models, the {@link IAutoBeTypeScriptCompileResult} might have
* `success := false`.
*
* Compilation errors trigger a self-correction feedback loop where the AI
* receives detailed error messages and attempts to fix the issues
* automatically.
*/
compiled: IAutoBeTypeScriptCompileResult;
/**
* Reason why the Test agent was activated through function calling.
*
* Explains the specific circumstances that triggered the AI chatbot to invoke
* the Test agent via function calling. This could include reasons such as
* initial test suite generation after API specification completion, updating
* test scenarios due to API changes, or regenerating tests to reflect
* modified business requirements or database schemas.
*/
reason: string;
/**
* Iteration number of the requirements analysis report this test code was
* written for.
*
* Indicates which version of the requirements analysis this test suite
* reflects. If this value is lower than {@link AutoBeAnalyzeHistory.step}, it
* means the test code has not yet been updated to reflect the latest
* requirements and may need regeneration.
*
* A value of 0 indicates the initial test suite, while higher values
* represent subsequent revisions based on updated requirements, API changes,
* or database schema modifications.
*/
step: number;
/**
* ISO 8601 timestamp indicating when the test code generation was completed.
*
* Marks the exact moment when the Test agent finished writing all test
* scenarios, completed the compilation validation process, and resolved any
* compilation errors through the feedback loop. This timestamp is crucial for
* tracking the development timeline and determining the currency of the test
* suite relative to other development artifacts.
*/
completed_at: string & tags.Format<"date-time">;
}
undefined
/**
* Result of TypeScript compilation and validation operations.
*
* This union type represents all possible outcomes when the TypeScript compiler
* processes generated code from the Test and Realize agents. The compilation
* results enable AI self-correction through detailed feedback mechanisms while
* ensuring that all generated code meets production standards and integrates
* seamlessly with the TypeScript ecosystem.
*
* The compilation process validates framework integration, type system
* integrity, dependency resolution, and build compatibility. Success results
* indicate production-ready code, while failure results provide detailed
* diagnostics for iterative refinement through the AI feedback loop.
*
* @author Samchon
*/
export type IAutoBeTypeScriptCompileResult =
| IAutoBeTypeScriptCompileResult.ISuccess
| IAutoBeTypeScriptCompileResult.IFailure
| IAutoBeTypeScriptCompileResult.IException;
export namespace IAutoBeTypeScriptCompileResult {
/**
* Successful compilation result with generated JavaScript output.
*
* Represents the ideal outcome where TypeScript compilation completed without
* errors and produced clean JavaScript code ready for execution. This result
* indicates that the generated TypeScript code meets all production
* standards, integrates correctly with frameworks and dependencies, and
* maintains complete type safety throughout the application stack.
*/
export interface ISuccess {
/** Discriminator indicating successful compilation. */
type: "success";
// /**
// * Generated JavaScript files as key-value pairs.
// *
// * Contains the compiled JavaScript output with each key representing the
// * output file path and each value containing the generated JavaScript code.
// * The compiled code is ready for execution in Node.js environments and
// * maintains all functionality specified in the original TypeScript source
// * while ensuring optimal runtime performance.
// */
// javascript: Record<string, string>;
}
/**
* Compilation failure with detailed diagnostic information and partial
* output.
*
* Represents cases where TypeScript compilation encountered errors or
* warnings that prevent successful code generation. This result provides
* comprehensive diagnostic information to enable AI agents to understand
* specific issues and implement targeted corrections through the iterative
* refinement process.
*/
export interface IFailure {
/** Discriminator indicating compilation failure. */
type: "failure";
/**
* Detailed compilation diagnostics for error analysis and correction.
*
* Contains comprehensive information about compilation errors, warnings,
* and suggestions that occurred during the TypeScript compilation process.
* Each diagnostic includes file location, error category, diagnostic codes,
* and detailed messages that enable AI agents to understand and resolve
* specific compilation issues.
*/
diagnostics: IDiagnostic[];
// /**
// * Partial JavaScript output despite compilation failures.
// *
// * Contains any JavaScript code that was successfully generated before
// * compilation failures occurred. This partial output can provide context
// * for understanding which parts of the code compiled correctly and which
// * areas require correction during the AI feedback and refinement process.
// */
// javascript: Record<string, string>;
}
/**
* Unexpected exception during the compilation process.
*
* Represents cases where the TypeScript compilation process encountered an
* unexpected runtime error or system exception that prevented normal
* compilation operation. These cases indicate potential issues with the
* compilation environment or unexpected edge cases that should be
* investigated.
*/
export interface IException {
/** Discriminator indicating compilation exception. */
type: "exception";
/**
* The raw error or exception that occurred during compilation.
*
* Contains the original error object or exception details for debugging
* purposes. This information helps developers identify the root cause of
* unexpected compilation failures and improve system reliability while
* maintaining the robustness of the automated development pipeline.
*/
error: unknown;
}
/**
* Detailed diagnostic information for compilation issues.
*
* Provides comprehensive details about specific compilation problems
* including file locations, error categories, diagnostic codes, and
* descriptive messages. This information is essential for AI agents to
* understand compilation failures and implement precise corrections during
* the iterative development process.
*
* @author Samchon
*/
export interface IDiagnostic {
/**
* Source file where the diagnostic was generated.
*
* Specifies the TypeScript source file that contains the issue, or null if
* the diagnostic applies to the overall compilation process rather than a
* specific file. This information helps AI agents target corrections to the
* appropriate source files during the refinement process.
*/
file: string | null;
/**
* Category of the diagnostic message.
*
* Indicates the severity and type of the compilation issue, enabling AI
* agents to prioritize fixes and understand the impact of each diagnostic.
* Errors must be resolved for successful compilation, while warnings and
* suggestions can guide code quality improvements.
*/
category: DiagnosticCategory;
/**
* TypeScript diagnostic code for the specific issue.
*
* Provides the official TypeScript diagnostic code that identifies the
* specific type of compilation issue. This code can be used to look up
* detailed explanations and resolution strategies in TypeScript
* documentation or automated correction systems.
*/
code: number | string;
/**
* Character position where the diagnostic begins in the source file.
*
* Specifies the exact location in the source file where the issue starts,
* or undefined if the diagnostic doesn't apply to a specific location. This
* precision enables AI agents to make targeted corrections without
* affecting unrelated code sections.
*/
start: number | undefined;
/**
* Length of the text span covered by this diagnostic.
*
* Indicates how many characters from the start position are affected by
* this diagnostic, or undefined if the diagnostic doesn't apply to a
* specific text span. This information helps AI agents understand the scope
* of corrections needed for each issue.
*/
length: number | undefined;
/**
* Human-readable description of the compilation issue.
*
* Provides a detailed explanation of the compilation problem in natural
* language that AI agents can analyze to understand the issue and formulate
* appropriate corrections. The message text includes context and
* suggestions for resolving the identified problem.
*/
messageText: string;
}
/**
* Categories of TypeScript diagnostic messages.
*
* Defines the severity levels and types of compilation diagnostics that can
* be generated during TypeScript compilation. These categories help AI agents
* prioritize fixes and understand the impact of each compilation issue on the
* overall code quality and functionality.
*
* @author Samchon
*/
export type DiagnosticCategory =
| "warning" // Issues that don't prevent compilation but indicate potential problems
| "error" // Critical issues that prevent successful compilation and must be fixed
| "suggestion" // Recommendations for code improvements that enhance quality
| "message"; // Informational messages about the compilation process
}
AutoBeTestHistory
is a history generated when e2e test code is written based on the previous requirements analysis, database design, and RESTful API specification.
@autobe
conceives multiple use case scenarios for each API endpoint and implements them as test programs. These test programs are composed of one TypeScript file and a standalone function for each scenario, stored in the files
property. These are then built using the TypeScript compiler embedded in @autobe
, with the results stored in the compiled
property.
When the AI occasionally writes incorrect TypeScript code, @autobe
provides compilation error messages as feedback, allowing the AI to self-correct. This feedback process usually works correctly, so test code written by AI almost always compiles successfully. However, when using very small AI models, the IAutoBeTypeScriptCompileResult
result might have success := false
.
The step
property indicates which requirements analysis report iteration the test code was written for. If the AutoBeTestHistory.step
value is lower than AutoBeAnalyzeHistory.step
, it means the test code has not yet been updated to reflect the latest requirements.
AutoBeRealizeHistory
Not implemented yet.