# AI Master Prompt for CodeFlow MVP
## 1. PROJECT OVERVIEW
**App Name:** CodeFlow
**Value Proposition:** CodeFlow is a revolutionary SaaS platform designed to significantly accelerate the compilation and optimization of OCaml code by leveraging a new, high-performance C++ backend for the Ocamlc compiler. It provides developers with a dramatically faster and more efficient compilation experience, especially beneficial for large-scale projects and performance-critical applications. By translating OCaml code into idiomatic and readable C++, CodeFlow enables faster execution, easier debugging, and seamless integration with C++ ecosystems.
**Problem Solved:** The current Ocamlc compiler, while robust, can be a bottleneck for developers requiring maximum performance or working with very large codebases. This leads to longer development cycles and potential performance limitations in the final application. CodeFlow addresses this by offering an alternative, optimized C++ compilation backend that enhances speed and efficiency.
## 2. TECH STACK
- **Frontend:** React (Next.js App Router)
- **Styling:** Tailwind CSS
- **Backend Framework:** Node.js (within Next.js API routes)
- **Database ORM:** Drizzle ORM (PostgreSQL compatible)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (or Clerk for simpler integration)
- **UI Components:** shadcn/ui
- **State Management:** Zustand or Jotai (for global state), React Context API (for local/themed state)
- **Form Handling:** React Hook Form
- **Code Editor (for input):** Monaco Editor (or similar lightweight alternative if Monaco is too heavy)
- **Deployment:** Vercel or similar PaaS
## 3. DATABASE SCHEMA
We will use PostgreSQL with Drizzle ORM.
```typescript
// schema.ts (using Drizzle syntax)
import { pgTable, serial, varchar, text, timestamp, integer, boolean, pgEnum } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// Enum for subscription tiers
export const subscriptionTierEnum = pgEnum('subscription_tier', ['free', 'pro', 'enterprise']);
// Users Table
export const users = pgTable('users', {
id: varchar('id', { length: 255 }).primaryKey(), // From auth provider (e.g., clerk, nextauth)
email: varchar('email', { length: 255 }).notNull().unique(),
name: varchar('name', { length: 255 }),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
subscriptionTier: subscriptionTierEnum('subscription_tier').default('free'),
isActive: boolean('is_active').default(true),
});
export const usersRelations = relations(users, ({ many }) => ({
projects: many(projects),
}));
// Projects Table
export const projects = pgTable('projects', {
id: serial('id').primaryKey(),
userId: varchar('user_id', { length: 255 }).notNull().references(() => users.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 255 }).notNull(),
description: text('description'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const projectsRelations = relations(projects, ({ one, many }) => ({
user: one(users, {
fields: [projects.userId],
references: [users.id],
}),
files: many(files),
}));
// Files Table (for OCaml source code)
export const files = pgTable('files', {
id: serial('id').primaryKey(),
projectId: integer('project_id').notNull().references(() => projects.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 255 }).notNull(),
content: text('content').notNull(), // OCaml source code
language: varchar('language', { length: 50 }).default('ocaml'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const filesRelations = relations(files, ({ one }) => ({
project: one(projects, {
fields: [files.projectId],
references: [projects.id],
}),
}));
// Compilation Jobs Table
export const compilationJobs = pgTable('compilation_jobs', {
id: serial('id').primaryKey(),
fileId: integer('file_id').notNull().references(() => files.id, { onDelete: 'cascade' }),
userId: varchar('user_id', { length: 255 }).notNull().references(() => users.id, { onDelete: 'cascade' }),
projectId: integer('project_id').notNull().references(() => projects.id, { onDelete: 'cascade' }),
status: pgEnum('status', ['pending', 'compiling', 'completed', 'failed']),
compilerFlags: text('compiler_flags'), // e.g., "-optimize-level=3"
createdAt: timestamp('created_at').defaultNow(),
completedAt: timestamp('completed_at'),
output: text('output'), // C++ code or error messages
durationMs: integer('duration_ms'),
});
export const compilationJobsRelations = relations(compilationJobs, ({ one }) => ({
file: one(files, {
fields: [compilationJobs.fileId],
references: [files.id],
}),
user: one(users, {
fields: [compilationJobs.userId],
references: [users.id],
}),
project: one(projects, {
fields: [compilationJobs.projectId],
references: [projects.id],
}),
}));
```
## 4. CORE FEATURES & USER FLOW
**1. User Authentication:**
- **Flow:** User visits the landing page -> Clicks 'Sign Up'/'Log In' -> Redirected to authentication provider (e.g., Google, GitHub via NextAuth.js) -> Authenticated user is redirected to the dashboard.
- **Details:** Implement email/password (if needed) and OAuth providers. Protect all routes except landing page and auth pages.
**2. Project Management:**
- **Flow:** User logs in -> Sees a dashboard with existing projects or an empty state -> Clicks 'New Project' -> Enters project name and description -> Project is created and user is redirected to the project's file view.
- **Details:** Users can create, view, update, and delete projects. Each project encapsulates OCaml files.
**3. OCaml File Handling:**
- **Flow:** User navigates to a project -> Clicks 'New File' -> Enters filename (e.g., `primes.ml`) -> Opens a code editor (Monaco) -> User writes/pastes OCaml code -> User saves the file.
- **Details:** Allow creating new files, uploading existing `.ml` files, editing files in the browser. Store file content in the `files` table.
**4. C++ Backend Compilation:**
- **Flow:** User is viewing an OCaml file within a project -> Clicks 'Compile with C++ Backend' -> User can optionally specify compiler flags (e.g., optimization levels) -> Backend initiates a compilation job (`compilation_jobs` table, status='pending') -> A worker process picks up the job, compiles the OCaml code using the C++ backend (`ocamlc -cpp ...`), updates job status to 'compiling' -> Upon completion, status becomes 'completed' and output (C++ code or error message) is saved to the `output` field. If failed, status is 'failed'. -> User is notified of completion/failure and can view the output.
- **Details:** The core compilation logic will simulate or integrate with an Ocamlc version that supports a C++ backend. For MVP, this might involve calling a server-side script that performs the compilation. Define standard flags and allow custom inputs.
**5. View Compilation Output:**
- **Flow:** After compilation, user clicks 'View Output' on a completed job -> A modal or dedicated view displays the generated C++ code or any error messages from the compilation process.
- **Details:** Render the C++ code in a syntax-highlighted block. Display errors clearly.
## 5. API & DATA FETCHING
- **API Routes (Next.js App Router):**
- `POST /api/auth/*`: Handled by NextAuth.js.
- `GET /api/projects`: Fetch user's projects.
- `POST /api/projects`: Create a new project.
- `GET /api/projects/[projectId]`: Fetch a specific project.
- `PUT /api/projects/[projectId]`: Update a project.
- `DELETE /api/projects/[projectId]`: Delete a project.
- `GET /api/projects/[projectId]/files`: Fetch files for a project.
- `POST /api/projects/[projectId]/files`: Create a new file.
- `GET /api/files/[fileId]`: Fetch a specific file's content.
- `PUT /api/files/[fileId]`: Update a file's content.
- `POST /api/files/[fileId]/compile`: Initiate a compilation job.
- `GET /api/compilation-jobs/[jobId]`: Fetch compilation job status and output.
- `GET /api/compilation-jobs`: Fetch recent jobs for the user/project.
- **Data Fetching:**
- Use Server Components for initial data loading where possible (projects, file lists).
- Use Client Components with `fetch` or libraries like SWR/React Query for dynamic data (compilation status, form submissions, real-time updates).
- Pass data from API routes to components via props or context.
- Ensure proper error handling and loading states for all data fetching operations.
## 6. COMPONENT BREAKDOWN (Next.js App Router Structure)
- **`app/`**
- **`layout.tsx`**: Root layout (Provider wrappers, global CSS, Navbar/Footer).
- **`page.tsx`**: Landing Page (Marketing content, CTA).
- **`dashboard/`**
- **`layout.tsx`**: Dashboard layout (Sidebar, main content area).
- **`page.tsx`**: Project List View (Displays user's projects, 'New Project' button).
- **`projects/[projectId]/`**
- **`layout.tsx`**: Project-specific layout.
- **`page.tsx`**: File List View for the project (Displays OCaml files, 'New File' button).
- **`files/[fileId]/`**
- **`page.tsx`**: File Editor View (Monaco Editor for OCaml code, 'Compile' button).
- **`components/`**: `CodeEditor`, `FileSaveButton`, `CompileSettingsModal`.
- **`jobs/[jobId]/`**
- **`page.tsx`**: Compilation Job Detail View (Status, output, logs).
- **`settings/`**
- **`page.tsx`**: User Settings (Profile, Subscription details).
- **`(auth)/`** (if using NextAuth.js with separate routes)
- **`signin/page.tsx`**
- **`signup/page.tsx`**
- **`components/` (Shared UI Components)**
- `Navbar`: Top navigation bar.
- `Sidebar`: Navigation within the dashboard.
- `ProjectCard`: Display individual project summaries.
- `FileItem`: Display individual file names in a list.
- `Button`: Customizable buttons (using shadcn/ui).
- `Input`: Form inputs (using shadcn/ui).
- `Card`: Generic content cards (using shadcn/ui).
- `DataTable`: For displaying lists of projects, files, jobs.
- `LoadingSpinner`: Global and component-level loading indicators.
- `Alert`: For displaying messages and errors.
- `Tooltip`: For providing contextual information.
- **`lib/`**: Utility functions, API clients, Drizzle config.
- **`hooks/`**: Custom React hooks.
- **`styles/`**: Global CSS, Tailwind configuration.
- **State Management:**
- **Global State (Zustand/Jotai):** User authentication status, global UI settings.
- **Project/File State:** Manage within `projects/[projectId]` and `files/[fileId]` client components.
- **API Data State:** Managed via SWR/React Query or simple `useState` + `useEffect` for fetching.
## 7. UI/UX DESIGN & VISUAL IDENTITY
- **Design Style:** Modern, Clean, Developer-Focused.
- **Color Palette:**
- **Primary:** `#4F46E5` (Indigo-500) - For primary actions, links.
- **Secondary:** `#6366F1` (Indigo-600) - Accents, highlights.
- **Background:** `#111827` (Dark Slate-900) - Main background for a dark theme feel.
- **Card/Surface:** `#1F2937` (Slate-800) - For cards, modals, sidebars.
- **Text (Primary):** `#E5E7EB` (Text-white-100)
- **Text (Secondary):** `#9CA3AF` (Gray-400)
- **Accent/Success:** `#10B981` (Green-500)
- **Warning/Error:** `#EF4444` (Red-500)
- **Typography:**
- **Headings:** Inter (Variable font) - Bold, Semibold.
- **Body:** Inter (Variable font) - Regular.
- **Code:** Fira Code or Source Code Pro - Monospaced for readability.
- **Layout:**
- Sidebar navigation on the left.
- Main content area to the right.
- Use cards and clear visual hierarchy.
- Ample whitespace.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows appropriately. Ensure code editor is usable on medium to large screens primarily.
- **Visual Elements:** Subtle gradients on primary buttons, clean icons (e.g., fromlucide-react), minimal use of borders, focus on content.
## 8. SAMPLE/MOCK DATA
**1. User (Authenticated):**
```json
{
"id": "cl_mockuser123",
"email": "dev@example.com",
"name": "Alex Dev",
"subscriptionTier": "pro"
}
```
**2. Projects (User Dashboard):**
```json
[
{
"id": 1,
"userId": "cl_mockuser123",
"name": "Prime Calculator",
"description": "Ocamlc C++ backend example.",
"createdAt": "2024-07-28T10:00:00Z"
},
{
"id": 2,
"userId": "cl_mockuser123",
"name": "Web Scraper",
"description": "Data extraction tool.",
"createdAt": "2024-07-27T15:30:00Z"
}
]
```
**3. Files (Project View):**
```json
[
{
"id": 101,
"projectId": 1,
"name": "primes.ml",
"language": "ocaml",
"createdAt": "2024-07-28T10:05:00Z"
},
{
"id": 102,
"projectId": 1,
"name": "utils.ml",
"language": "ocaml",
"createdAt": "2024-07-28T10:10:00Z"
}
]
```
**4. OCaml Code (primes.ml Content):**
```ocaml
module List = struct
let rec filter p = function
| [] -> []
| x :: l -> if p x then x :: filter p l else filter p l
let rec init i last f = if i > last then [] else f i :: init (i+1) last f
end
let primes n =
let rec sieve candidates = match candidates with
| [] -> []
| p :: ps -> p :: sieve (List.filter (fun n -> n mod p <> 0) ps)
in sieve (List.init 2 n (fun i -> i))
let main ~limit =
let result = primes limit in
Printf.printf "Primes up to %d: %s\n" limit (String.concat ", " (List.map string_of_int result));;
main (int_of_string Sys.argv.(1))
```
**5. Compilation Job (Pending):**
```json
{
"id": 501,
"fileId": 101,
"userId": "cl_mockuser123",
"projectId": 1,
"status": "pending",
"compilerFlags": "-optimize-level=3",
"createdAt": "2024-07-28T11:00:00Z"
}
```
**6. Compilation Job (Completed with C++ Output):**
```json
{
"id": 502,
"fileId": 101,
"userId": "cl_mockuser123",
"projectId": 1,
"status": "completed",
"compilerFlags": "-optimize-level=3",
"createdAt": "2024-07-28T11:05:00Z",
"completedAt": "2024-07-28T11:05:30Z",
"durationMs": 30000,
"output": "#ifndef limit\n#error \"Parameter limit missing\"\n#include <stop_after_error> \n#endif\n\ntemplate <typename...> struct Cons;\ntemplate <int tag, typename...> struct Cons_;\n\ntemplate <int n> struct I {\n static constexpr int tag = 1000;\n static constexpr bool nonzero = ((n) != (0));\n static constexpr int val = n;\n};\n\nstruct EXCEPTION { };\n\ntemplate <typename f0_, typename f1_> struct Cons<f0_, f1_>{\n static constexpr int tag = 0;\n static constexpr bool nonzero = true;\n static constexpr int val = -1;\n // ... rest of generated C++ code ...\n};\n\n// ... main function translated to C++ ...\n"
}
```
**7. Compilation Job (Failed):**
```json
{
"id": 503,
"fileId": 101,
"userId": "cl_mockuser123",
"projectId": 1,
"status": "failed",
"createdAt": "2024-07-28T11:10:00Z",
"completedAt": "2024-07-28T11:10:15Z",
"durationMs": 15000,
"output": "Error: Undefined identifier 'Printf' on line 15.\nError: Syntax error."
}
```
## 9. ANIMATIONS
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js `Layout Router` features or libraries like `Framer Motion` for more sophisticated transitions (e.g., slide-in for sidebar, fade for content blocks).
- **Button Hovers:** Slight scale-up or background color change on hover for interactive elements.
- **Loading States:** Use skeleton loaders or spinners (e.g., `react-lds-ring` or shadcn/ui's primitives) for data fetching and compilation processes. Provide clear visual feedback that an operation is in progress.
- **Form Submissions:** Animate submit buttons to a loading state (e.g., spinner inside the button) and provide success/error confirmations.
- **Element Transitions:** Smooth transitions for showing/hiding elements (e.g., modals, dropdowns) using Tailwind CSS transitions.
## 10. EDGE CASES & VALIDATIONS
- **Authentication:** Redirect unauthenticated users to login. Handle expired sessions gracefully.
- **Authorization:** Ensure users can only access and modify their own projects and files.
- **Empty States:** Provide clear UI messages and CTAs for when there are no projects, no files in a project, or no compilation history.
- **Input Validation:** Validate project names, file names (disallow invalid characters), and potentially OCaml code syntax before attempting compilation (client-side and server-side).
- **Compilation Errors:** Clearly display Ocamlc C++ backend errors to the user. Handle cases where the C++ backend might not be available or fails unexpectedly.
- **Large Files/Projects:** Implement mechanisms to handle potentially large OCaml source files and generated C++ code (e.g., streaming, background processing for compilation, clear indications of processing time).
- **Rate Limiting:** Implement rate limiting on API endpoints, especially the compilation endpoint, to prevent abuse and manage server load. Tiered limits based on subscription level.
- **File Type Handling:** Ensure only `.ml` files are processed for OCaml compilation.
- **Dependency Management:** (Future Consideration) How to handle OCaml projects with external dependencies. For MVP, focus on single-file compilation.
## 11. TURKISH TRANSLATIONS (Key UI Text)
- **App Title:** CodeFlow
- **Sign Up:** Kaydol
- **Log In:** Giriş Yap
- **Dashboard:** Kontrol Paneli
- **New Project:** Yeni Proje
- **Project Name:** Proje Adı
- **Project Description:** Proje Açıklaması
- **Create Project:** Proje Oluştur
- **My Projects:** Projelerim
- **New File:** Yeni Dosya
- **File Name:** Dosya Adı
- **Save File:** Dosyayı Kaydet
- **Compile:** Derle
- **Compilation Settings:** Derleme Ayarları
- **Compiler Flags:** Derleyici Bayrakları
- **View Output:** Çıktıyı Görüntüle
- **Compilation Output:** Derleme Çıktısı
- **Job Status:** Görev Durumu
- **Pending:** Bekliyor
- **Compiling:** Derleniyor
- **Completed:** Tamamlandı
- **Failed:** Başarısız Oldu
- **Details:** Detaylar
- **Settings:** Ayarlar
- **Profile:** Profil
- **Subscription:** Abonelik
- **Upgrade Plan:** Plan Yükselt
- **Loading...:** Yükleniyor...
- **Error:** Hata
- **Success:** Başarılı
- **Are you sure?** Emin misin?
- **Delete Project:** Projeyi Sil
- **Are you sure you want to delete this project?** Bu projeyi silmek istediğinizden emin misiniz?
- **No projects yet.** Henüz proje yok.
- **Create your first project!** İlk projenizi oluşturun!
- **No files in this project.** Bu projede dosya yok.
- **Add a file to get started.** Başlamak için bir dosya ekleyin.
- **No compilation history.** Derleme geçmişi yok.