npm package: @mifty/cli
Description: Enterprise-level Node.js TypeScript Framework with Database Designer UI and Module Generator
Author: Abhir
Latest version: 1.0.14

# 🚀 Mifty Framework

<div align="center">

**Enterprise-Grade Node.js TypeScript Framework with Visual Database Designer & Auto Code Generation**

[![npm version](https://img.shields.io/npm/v/@mifty/cli.svg)](https://www.npmjs.com/package/@mifty/cli)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/Node.js-16+-green.svg)](https://nodejs.org)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org)
[![Downloads](https://img.shields.io/npm/dm/@mifty/cli.svg)](https://www.npmjs.com/package/@mifty/cli)

**[Quick Start](#-quick-start)** • **[Features](#-why-mifty)** • **[Documentation](#-usage)** • **[Commands](./COMMANDS.md)** • **[Examples](#-examples)** • **[Adapters](./ADAPTERS.md)**

</div>

## 🎯 What is Mifty?

Mifty is a **modern Node.js TypeScript framework** that revolutionizes backend development by combining:

- 🎨 **Visual Database Designer** - Design your database schema with drag-and-drop UI
- 🤖 **Auto Code Generation** - Generate complete CRUD modules, tests, and API routes
- 🏗️ **Clean Architecture** - Built-in dependency injection and layered architecture
- ⚡ **Developer Experience** - Hot reload, error monitoring, and auto-fix capabilities
- 🔌 **Rich Ecosystem** - 20+ pre-built adapters for AWS, Stripe, Auth, and more

**Perfect for:** REST APIs, Microservices, Enterprise Applications, Rapid Prototyping

### 🎬 See Mifty in Action

```bash
# From zero to running API in 2 minutes
mifty init my-blog-api && cd my-blog-api && npm install && npm run dev:full
```

**What you get instantly:**
- ✅ TypeScript API server running on port 3000
- 🎨 Visual database designer at http://localhost:3001/ui
- 📊 Database viewer at http://localhost:5555
- 🔍 Real-time error monitoring with auto-fix
- 🧪 Complete testing setup with Jest

---

## ⚡ Quick Start

Get your enterprise API running in **under 2 minutes**:

```bash
# 1. Install globally
npm install -g @mifty/cli

# 2. Create project
mifty init my-api
cd my-api

# 3. Install dependencies
npm install

# 4. Start development
npm run dev
```

**🎉 Your API is now running!**

| Service | URL | Description |
|---------|-----|-------------|
| 🌐 **API Server** | http://localhost:3000 | Main REST API |
| 🎨 **DB Designer** | http://localhost:3001/ui | Visual Database Designer |
| 📊 **Prisma Studio** | http://localhost:5555 | Database Viewer |
| 🔍 **Monitor** | Terminal | Error Monitor with Auto-fix |

### 🎬 Next Steps

1. **🎨 Design Database**: Open http://localhost:3001/ui to visually design your schema
2. **🤖 Generate Code**: Run `npm run generate` to create modules from your design  
3. **🧪 Test API**: Your endpoints are automatically available at `/api/v1/`
4. **🔌 Add Features**: Install adapters with `npm run adapter list`

### 🚀 What Makes Mifty Special?

<div align="center">

| Traditional Way | Mifty Way | Time Saved |
|----------------|-----------|------------|
| 📝 Write Prisma schema manually | 🎨 Visual drag-and-drop designer | **1 hour** |
| 🔧 Build CRUD operations by hand | 🤖 Auto-generate everything | **4 hours** |
| 🧪 Write tests manually | ✅ Tests generated automatically | **3 hours** |
| 🐛 Debug errors manually | 🔍 AI-powered auto-fix monitor | **2 hours** |
| **Total per module: ~10 hours** | **Total per module: ~30 minutes** | **Save 15+ hours** |

</div>

---

## 🏗️ Lightweight Architecture

Mifty uses a **smart architecture** that keeps your projects lightweight:

- **🎯 Framework Tools Stay in `node_modules`**: All development tools (DB Designer, Monitor, CLI scripts, Adapter templates) remain in the npm package
- **📦 Only Your Code in Your Project**: Generated modules, database design, and installed adapters are the only things in your project
- **🔌 Adapters from npm**: When you install adapters, they're generated into your project but the templates stay in `node_modules/mifty`
- **⚡ Fast & Clean**: No bloated framework files copied into your project

**How it works:**
```bash
# When you run commands, they execute from node_modules
npm run db-designer    # Runs from node_modules/mifty/bin/db-designer.js
npm run generate       # Runs from node_modules/mifty/bin/generate.js
npm run adapter install storage-service  # Templates from node_modules/mifty/src/scripts/adapters/templates/

# Your project stays clean with only:
src/
├── modules/           # Your generated modules
├── adapters/          # Your installed adapters
└── db.design.ts       # Your database design
```

---

## 🌟 Why Choose Mifty?

<div align="center">

### ⚡ **10x Faster Development** • 🎨 **Visual Design** • 🤖 **Auto Generation** • 🛡️ **Type Safe**

</div>

### 🚀 Key Benefits

- **⏱️ Save 15+ Hours per Module** - Auto-generate complete CRUD operations, tests, and documentation
- **🎨 No-Code Database Design** - Visual drag-and-drop interface for schema creation
- **🛡️ Production-Ready Code** - Built-in security, validation, error handling, and testing
- **🔌 Rich Ecosystem** - 20+ adapters for AWS, Stripe, Auth, Email, Storage, and more
- **📈 Scalable Architecture** - Clean architecture patterns with dependency injection
- **🔄 Developer Experience** - Hot reload, auto-fix, real-time monitoring

### Traditional Development vs Mifty

<table>
<tr>
<th>Task</th>
<th>Traditional Approach</th>
<th>Mifty</th>
<th>Time Saved</th>
</tr>
<tr>
<td><strong>Project Setup</strong></td>
<td>Hours of configuration<br/>Install dependencies<br/>Setup folder structure<br/>Configure TypeScript</td>
<td><code>mifty init</code><br/>✅ Done in 30 seconds</td>
<td><strong>~2 hours</strong></td>
</tr>
<tr>
<td><strong>Database Design</strong></td>
<td>Write Prisma schema manually<br/>Learn schema syntax<br/>Handle relations</td>
<td>🎨 Visual UI Designer<br/>Drag & drop tables<br/>Click to add relations</td>
<td><strong>~1 hour</strong></td>
</tr>
<tr>
<td><strong>CRUD Operations</strong></td>
<td>Write 100s of lines<br/>Repository layer<br/>Service layer<br/>Controller layer</td>
<td>🤖 Auto-generated<br/>✅ All layers included<br/>✅ With validations</td>
<td><strong>~4 hours</strong></td>
</tr>
<tr>
<td><strong>API Routes</strong></td>
<td>Manual routing setup<br/>Define each endpoint<br/>Add middleware</td>
<td>✅ Auto-generated RESTful routes<br/>✅ Middleware included</td>
<td><strong>~1 hour</strong></td>
</tr>
<tr>
<td><strong>Validation</strong></td>
<td>Write Zod/Joi schemas<br/>Validate each field<br/>Handle errors</td>
<td>✅ Auto-generated from DB design<br/>✅ Type-safe validations</td>
<td><strong>~2 hours</strong></td>
</tr>
<tr>
<td><strong>Testing</strong></td>
<td>Write unit tests<br/>Write integration tests<br/>Setup mocks</td>
<td>✅ Auto-generated tests<br/>✅ Unit & Integration<br/>✅ Mocks included</td>
<td><strong>~3 hours</strong></td>
</tr>
<tr>
<td><strong>Error Handling</strong></td>
<td>Debug manually<br/>Fix import errors<br/>Chase down bugs</td>
<td>🔍 AI-powered auto-fix monitor<br/>✅ Real-time detection<br/>✅ Auto-fix imports</td>
<td><strong>~2 hours</strong></td>
</tr>
<tr>
<td colspan="3" align="right"><strong>Total Time Saved per Module:</strong></td>
<td><strong>~15 hours</strong></td>
</tr>
</table>

### 🎯 Core Features

<table>
<tr>
<td width="50%">

#### 🎨 Visual Database Designer
- Drag-and-drop table creation
- Visual relationship mapping
- Real-time schema preview
- History & version tracking
- Export to Prisma schema

#### 🤖 Auto Code Generation
- Complete CRUD modules
- Repository pattern
- Service layer with business logic
- Controllers with validation
- RESTful routes
- Unit & integration tests

#### 🔄 Development Tools
- Hot reload with ts-node-dev
- Error monitor with auto-fix
- Import issue detection
- Real-time compilation
- Integrated Prisma Studio

</td>
<td width="50%">

#### 🛡️ Type Safety & Quality
- Full TypeScript support
- Prisma ORM integration
- Zod validation schemas
- ESLint & Prettier configured
- Jest testing framework

#### 🏗️ Clean Architecture
- Dependency injection (tsyringe)
- Repository pattern
- Service layer separation
- Controller abstraction
- Modular structure

#### 📦 Lightweight & Flexible
- Tools in node_modules
- Not copied to projects
- Microservices ready
- Configurable services
- Docker support

</td>
</tr>
</table>

---

## 📦 Installation

### Prerequisites

<table>
<tr>
<td width="50%">

**✅ Required:**
- **Node.js** 16.x or higher ([Download](https://nodejs.org/))
- **npm** 7.x or higher (comes with Node.js)

</td>
<td width="50%">

**🔧 Optional:**
- **Database**: PostgreSQL, MySQL, SQLite
- **Git** (for version control)
- **Docker** (for containerization)

</td>
</tr>
</table>

> **💡 Beginner-Friendly**: Mifty works with SQLite by default - no database setup required to get started!

### Installation

#### 🚀 One-Line Install (Recommended)
```bash
npm install -g @mifty/cli
```

#### ✅ Verify Installation
```bash
mifty --version
mifty --help
```

**Expected output:**
```
$ mifty --version
@mifty/cli v1.0.0

$ mifty --help
Usage: mifty [command] [options]

Commands:
  init <project-name>  Create a new Mifty project
  --version           Show version number
  --help              Show help
```

> **💡 Alternative**: For local development, you can also use `npm install -g mifty`

### Troubleshooting

<details>
<summary><strong>🔧 Common Issues & Solutions</strong></summary>

#### Installation Problems
```bash
# Clear npm cache and reinstall
npm cache clean --force
npm uninstall -g @mifty/cli
npm install -g @mifty/cli
```

#### Port Already in Use
```bash
# Check what's using the port
lsof -i :3000  # or :3001 for DB Designer

# Kill the process or change port in .env
PORT=3001 npm run dev
```

#### Database Connection Issues
```bash
# Check your DATABASE_URL in .env
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"

# For SQLite (default, no setup needed)
DATABASE_URL="file:./dev.db"
```

#### Permission Errors (macOS/Linux)
```bash
# Fix npm permissions
sudo chown -R $(whoami) ~/.npm
```

</details>

> **💡 Need help?** Mifty has built-in error monitoring with auto-fix. Most issues are detected and resolved automatically. For other problems, check our [Issue Tracker](https://github.com/abhir22/miftyjs/issues).

### Available Commands After Installation

Once installed globally, you have access to these commands:

```bash
mifty init <project-name>     # Create new project
mifty-generate               # Generate modules (run from project)
mifty-db-designer           # Start database designer (run from project)
mifty-monitor               # Start error monitor (run from project)
mifty-adapter               # Manage adapters (run from project)
```

### What Gets Installed Where

**Global Installation (`@mifty/cli`):**
- CLI commands: `mifty`, `mifty-generate`, `mifty-db-designer`, etc.
- Framework tools and templates in global `node_modules`

**Project Creation (`mifty init`):**
- Copies only essential project files (src/, config/, etc.)
- Adds `@mifty/cli` as devDependency
- All tools accessed via npm scripts that call global commands

**Result:** Lightweight projects with full framework power! 🚀

---

## 🗄️ Database Configuration

Mifty supports all major databases through Prisma ORM. **You can easily switch between databases by simply changing the provider in your Prisma schema** - no code changes required!

### 🎯 Quick Database Switch

**Step 1:** Update the `provider` in `src/prisma/schema.prisma`
**Step 2:** Update `DATABASE_URL` in `.env`
**Step 3:** Run `npm run prisma:migrate`

That's it! Your entire application automatically works with the new database.

### 📋 Supported Databases

<table>
<tr>
<th>Database</th>
<th>Provider</th>
<th>Best For</th>
<th>Setup Difficulty</th>
</tr>
<tr>
<td><strong>SQLite</strong></td>
<td><code>sqlite</code></td>
<td>Development, Prototyping</td>
<td>🟢 None (Default)</td>
</tr>
<tr>
<td><strong>PostgreSQL</strong></td>
<td><code>postgresql</code></td>
<td>Production, Complex queries</td>
<td>🟡 Easy</td>
</tr>
<tr>
<td><strong>MySQL</strong></td>
<td><code>mysql</code></td>
<td>Web applications, WordPress</td>
<td>🟡 Easy</td>
</tr>
<tr>
<td><strong>SQL Server</strong></td>
<td><code>sqlserver</code></td>
<td>Enterprise, Microsoft stack</td>
<td>🟠 Medium</td>
</tr>
<tr>
<td><strong>MongoDB</strong></td>
<td><code>mongodb</code></td>
<td>Document storage, NoSQL</td>
<td>🟡 Easy</td>
</tr>
</table>

### 🔧 Database Configuration Examples

#### 1️⃣ SQLite (Default - No Setup Required)

**Prisma Schema (`src/prisma/schema.prisma`):**
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String
  createdAt DateTime @default(now())
}
```

**Environment (`.env`):**
```env
DATABASE_URL="file:./dev.db"
```

**Perfect for:** Development, testing, small applications

---

#### 2️⃣ PostgreSQL (Recommended for Production)

**Prisma Schema (`src/prisma/schema.prisma`):**
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String
  createdAt DateTime @default(now())
}
```

**Environment (`.env`):**
```env
# Local PostgreSQL
DATABASE_URL="postgresql://username:password@localhost:5432/myapp_db"

# Cloud PostgreSQL (e.g., Heroku, Railway, Supabase)
DATABASE_URL="postgresql://user:pass@host:5432/dbname?sslmode=require"

# With connection pooling
DATABASE_URL="postgresql://user:pass@host:5432/dbname?connection_limit=5&pool_timeout=10"
```

**Setup PostgreSQL locally:**
```bash
# Using Docker
docker run --name postgres -e POSTGRES_PASSWORD=mypassword -p 5432:5432 -d postgres

# Using Homebrew (macOS)
brew install postgresql
brew services start postgresql
createdb myapp_db

# Using apt (Ubuntu/Debian)
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo -u postgres createdb myapp_db
```

---

#### 3️⃣ MySQL/MariaDB

**Prisma Schema (`src/prisma/schema.prisma`):**
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String
  createdAt DateTime @default(now())
}
```

**Environment (`.env`):**
```env
# Local MySQL
DATABASE_URL="mysql://username:password@localhost:3306/myapp_db"

# Cloud MySQL (e.g., PlanetScale, AWS RDS)
DATABASE_URL="mysql://user:pass@host:3306/dbname?sslaccept=strict"

# With SSL and connection options
DATABASE_URL="mysql://user:pass@host:3306/dbname?sslmode=REQUIRED&connection_limit=5"
```

**Setup MySQL locally:**
```bash
# Using Docker
docker run --name mysql -e MYSQL_ROOT_PASSWORD=mypassword -e MYSQL_DATABASE=myapp_db -p 3306:3306 -d mysql:8

# Using Homebrew (macOS)
brew install mysql
brew services start mysql
mysql -u root -p -e "CREATE DATABASE myapp_db;"

# Using apt (Ubuntu/Debian)
sudo apt update
sudo apt install mysql-server
sudo mysql -e "CREATE DATABASE myapp_db;"
```

---

#### 4️⃣ SQL Server

**Prisma Schema (`src/prisma/schema.prisma`):**
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String
  createdAt DateTime @default(now())
}
```

**Environment (`.env`):**
```env
# Local SQL Server
DATABASE_URL="sqlserver://localhost:1433;database=myapp_db;user=sa;password=YourPassword123;trustServerCertificate=true"

# Azure SQL Database
DATABASE_URL="sqlserver://server.database.windows.net:1433;database=myapp_db;user=username;password=password;encrypt=true"
```

---

#### 5️⃣ MongoDB

**Prisma Schema (`src/prisma/schema.prisma`):**
```prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

model User {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  email     String   @unique
  name      String
  createdAt DateTime @default(now())
}
```

**Environment (`.env`):**
```env
# Local MongoDB
DATABASE_URL="mongodb://localhost:27017/myapp_db"

# MongoDB Atlas (Cloud)
DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/myapp_db?retryWrites=true&w=majority"

# With authentication
DATABASE_URL="mongodb://username:password@localhost:27017/myapp_db?authSource=admin"
```

**Setup MongoDB locally:**
```bash
# Using Docker
docker run --name mongodb -p 27017:27017 -d mongo

# Using Homebrew (macOS)
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

# Using apt (Ubuntu/Debian)
sudo apt update
sudo apt install mongodb
sudo systemctl start mongodb
```

### 🚀 Switching Databases

**Example: SQLite → PostgreSQL**

1. **Update Prisma Schema:**
   ```prisma
   datasource db {
     provider = "postgresql"  // Changed from "sqlite"
     url      = env("DATABASE_URL")
   }
   ```

2. **Update Environment:**
   ```env
   # Old
   DATABASE_URL="file:./dev.db"
   
   # New
   DATABASE_URL="postgresql://user:pass@localhost:5432/myapp"
   ```

3. **Apply Changes:**
   ```bash
   npm run prisma:generate
   npm run prisma:migrate
   ```

**That's it!** Your entire application now works with PostgreSQL. All your generated modules, API endpoints, and business logic remain exactly the same.

### 🔧 Database Migration Commands

```bash
# Generate Prisma client after schema changes
npm run prisma:generate

# Create and apply new migration
npm run prisma:migrate

# View migration status
npm run prisma:migrate:status

# Deploy migrations (production)
npm run prisma:migrate:deploy

# Push schema changes without migration (development)
npm run prisma:push

# Reset database (⚠️ deletes all data)
npm run prisma:reset

# Open database browser
npm run prisma:studio
```

### 🌐 Cloud Database Providers

<table>
<tr>
<th>Provider</th>
<th>Database</th>
<th>Free Tier</th>
<th>Best For</th>
</tr>
<tr>
<td><strong>Supabase</strong></td>
<td>PostgreSQL</td>
<td>✅ 500MB</td>
<td>Full-stack apps with auth</td>
</tr>
<tr>
<td><strong>PlanetScale</strong></td>
<td>MySQL</td>
<td>✅ 5GB</td>
<td>Serverless MySQL</td>
</tr>
<tr>
<td><strong>Railway</strong></td>
<td>PostgreSQL</td>
<td>✅ 1GB</td>
<td>Simple deployment</td>
</tr>
<tr>
<td><strong>MongoDB Atlas</strong></td>
<td>MongoDB</td>
<td>✅ 512MB</td>
<td>Document databases</td>
</tr>
<tr>
<td><strong>Heroku Postgres</strong></td>
<td>PostgreSQL</td>
<td>✅ 1GB</td>
<td>Easy Heroku integration</td>
</tr>
</table>

### 💡 Pro Tips

- **🚀 Start with SQLite** for development - zero setup required
- **📈 Use PostgreSQL** for production - best performance and features  
- **🔄 Switch anytime** - Mifty makes database changes seamless
- **🧪 Test migrations** on a copy of your data before production
- **📊 Use Prisma Studio** (`npm run prisma:studio`) to browse your data
- **🔒 Always backup** before running `prisma:reset`

---

## 🎯 Step-by-Step Tutorial

### 1️⃣ Create Your First Project

```bash
# Create a new project
mifty init my-awesome-api
cd my-awesome-api

# Install dependencies
npm install

# Generate Prisma client
npm run prisma:generate
```

**What just happened?**
- ✅ Created a complete TypeScript project structure
- ✅ Installed all necessary dependencies
- ✅ Set up Prisma ORM with SQLite database
- ✅ Configured testing, linting, and development tools
- ✅ Added npm scripts for all common tasks

<details>
<summary><strong>📋 Advanced CLI Options</strong></summary>

```bash
mifty init <project-name> [options]

Options:
  -s, --skip-install    Skip npm install (install manually later)
  --with-git            Initialize git repository automatically
  -h, --help            Display help information

Examples:
  mifty init blog-api --with-git        # Create project with git
  mifty init shop-api --skip-install    # Create without installing deps
```
</details>

---

### 2️⃣ Choose Your Development Mode

<table>
<tr>
<th>Command</th>
<th>What Starts</th>
<th>Best For</th>
</tr>
<tr>
<td>

```bash
npm run dev
```

</td>
<td>
🌐 API Server (3000)<br/>
🔍 Error Monitor
</td>
<td>
**Daily coding**<br/>
Building API endpoints
</td>
</tr>
<tr>
<td>

```bash
npm run dev:full
```

</td>
<td>
🌐 API Server (3000)<br/>
🎨 **DB Designer (3001)**<br/>
📊 Prisma Studio (5555)<br/>
🔍 Error Monitor
</td>
<td>
**Database design**<br/>
Full development suite
</td>
</tr>
<tr>
<td>

```bash
npm run db-designer
```

</td>
<td>
🎨 DB Designer only (3001)
</td>
<td>
**Schema design only**<br/>
Planning database structure
</td>
</tr>
</table>

> **🎯 Recommendation**: Start with `npm run dev:full` to access all tools at once!

---

## 🎨 Database Designer - Complete Guide

Mifty provides **two ways** to design your database schema:
1. **🎨 Visual UI Designer** - Drag-and-drop interface (recommended for beginners)
2. **📝 Manual Code Editing** - Direct `db.design.ts` file editing (for advanced users)

Both approaches generate the same result and can be used interchangeably!

---

## 🎨 Method 1: Visual UI Designer

### 🚀 Getting Started

#### Step 1: Launch the Designer
```bash
# Option 1: Full development suite
npm run dev:full

# Option 2: Designer only
npm run db-designer
```

**Access the designer at:** `http://localhost:3001/ui`

#### Step 2: Designer Interface Overview

<table>
<tr>
<th>Section</th>
<th>Purpose</th>
<th>Key Features</th>
</tr>
<tr>
<td><strong>🎯 Canvas</strong></td>
<td>Main design area</td>
<td>Drag tables, create relationships</td>
</tr>
<tr>
<td><strong>🛠️ Toolbar</strong></td>
<td>Design tools</td>
<td>Add Table, Add Relationship, Save</td>
</tr>
<tr>
<td><strong>📋 Properties Panel</strong></td>
<td>Edit selected items</td>
<td>Column types, constraints, validations</td>
</tr>
<tr>
<td><strong>📜 Schema Preview</strong></td>
<td>Live Prisma schema</td>
<td>Real-time code generation</td>
</tr>
</table>

### 📋 Step-by-Step Tutorial

#### 🏗️ Creating Tables

**Step 1: Add a New Table**
1. Click **"+ Add Table"** button
2. Enter table name (e.g., "User")
3. Table appears on canvas

**Step 2: Add Columns**
1. Click on the table to select it
2. In Properties Panel, click **"+ Add Column"**
3. Configure each column:

<table>
<tr>
<th>Setting</th>
<th>Options</th>
<th>Example</th>
</tr>
<tr>
<td><strong>Name</strong></td>
<td>Column identifier</td>
<td><code>email</code>, <code>firstName</code></td>
</tr>
<tr>
<td><strong>Type</strong></td>
<td>String, Int, Boolean, DateTime, etc.</td>
<td><code>String</code> for email</td>
</tr>
<tr>
<td><strong>Required</strong></td>
<td>✅ Required / ❌ Optional</td>
<td>✅ for email</td>
</tr>
<tr>
<td><strong>Unique</strong></td>
<td>✅ Unique / ❌ Not unique</td>
<td>✅ for email</td>
</tr>
<tr>
<td><strong>Primary Key</strong></td>
<td>✅ Primary / ❌ Regular</td>
<td>✅ for id</td>
</tr>
<tr>
<td><strong>Default Value</strong></td>
<td>Static value or function</td>
<td><code>now()</code> for createdAt</td>
</tr>
</table>

#### 🎯 Complete Example: User Table

**Visual Steps:**
1. **Add Table** → Name: "User"
2. **Add Columns:**
   - `id`: String, Primary Key, Default: `cuid()`
   - `email`: String, Required, Unique
   - `firstName`: String, Required
   - `lastName`: String, Optional
   - `age`: Int, Optional
   - `isActive`: Boolean, Default: `true`
   - `createdAt`: DateTime, Default: `now()`
   - `updatedAt`: DateTime, Updated: `now()`

#### 🔗 Creating Relationships

**Step 1: Add Related Table**
1. Create "Post" table with columns:
   - `id`: String, Primary Key
   - `title`: String, Required
   - `content`: String, Optional
   - `authorId`: String, Required
   - `createdAt`: DateTime, Default: `now()`

**Step 2: Create Relationship**
1. Click **"+ Add Relationship"** button
2. **Select Source:** User table → id column
3. **Select Target:** Post table → authorId column
4. **Choose Type:** One-to-Many (User has many Posts)
5. **Relationship Name:** "posts" (on User), "author" (on Post)

#### 🎨 Available Relationship Types

<table>
<tr>
<th>Type</th>
<th>Description</th>
<th>Example</th>
<th>Visual Indicator</th>
</tr>
<tr>
<td><strong>One-to-One</strong></td>
<td>Each record relates to exactly one</td>
<td>User ↔ Profile</td>
<td>1 ——— 1</td>
</tr>
<tr>
<td><strong>One-to-Many</strong></td>
<td>One record relates to many</td>
<td>User → Posts</td>
<td>1 ——— ∞</td>
</tr>
<tr>
<td><strong>Many-to-Many</strong></td>
<td>Many records relate to many</td>
<td>Users ↔ Roles</td>
<td>∞ ——— ∞</td>
</tr>
</table>

#### 💾 Saving Your Design

**Auto-Save Features:**
- ✅ **Auto-saves** every change
- ✅ **Creates backups** with timestamps
- ✅ **Updates** `src/db.design.ts` automatically
- ✅ **Generates** Prisma schema in real-time

**Manual Save:**
- Click **"💾 Save Design"** button
- Downloads backup file
- Confirms all changes saved

### 🎨 Advanced UI Features

#### 🎯 Column Types & Constraints

<table>
<tr>
<th>Data Type</th>
<th>Use Case</th>
<th>Constraints Available</th>
</tr>
<tr>
<td><strong>String</strong></td>
<td>Text, emails, names</td>
<td>Required, Unique, Min/Max length</td>
</tr>
<tr>
<td><strong>Int</strong></td>
<td>Numbers, IDs, counts</td>
<td>Required, Unique, Min/Max value</td>
</tr>
<tr>
<td><strong>Float</strong></td>
<td>Decimals, prices</td>
<td>Required, Unique, Min/Max value</td>
</tr>
<tr>
<td><strong>Boolean</strong></td>
<td>True/false flags</td>
<td>Required, Default value</td>
</tr>
<tr>
<td><strong>DateTime</strong></td>
<td>Timestamps, dates</td>
<td>Required, Default: now(), updatedAt</td>
</tr>
<tr>
<td><strong>Json</strong></td>
<td>Complex data structures</td>
<td>Required, Default value</td>
</tr>
<tr>
<td><strong>Enum</strong></td>
<td>Fixed set of values</td>
<td>Required, Enum values list</td>
</tr>
</table>

#### 🔧 Default Value Options

<table>
<tr>
<th>Function</th>
<th>Description</th>
<th>Example Usage</th>
</tr>
<tr>
<td><code>cuid()</code></td>
<td>Unique identifier</td>
<td>Primary keys</td>
</tr>
<tr>
<td><code>uuid()</code></td>
<td>UUID identifier</td>
<td>Primary keys</td>
</tr>
<tr>
<td><code>now()</code></td>
<td>Current timestamp</td>
<td>createdAt fields</td>
</tr>
<tr>
<td><code>autoincrement()</code></td>
<td>Auto-incrementing number</td>
<td>Numeric IDs</td>
</tr>
<tr>
<td>Static values</td>
<td>Fixed default</td>
<td><code>"PENDING"</code>, <code>0</code>, <code>true</code></td>
</tr>
</table>

---

## 📝 Method 2: Manual Code Editing (`db.design.ts`)

For developers who prefer code-first approach or need more control, you can directly edit the `src/db.design.ts` file.

### 📁 File Structure

```typescript
// src/db.design.ts
export const dbDesign = {
  tables: [
    {
      name: "User",
      columns: [
        // Column definitions
      ],
      relationships: [
        // Relationship definitions  
      ]
    }
  ]
};
```

### 🏗️ Creating Tables Manually

#### Basic Table Structure

```typescript
export const dbDesign = {
  tables: [
    {
      name: "User",
      columns: [
        {
          name: "id",
          type: "String",
          isPrimaryKey: true,
          isRequired: true,
          defaultValue: "cuid()"
        },
        {
          name: "email", 
          type: "String",
          isRequired: true,
          isUnique: true
        },
        {
          name: "firstName",
          type: "String", 
          isRequired: true
        },
        {
          name: "lastName",
          type: "String",
          isRequired: false
        },
        {
          name: "age",
          type: "Int",
          isRequired: false,
          minValue: 0,
          maxValue: 150
        },
        {
          name: "isActive",
          type: "Boolean",
          isRequired: true,
          defaultValue: "true"
        },
        {
          name: "createdAt",
          type: "DateTime",
          isRequired: true,
          defaultValue: "now()"
        },
        {
          name: "updatedAt",
          type: "DateTime",
          isRequired: true,
          isUpdatedAt: true
        }
      ]
    }
  ]
};
```

### 📋 Column Configuration Options

#### 🎯 All Available Column Properties

```typescript
{
  name: "columnName",           // Required: Column identifier
  type: "String",               // Required: Data type
  
  // Constraints
  isRequired: true,             // Optional: Not null constraint
  isUnique: true,               // Optional: Unique constraint  
  isPrimaryKey: true,           // Optional: Primary key
  isUpdatedAt: true,            // Optional: Auto-update timestamp
  
  // Default values
  defaultValue: "cuid()",       // Optional: Default value or function
  
  // String constraints
  minLength: 3,                 // Optional: Minimum string length
  maxLength: 100,               // Optional: Maximum string length
  
  // Numeric constraints  
  minValue: 0,                  // Optional: Minimum numeric value
  maxValue: 1000,               // Optional: Maximum numeric value
  
  // Enum values (for Enum type)
  enumValues: ["PENDING", "APPROVED", "REJECTED"],
  
  // Relationships
  relationTo: "Post",           // Optional: Related table name
  relationType: "OneToMany",    // Optional: Relationship type
  relationName: "posts"         // Optional: Relationship field name
}
```

#### 🎨 Data Types Reference

<table>
<tr>
<th>Type</th>
<th>TypeScript</th>
<th>Database</th>
<th>Example</th>
</tr>
<tr>
<td><code>String</code></td>
<td><code>string</code></td>
<td>VARCHAR/TEXT</td>
<td><code>"John Doe"</code></td>
</tr>
<tr>
<td><code>Int</code></td>
<td><code>number</code></td>
<td>INTEGER</td>
<td><code>42</code></td>
</tr>
<tr>
<td><code>Float</code></td>
<td><code>number</code></td>
<td>DECIMAL/FLOAT</td>
<td><code>3.14</code></td>
</tr>
<tr>
<td><code>Boolean</code></td>
<td><code>boolean</code></td>
<td>BOOLEAN</td>
<td><code>true</code></td>
</tr>
<tr>
<td><code>DateTime</code></td>
<td><code>Date</code></td>
<td>TIMESTAMP</td>
<td><code>2024-01-15T10:30:00Z</code></td>
</tr>
<tr>
<td><code>Json</code></td>
<td><code>object</code></td>
<td>JSON/JSONB</td>
<td><code>{"key": "value"}</code></td>
</tr>
<tr>
<td><code>Enum</code></td>
<td><code>enum</code></td>
<td>ENUM</td>
<td><code>"ACTIVE"</code></td>
</tr>
</table>

### 🔗 Creating Relationships Manually

#### One-to-Many Relationship Example

```typescript
export const dbDesign = {
  tables: [
    {
      name: "User",
      columns: [
        { name: "id", type: "String", isPrimaryKey: true, defaultValue: "cuid()" },
        { name: "email", type: "String", isRequired: true, isUnique: true },
        { name: "name", type: "String", isRequired: true }
      ],
      relationships: [
        {
          type: "OneToMany",
          relatedTable: "Post",
          foreignKey: "authorId",
          relationName: "posts"
        }
      ]
    },
    {
      name: "Post", 
      columns: [
        { name: "id", type: "String", isPrimaryKey: true, defaultValue: "cuid()" },
        { name: "title", type: "String", isRequired: true },
        { name: "content", type: "String", isRequired: false },
        { name: "authorId", type: "String", isRequired: true }
      ],
      relationships: [
        {
          type: "ManyToOne",
          relatedTable: "User", 
          foreignKey: "authorId",
          relationName: "author"
        }
      ]
    }
  ]
};
```

#### Many-to-Many Relationship Example

```typescript
export const dbDesign = {
  tables: [
    {
      name: "User",
      columns: [
        { name: "id", type: "String", isPrimaryKey: true, defaultValue: "cuid()" },
        { name: "email", type: "String", isRequired: true, isUnique: true }
      ],
      relationships: [
        {
          type: "ManyToMany",
          relatedTable: "Role",
          relationName: "roles",
          inverseRelationName: "users"
        }
      ]
    },
    {
      name: "Role",
      columns: [
        { name: "id", type: "String", isPrimaryKey: true, defaultValue: "cuid()" },
        { name: "name", type: "String", isRequired: true, isUnique: true }
      ],
      relationships: [
        {
          type: "ManyToMany", 
          relatedTable: "User",
          relationName: "users",
          inverseRelationName: "roles"
        }
      ]
    }
  ]
};
```

### 🎯 Complete Real-World Example

```typescript
// src/db.design.ts
export const dbDesign = {
  tables: [
    {
      name: "User",
      columns: [
        {
          name: "id",
          type: "String",
          isPrimaryKey: true,
          isRequired: true,
          defaultValue: "cuid()"
        },
        {
          name: "email",
          type: "String", 
          isRequired: true,
          isUnique: true,
          minLength: 5,
          maxLength: 100
        },
        {
          name: "firstName",
          type: "String",
          isRequired: true,
          minLength: 2,
          maxLength: 50
        },
        {
          name: "lastName", 
          type: "String",
          isRequired: false,
          maxLength: 50
        },
        {
          name: "age",
          type: "Int",
          isRequired: false,
          minValue: 13,
          maxValue: 120
        },
        {
          name: "status",
          type: "Enum",
          enumValues: ["ACTIVE", "INACTIVE", "SUSPENDED"],
          isRequired: true,
          defaultValue: "ACTIVE"
        },
        {
          name: "profile",
          type: "Json",
          isRequired: false
        },
        {
          name: "createdAt",
          type: "DateTime",
          isRequired: true,
          defaultValue: "now()"
        },
        {
          name: "updatedAt",
          type: "DateTime", 
          isRequired: true,
          isUpdatedAt: true
        }
      ],
      relationships: [
        {
          type: "OneToMany",
          relatedTable: "Post",
          foreignKey: "authorId", 
          relationName: "posts"
        },
        {
          type: "OneToOne",
          relatedTable: "Profile",
          foreignKey: "userId",
          relationName: "profile"
        }
      ]
    },
    {
      name: "Post",
      columns: [
        {
          name: "id",
          type: "String",
          isPrimaryKey: true,
          defaultValue: "cuid()"
        },
        {
          name: "title",
          type: "String",
          isRequired: true,
          minLength: 5,
          maxLength: 200
        },
        {
          name: "content",
          type: "String",
          isRequired: false
        },
        {
          name: "published",
          type: "Boolean",
          isRequired: true,
          defaultValue: "false"
        },
        {
          name: "authorId",
          type: "String",
          isRequired: true
        },
        {
          name: "createdAt",
          type: "DateTime",
          defaultValue: "now()"
        }
      ],
      relationships: [
        {
          type: "ManyToOne",
          relatedTable: "User",
          foreignKey: "authorId",
          relationName: "author"
        }
      ]
    },
    {
      name: "Profile",
      columns: [
        {
          name: "id", 
          type: "String",
          isPrimaryKey: true,
          defaultValue: "cuid()"
        },
        {
          name: "bio",
          type: "String",
          isRequired: false,
          maxLength: 500
        },
        {
          name: "avatar",
          type: "String",
          isRequired: false
        },
        {
          name: "userId",
          type: "String",
          isRequired: true,
          isUnique: true
        }
      ],
      relationships: [
        {
          type: "OneToOne",
          relatedTable: "User",
          foreignKey: "userId",
          relationName: "user"
        }
      ]
    }
  ]
};
```

### 🔄 Switching Between Methods

**UI to Code:**
- Design in UI → Automatically updates `db.design.ts`
- All changes reflected in code immediately

**Code to UI:**
- Edit `db.design.ts` → Refresh UI to see changes
- UI loads your code-based design

### ✅ Validation & Testing

**Validate your design:**
```bash
# Generate Prisma schema to check for errors
npm run prisma:generate

# Check if design is valid
npm run generate
```

**Common validation errors:**
- Missing required fields
- Invalid relationship configurations
- Duplicate column names
- Invalid data types

### 🎯 Pro Tips for Manual Editing

1. **🔍 Use TypeScript**: Enable IntelliSense for better editing experience
2. **📋 Copy from UI**: Design complex relationships in UI, then copy the generated code
3. **🧪 Test frequently**: Run `npm run prisma:generate` to validate changes
4. **📦 Version control**: Commit `db.design.ts` changes for team collaboration
5. **🔄 Backup**: UI creates automatic backups, but manual backups are recommended

### 🎨 Designer Features Summary

| Feature | UI Method | Manual Method |
|---------|-----------|---------------|
| **🎯 Ease of Use** | ✅ Drag & drop | 🔧 Code editing |
| **🚀 Speed** | ✅ Very fast | 🔧 Moderate |
| **🎨 Visual Feedback** | ✅ Real-time | ❌ None |
| **🔧 Fine Control** | 🔧 Limited | ✅ Complete |
| **📋 Complex Schemas** | 🔧 Can get cluttered | ✅ Clean code |
| **👥 Team Collaboration** | 🔧 Visual sharing | ✅ Git-friendly |
| **📚 Learning Curve** | ✅ Beginner-friendly | 🔧 Requires knowledge |

**🎯 Recommendation**: Start with the UI for learning, then switch to manual editing for complex projects or when you need precise control.

---

### 3️⃣ Generate Your API Code

```bash
npm run generate
```

#### 🎯 Interactive Generation Process

<table>
<tr>
<th>Step</th>
<th>What You Choose</th>
<th>Example</th>
</tr>
<tr>
<td>**1️⃣ Source**</td>
<td>Generate from db.design.ts</td>
<td>✅ Use your visual design</td>
</tr>
<tr>
<td>**2️⃣ Tables**</td>
<td>Select tables to generate</td>
<td>☑️ User ☑️ Post ☐ Comment</td>
</tr>
<tr>
<td>**3️⃣ Features**</td>
<td>Choose what to include</td>
<td>✅ CRUD ✅ Search ✅ Tests</td>
</tr>
<tr>
<td>**4️⃣ Confirm**</td>
<td>Review and generate</td>
<td>🚀 Generate 47 files in 3 seconds</td>
</tr>
</table>

#### 📦 What Gets Generated (Per Table)

<div align="center">

| Layer | Files Generated | Purpose |
|-------|----------------|---------|
| **🎯 Types** | `user.entity.ts` | TypeScript interfaces |
| **📝 DTOs** | `create-user.dto.ts`, `update-user.dto.ts` | Data transfer objects |
| **🗄️ Repository** | `user.repository.ts` | Database operations |
| **⚙️ Service** | `user.service.ts` | Business logic |
| **🌐 Controller** | `user.controller.ts` | HTTP request handlers |
| **🛣️ Routes** | `user.routes.ts` | API endpoints |
| **✅ Validation** | `user.validation.ts` | Zod schemas |
| **🧪 Tests** | `user.service.test.ts`, `user.controller.test.ts` | Unit tests |
| **🔗 Integration** | `user.integration.test.ts` | API tests |

</div>

#### 🎯 Generation Features

<details>
<summary><strong>🚀 What You Get Out of the Box</strong></summary>

**📋 CRUD Operations:**
- ✅ Create new records with validation
- ✅ Read with pagination and filtering
- ✅ Update with partial data support
- ✅ Delete with soft delete option
- ✅ Bulk operations support

**🔍 Advanced Features:**
- ✅ Search across multiple fields
- ✅ Advanced filtering and sorting
- ✅ Pagination with limit/offset
- ✅ Relationship loading (eager/lazy)
- ✅ Input validation with Zod
- ✅ Error handling and logging

**🧪 Testing Suite:**
- ✅ Unit tests with 90%+ coverage
- ✅ Integration tests for all endpoints
- ✅ Mocked dependencies
- ✅ Test fixtures and factories
- ✅ Performance tests

</details>

#### 🎉 Result: Instant API

After generation, you immediately get:

```bash
# Your API endpoints are ready!
GET    /api/v1/user/          # List users (with pagination)
GET    /api/v1/user/search    # Search users
GET    /api/v1/user/:id       # Get user by ID
POST   /api/v1/user/          # Create new user
PUT    /api/v1/user/:id       # Update user
DELETE /api/v1/user/:id       # Delete user

# Same for every table you generated!
GET    /api/v1/post/          # Post endpoints
GET    /api/v1/comment/       # Comment endpoints
```

---

### 4️⃣ Install Adapters (Optional)

**🔌 Plug-and-play integrations for AWS, Stripe, Email, Storage, Authentication, and more!**

Mifty adapters are **installed from npm** (not copied into your project), keeping your codebase lightweight while providing powerful integrations.

#### Quick Start with Adapters

```bash
# List all available adapters
npm run adapter list

# List authentication adapters
npm run auth:list

# Check what's already installed
npm run adapter installed
```

---

#### 📦 Service Adapters

**Available Service Adapters:**

<table>
<tr>
<th>Category</th>
<th>Adapters</th>
<th>Install Command</th>
</tr>
<tr>
<td><strong>☁️ Cloud Storage</strong></td>
<td>AWS S3, Local Storage</td>
<td><code>npm run adapter install storage-service</code></td>
</tr>
<tr>
<td><strong>📧 Email Service</strong></td>
<td>Gmail, SMTP, SendGrid, AWS SES</td>
<td><code>npm run adapter install email-service</code></td>
</tr>
<tr>
<td><strong>💳 Payments</strong></td>
<td>Stripe</td>
<td><code>npm run adapter install stripe</code></td>
</tr>
<tr>
<td><strong>💾 Caching</strong></td>
<td>Redis</td>
<td><code>npm run adapter install redis</code></td>
</tr>
<tr>
<td><strong>💬 Messaging</strong></td>
<td>Twilio SMS</td>
<td><code>npm run adapter install twilio</code></td>
</tr>
<tr>
<td><strong>🤖 AI/ML</strong></td>
<td>OpenAI</td>
<td><code>npm run adapter install openai</code></td>
</tr>
<tr>
<td><strong>🔥 Backend Services</strong></td>
<td>Firebase</td>
<td><code>npm run adapter install firebase</code></td>
</tr>
<tr>
<td><strong>⚡ Serverless</strong></td>
<td>AWS Lambda</td>
<td><code>npm run adapter install aws-lambda</code></td>
</tr>
</table>

**⭐ Universal Adapters** (Switch providers via .env):

1. **Storage Service Adapter**
   ```bash
   npm run adapter install storage-service
   ```
   - Switch between **AWS S3** and **Local Storage** via `.env`
   - Unified API for all storage operations
   - Perfect for development (local) → production (S3) workflow

2. **Email Service Adapter**
   ```bash
   npm run adapter install email-service
   ```
   - Switch between **Gmail** and **SMTP** via `.env`
   - Built-in OTP email templates
   - Unified API for all email operations

**Usage Examples:**

```typescript
// Storage Service - Upload files (S3 or Local based on .env)
import { storageService } from '@/adapters/storage-service/storage.adapter';

const result = await storageService.upload({
  file: fileBuffer,
  fileName: 'avatar.jpg',
  key: 'avatars/user-123/avatar.jpg',
  contentType: 'image/jpeg',
});
console.log(result.url); // Public URL to access the file

// Email Service - Send emails (Gmail or SMTP based on .env)
import { emailService } from '@/adapters/email-service/email.adapter';

await emailService.sendOTP('user@example.com', '123456', 5);
await emailService.sendEmail({
  to: 'user@example.com',
  subject: 'Welcome!',
  html: '<h1>Welcome to our app!</h1>',
});
```

**Configuration (.env):**

```env
# Storage Service - Choose provider
STORAGE_TYPE=local                    # or 's3'
LOCAL_UPLOAD_DIR=./uploads
LOCAL_BASE_URL=http://localhost:3000/uploads
AWS_S3_BUCKET=my-bucket
AWS_REGION=us-east-1

# Email Service - Choose provider
EMAIL_PROVIDER=gmail                  # or 'smtp'
GMAIL_USER=your-email@gmail.com
GMAIL_APP_PASSWORD=your-app-password
SMTP_HOST=smtp.example.com
SMTP_PORT=587
```

---

#### 🔐 Authentication Adapters

**Available Auth Adapters:**

<table>
<tr>
<th>Type</th>
<th>Provider</th>
<th>Install Command</th>
</tr>
<tr>
<td rowspan="4"><strong>OAuth 2.0</strong></td>
<td>GitHub</td>
<td><code>npm run auth:install auth-github</code></td>
</tr>
<tr>
<td>Google</td>
<td><code>npm run auth:install auth-google</code></td>
</tr>
<tr>
<td>LinkedIn</td>
<td><code>npm run auth:install auth-linkedin</code></td>
</tr>
<tr>
<td>Facebook</td>
<td><code>npm run auth:install auth-facebook</code></td>
</tr>
<tr>
<td rowspan="2"><strong>OTP Auth</strong></td>
<td>Email OTP</td>
<td><code>npm run auth:install auth-email-otp</code></td>
</tr>
<tr>
<td>Mobile OTP</td>
<td><code>npm run auth:install auth-mobile-otp</code></td>
</tr>
</table>

**Quick Setup Example:**

```bash
# 1. Install GitHub OAuth
npm run auth:install auth-github

# 2. Install Email OTP with Gmail
npm run auth:install auth-email-otp
npm run adapter install email-service

# 3. Configure .env
# Add your OAuth credentials and email settings

# 4. Use in your app
# OAuth: http://localhost:3000/api/v1/auth/github
# OTP: POST /api/v1/auth/otp/send
```

**Usage Example:**

```html
<!-- OAuth Login Buttons -->
<a href="/api/v1/auth/github">
  <button>Login with GitHub</button>
</a>
<a href="/api/v1/auth/google">
  <button>Login with Google</button>
</a>

<!-- Email OTP Login -->
<form id="otpForm">
  <input type="email" id="email" placeholder="Enter email" />
  <button type="submit">Send OTP</button>
</form>

<script>
// Send OTP
document.getElementById('otpForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const email = document.getElementById('email').value;

  await fetch('/api/v1/auth/otp/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email })
  });

  alert('OTP sent to your email!');
});

// Verify OTP
async function verifyOTP(email, otp) {
  const response = await fetch('/api/v1/auth/otp/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, otp })
  });

  const data = await response.json();
  localStorage.setItem('token', data.token);
}
</script>
```

---

#### 📖 Adapter Documentation

- **[Complete Adapter Commands Reference](./ADAPTERS.md)** - All adapter installation commands
- **[Commands Reference](./COMMANDS.md)** - All CLI commands including adapters

**Key Features:**
- ✅ **Zero Configuration** - Works out of the box with sensible defaults
- ✅ **Environment-based** - Switch providers via `.env` file
- ✅ **Auto Dependencies** - Automatically installs required npm packages
- ✅ **Type Safe** - Full TypeScript support with IntelliSense
- ✅ **Lightweight** - Adapters stay in `node_modules`, not copied to your project
- ✅ **Production Ready** - Battle-tested integrations

---

### 5️⃣ Test Your API

```bash
# Start your API server
npm run dev
```

#### 🧪 Test Your Endpoints

**Using curl:**
```bash
# Create a user
curl -X POST http://localhost:3000/api/v1/user \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com"}'

# Get all users
curl http://localhost:3000/api/v1/user

# Search users
curl "http://localhost:3000/api/v1/user/search?name=John"
```

**Using your browser:**
```
🌐 http://localhost:3000/api/v1/user          # List all users
🌐 http://localhost:3000/api/v1/user/search   # Search interface
🌐 http://localhost:3000/health               # Health check
```

#### 📊 Monitor Your API

<table>
<tr>
<td width="50%">

**🔍 Real-time Monitoring:**
- Error detection and auto-fix
- Import issue resolution
- Performance monitoring
- Request/response logging

</td>
<td width="50%">

**🧪 Testing Tools:**
- Run tests: `npm test`
- Watch mode: `npm run test:watch`
- Coverage: `npm run test:coverage`
- Integration tests included

</td>
</tr>
</table>

#### 🚀 Production Deployment

```bash
# Build for production
npm run build

# Start production server
npm start

# Or use Docker
docker build -t my-api .
docker run -p 3000:3000 my-api
```

---

## 📁 Project Structure

```
my-project/
├── 📂 src/
│   ├── 📂 modules/                    # 🤖 Auto-generated modules
│   │   └── 📂 user/                   # Example: User module
│   │       ├── 📂 controllers/        # HTTP request handlers
│   │       │   └── user.controller.ts
│   │       ├── 📂 services/           # Business logic layer
│   │       │   └── user.service.ts
│   │       ├── 📂 repositories/       # Database operations
│   │       │   └── user.repository.ts
│   │       ├── 📂 entities/           # TypeScript types
│   │       │   └── user.entity.ts
│   │       ├── 📂 dtos/               # Data transfer objects
│   │       │   ├── create-user.dto.ts
│   │       │   └── update-user.dto.ts
│   │       ├── 📂 validations/        # Zod validation schemas
│   │       │   └── user.validation.ts
│   │       ├── 📂 routes/             # Express routes
│   │       │   └── user.routes.ts
│   │       └── 📂 tests/              # Unit tests
│   │           ├── user.service.test.ts
│   │           └── user.controller.test.ts
│   │
│   ├── 📂 adapters/                   # 🔌 Installed service adapters
│   │   ├── 📂 aws-s3/                 # AWS S3 adapter
│   │   │   ├── s3.adapter.ts
│   │   │   ├── s3.config.ts
│   │   │   └── README.md
│   │   ├── 📂 stripe/                 # Stripe adapter
│   │   │   ├── stripe.adapter.ts
│   │   │   └── stripe.config.ts
│   │   └── index.ts                   # Adapter registry
│   │
│   ├── 📂 tests/
│   │   └── 📂 integration/            # Integration tests
│   │       └── user.integration.test.ts
│   │
│   ├── 📂 prisma/
│   │   ├── schema.prisma              # Prisma schema (auto-generated)
│   │   └── 📂 migrations/             # Database migrations
│   │
│   ├── 📂 core/                       # Framework core utilities
│   │   ├── 📂 interfaces/             # Base interfaces
│   │   ├── 📂 utils/                  # Utility functions
│   │   └── 📂 decorators/             # Custom decorators
│   │
│   ├── 📂 loaders/                    # App initialization
│   │   ├── express.ts                 # Express setup
│   │   ├── prisma.ts                  # Prisma client
│   │   └── routes.ts                  # Route loader
│   │
│   ├── 📂 routes/                     # Route registration
│   │   └── index.ts                   # Main router
│   │
│   ├── 📂 servers/                    # Server configurations
│   │   ├── user.server.ts             # Main API server
│   │   └── db-designer.server.ts      # DB Designer server
│   │
│   ├── 📂 config/                     # Configuration files
│   │   ├── services.config.ts         # Services orchestration
│   │   └── microservices.config.ts    # Microservices setup
│   │
│   ├── 📂 types/                      # Global TypeScript types
│   │   └── app-config.ts
│   │
│   ├── 📄 app.ts                      # Express app setup
│   └── 📄 db.design.ts                # 🎨 Database design file
│
├── 📂 node_modules/
│   └── 📂 mifty/                 # Framework tools (not copied)
│       ├── 📂 bin/                    # CLI executables
│       ├── 📂 src/ui/                 # DB Designer UI
│       └── 📂 src/scripts/            # Generator scripts
│
├── 📄 COMMANDS.md                     # 📋 Quick command reference
├── 📄 README.md                       # 📖 This file
├── 📄 package.json                    # Dependencies & scripts
├── 📄 tsconfig.json                   # TypeScript configuration
├── 📄 .env                            # Environment variables
└── 📄 docker-compose.yml              # Docker setup
```

### 🎯 Key Directories

| Directory | Purpose | Auto-Generated? |
|-----------|---------|-----------------|
| `src/modules/` | Your business modules | ✅ Yes |
| `src/prisma/` | Database schema & migrations | ✅ Yes |
| `src/core/` | Framework utilities | ❌ No (Framework) |
| `src/loaders/` | App initialization | ❌ No (Framework) |
| `src/servers/` | Server configurations | ⚠️ Customizable |
| `src/config/` | Service configurations | ⚠️ Customizable |

---

## 🛠️ Available Commands

> **📖 See [COMMANDS.md](./COMMANDS.md) for the complete command reference with all endpoints**

### 🚀 Development Commands

<table>
<tr>
<th>Command</th>
<th>Description</th>
<th>When to Use</th>
</tr>
<tr>
<td><code>npm run dev</code></td>
<td>Start API + Monitor</td>
<td>✅ Daily development</td>
</tr>
<tr>
<td><code>npm run dev:full</code></td>
<td>Start API + DB Designer + Monitor + Prisma Studio</td>
<td>🎨 Database design work</td>
</tr>
<tr>
<td><code>npm run dev:server</code></td>
<td>Start API server only</td>
<td>🔧 Testing API only</td>
</tr>
<tr>
<td><code>npm run dev:monitor</code></td>
<td>Start error monitor only</td>
<td>🔍 Error monitoring</td>
</tr>
<tr>
<td><code>npm run dev:db-designer</code></td>
<td>Start DB Designer UI only</td>
<td>🎨 Database design only</td>
</tr>
</table>

### 🏗️ Build & Production

```bash
npm run build                  # Build TypeScript to JavaScript
npm run build:watch            # Watch mode - rebuild on changes
npm start                      # Start production server
```

### 🗄️ Database Commands

```bash
npm run prisma:generate        # Generate Prisma Client
npm run prisma:migrate         # Create and apply migration
npm run prisma:studio          # Open Prisma Studio (port 5555)
npm run prisma:push            # Push schema without migration
npm run prisma:reset           # Reset database (⚠️ deletes all data)
```

### 🤖 Module Generation

```bash
npm run generate               # Interactive module generator
npm run generate:module <name> # Generate a specific module
npm run generate:ai            # Generate AI tests/docs
```

### 🧪 Testing

```bash
npm test                       # Run all tests with coverage
npm run test:watch             # Run tests in watch mode
npm run test:coverage          # Detailed coverage report
```

### 🔍 Error Monitoring

```bash
npm run monitor                # Start error monitor
npm run monitor:autofix        # Monitor with auto-fix enabled
npm run watch:imports          # Watch import issues
```

### ✨ Code Quality

```bash
npm run lint                   # Run ESLint
npm run lint:fix               # Run ESLint with auto-fix
npm run format                 # Format code with Prettier
```

---

## 🌐 Service Endpoints

### API Server (Port 3000)
```
http://localhost:3000                    # Main API
http://localhost:3000/api/v1/user        # User endpoints (example)
http://localhost:3000/health             # Health check
```

### DB Designer (Port 3001)
```
http://localhost:3001/ui                 # DB Designer UI
http://localhost:3001/api/db-design      # Get/Update design (API)
http://localhost:3001/health             # Health check
```

**DB Designer API Endpoints:**
- `GET /api/db-design` - Get current database design
- `POST /api/db-design` - Update database design
- `POST /api/db-design/validate` - Validate design structure
- `GET /api/db-design/backups` - List all backup files
- `POST /api/db-design/restore/:filename` - Restore from backup

### Prisma Studio (Port 5555)
```
http://localhost:5555                    # Prisma Studio UI
```

---



## 🧪 Testing

Auto-generated tests include:

### Unit Tests
- Service layer tests with mocked repositories
- Controller tests with mocked services
- Validation schema tests

### Integration Tests
- Full HTTP request/response cycle
- Database operations
- Error handling

```bash
npm test                       # Run all tests
npm run test:watch             # Watch mode
npm run test:coverage          # Coverage report
```

---

## 🚀 Deployment

### Environment Variables

Create `.env` file in your project root (use `.env.example` as a template):

```bash
# Copy the example file
cp .env.example .env

# Edit with your configuration
nano .env
```

**Example configuration:**

```env
# Server Configuration
NODE_ENV=production
PORT=3000

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/mydb

# Security
JWT_SECRET=your-super-secret-jwt-key-change-this
CORS_ORIGIN=https://yourdomain.com

# Optional: DB Designer (if deploying separately)
DB_DESIGNER_PORT=3001

# Optional: Logging
LOG_LEVEL=info
```

### Build & Deploy

```bash
# 1. Install dependencies
npm install --production

# 2. Generate Prisma Client
npm run prisma:generate

# 3. Run migrations
npm run prisma:migrate:deploy

# 4. Build TypeScript
npm run build

# 5. Start production server
npm start
```

### Docker Deployment

```bash
# Build Docker image
docker build -t my-api .

# Run container
docker run -p 3000:3000 --env-file .env my-api

# Or use docker-compose
docker-compose up -d
```

### Production Checklist

<table>
<tr>
<th>Category</th>
<th>Checklist Items</th>
</tr>
<tr>
<td><strong>🔒 Security</strong></td>
<td>
✅ Set <code>NODE_ENV=production</code><br/>
✅ Use strong <code>JWT_SECRET</code><br/>
✅ Configure CORS for your domain<br/>
✅ Enable Helmet security headers<br/>
✅ Set up rate limiting<br/>
✅ Use HTTPS in production
</td>
</tr>
<tr>
<td><strong>🗄️ Database</strong></td>
<td>
✅ Configure production <code>DATABASE_URL</code><br/>
✅ Run all migrations<br/>
✅ Set up database backups<br/>
✅ Configure connection pooling<br/>
✅ Enable query logging (if needed)
</td>
</tr>
<tr>
<td><strong>📊 Monitoring</strong></td>
<td>
✅ Set up error tracking (Sentry, etc.)<br/>
✅ Configure logging service<br/>
✅ Set up uptime monitoring<br/>
✅ Enable performance monitoring<br/>
✅ Configure alerts
</td>
</tr>
<tr>
<td><strong>⚡ Performance</strong></td>
<td>
✅ Enable compression<br/>
✅ Configure caching<br/>
✅ Optimize database queries<br/>
✅ Set up CDN for static assets<br/>
✅ Enable gzip compression
</td>
</tr>
<tr>
<td><strong>🔄 CI/CD</strong></td>
<td>
✅ Set up automated tests<br/>
✅ Configure deployment pipeline<br/>
✅ Enable automatic migrations<br/>
✅ Set up staging environment<br/>
✅ Configure rollback strategy
</td>
</tr>
</table>

---

## 🙋‍♂️ Frequently Asked Questions

<details>
<summary><strong>❓ Is Mifty suitable for beginners?</strong></summary>

**Absolutely!** Mifty is designed to be beginner-friendly:
- 🎨 Visual database designer (no SQL knowledge required)
- 🤖 Auto-generates all boilerplate code
- 📚 Comprehensive documentation and examples
- 🔍 Built-in error monitoring with helpful suggestions
- 💡 Works with SQLite out of the box (no database setup needed)

</details>

<details>
<summary><strong>❓ Can I use Mifty for production applications?</strong></summary>

**Yes!** Mifty generates production-ready code:
- 🛡️ Built-in security best practices
- 🧪 Comprehensive test coverage
- 📈 Scalable clean architecture
- 🔒 Type-safe with TypeScript
- 🚀 Docker support included
- 📊 Performance monitoring ready

</details>

<details>
<summary><strong>❓ What databases does Mifty support?</strong></summary>

Mifty supports all Prisma-compatible databases:
- ✅ **PostgreSQL** (recommended for production)
- ✅ **MySQL/MariaDB**
- ✅ **SQLite** (default, great for development)
- ✅ **SQL Server**
- ✅ **MongoDB** (via Prisma)
- ✅ **CockroachDB**

</details>

<details>
<summary><strong>❓ How is Mifty different from other frameworks?</strong></summary>

**Key differences:**
- 🎨 **Visual Database Designer** - No other framework has this
- 🤖 **Complete Code Generation** - Not just scaffolding, but production-ready code
- 🔍 **AI-Powered Error Monitoring** - Auto-fixes common issues
- 📦 **Lightweight Architecture** - Tools stay in node_modules
- 🔌 **Rich Adapter Ecosystem** - 20+ pre-built integrations

</details>

<details>
<summary><strong>❓ Can I customize the generated code?</strong></summary>

**Absolutely!** 
- ✅ Generated code is fully editable
- ✅ Clean, readable TypeScript
- ✅ Follows standard patterns
- ✅ Well-commented and documented
- ✅ Easy to extend and modify
- ✅ No vendor lock-in

</details>

<details>
<summary><strong>❓ Does Mifty support microservices?</strong></summary>

**Yes!** Mifty is microservices-ready:
- 🏗️ Modular architecture
- 🔧 Configurable service orchestration
- 🐳 Docker support
- 🌐 API Gateway patterns
- 📡 Service discovery ready
- 🔄 Independent deployments

</details>

---

## ✅ Complete Getting Started Checklist

### 🎯 Your First 10 Minutes with Mifty

<table>
<tr>
<th>Step</th>
<th>Command</th>
<th>Time</th>
<th>What You Get</th>
</tr>
<tr>
<td>**1️⃣ Install**</td>
<td><code>npm install -g @mifty/cli</code></td>
<td>30s</td>
<td>Mifty CLI ready to use</td>
</tr>
<tr>
<td>**2️⃣ Create**</td>
<td><code>mifty init my-api && cd my-api</code></td>
<td>30s</td>
<td>Complete project structure</td>
</tr>
<tr>
<td>**3️⃣ Install**</td>
<td><code>npm install</code></td>
<td>2min</td>
<td>All dependencies installed</td>
</tr>
<tr>
<td>**4️⃣ Start**</td>
<td><code>npm run dev:full</code></td>
<td>10s</td>
<td>API + DB Designer + Studio running</td>
</tr>
<tr>
<td>**5️⃣ Design**</td>
<td>Open http://localhost:3001/ui</td>
<td>2min</td>
<td>Visual database schema</td>
</tr>
<tr>
<td>**6️⃣ Generate**</td>
<td><code>npm run generate</code></td>
<td>30s</td>
<td>Complete CRUD API with tests</td>
</tr>
<tr>
<td>**7️⃣ Test**</td>
<td><code>npm test</code></td>
<td>1min</td>
<td>All tests passing ✅</td>
</tr>
<tr>
<td colspan="3"><strong>Total Time:</strong></td>
<td><strong>~7 minutes to working API!</strong></td>
</tr>
</table>

### 🎯 What You Should Have Now

After following the checklist:

- ✅ **Running API Server** at http://localhost:3000
- ✅ **Database Designer** at http://localhost:3001/ui  
- ✅ **Database Viewer** at http://localhost:5555
- ✅ **Generated API Endpoints** (e.g., `/api/v1/user/`)
- ✅ **Comprehensive Tests** with high coverage
- ✅ **Error Monitoring** with auto-fix
- ✅ **Production-Ready Code** with TypeScript

### 🚀 Next Steps

<table>
<tr>
<td width="33%">

**🔌 Add Integrations**
```bash
npm run adapter list
npm run auth:list
```
Install AWS, Stripe, Auth adapters

</td>
<td width="33%">

**🎨 Enhance Database**
- Add more tables
- Create relationships  
- Set up validations
- Plan for scale

</td>
<td width="33%">

**🚀 Deploy**
```bash
npm run build
npm start
```
Deploy to production

</td>
</tr>
</table>

---

## 📚 Real-World Examples

### Example 1: Blog API in 5 Minutes

```bash
# 1. Create project
mifty init blog-api
cd blog-api
npm install

# 2. Start DB Designer
npm run dev:db-designer
```

**Design your schema at http://localhost:3001/ui:**

<table>
<tr>
<th>Table</th>
<th>Columns</th>
<th>Relations</th>
</tr>
<tr>
<td><strong>User</strong></td>
<td>
• id (UUID)<br/>
• email (String, unique)<br/>
• name (String)<br/>
• password (String)<br/>
• createdAt (DateTime)
</td>
<td>
→ One-to-Many with Post<br/>
→ One-to-Many with Comment
</td>
</tr>
<tr>
<td><strong>Post</strong></td>
<td>
• id (UUID)<br/>
• title (String)<br/>
• content (Text)<br/>
• published (Boolean)<br/>
• authorId (UUID)<br/>
• createdAt (DateTime)
</td>
<td>
← Many-to-One with User<br/>
→ One-to-Many with Comment<br/>
→ Many-to-Many with Tag
</td>
</tr>
<tr>
<td><strong>Comment</strong></td>
<td>
• id (UUID)<br/>
• content (Text)<br/>
• postId (UUID)<br/>
• authorId (UUID)<br/>
• createdAt (DateTime)
</td>
<td>
← Many-to-One with Post<br/>
← Many-to-One with User
</td>
</tr>
<tr>
<td><strong>Tag</strong></td>
<td>
• id (UUID)<br/>
• name (String, unique)<br/>
• slug (String, unique)
</td>
<td>
→ Many-to-Many with Post
</td>
</tr>
</table>

```bash
# 3. Generate modules
npm run generate

# 4. Start A