PROJECT: Universal CMS Platform with AI Integration
Executive Summary
Build a next-generation Content Management System that combines multi-site deployment, AI-powered assistance, component libraries, blog publishing, and developer tools into a unified Cloudflare-first platform. This is a production-grade system designed to compete with WordPress, Webflow, and modern site builders while being infinitely more developer-friendly and AI-native.
SYSTEM ARCHITECTURE OVERVIEW
┌─────────────────────────────────────────────────────────────────┐
│ FRONTEND APPLICATIONS │
├─────────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │
│ │ Admin Panel │ │ Site Builder │ │ Agent Studio │ │
│ │ (Dashboard) │ │ (WYSIWYG) │ │ (AI Workflows) │ │
│ └──────────────┘ └──────────────┘ └────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Code Editor (MDX + CodeMirror 6) │ │
│ └──────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ API LAYER │
├─────────────────────────────────────────────────────────────────┤
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ tRPC API (Type-safe, end-to-end) │ │
│ │ • Sites • Pages • Components • Media • Users │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ AI Assistant Core (Cloudflare Vibe SDK) │ │
│ │ • OpenRouter Multi-Model • Claude API Premium │ │
│ │ • Ollama Local Dev • Context Management │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Agent Engine (Visual Workflow Builder) │ │
│ │ • Custom Tools • Testing • Deployment │ │
│ └──────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ CLOUDFLARE INFRASTRUCTURE │
├─────────────────────────────────────────────────────────────────┤
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ ┌─────────────────┐ │
│ │ D1 │ │ R2 │ │ Vectorize │ │ Durable Objects │ │
│ │ (SQLite) │ │ (Storage)│ │ (Vectors) │ │ (Real-time) │ │
│ └──────────┘ └──────────┘ └───────────┘ └─────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Deployment Engine (Pages + Workers) │ │
│ └──────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
PHASE 0: ARCHITECTURE & TYPE SYSTEM (DO THIS FIRST)
Critical: Build Foundation Before Any Code
Create comprehensive documentation and type system:
1. /docs/ARCHITECTURE.md - System Design Document
markdown
# System Architecture
## Overview
- Multi-tenant CMS architecture
- Edge-first deployment model
- Type-safe API with tRPC
- AI-native from ground up
## Data Model
- Sites → Pages → Sections → Components
- Users → Teams → Permissions
- Assets → Media Library → CDN
- Agents → Workflows → Tools
## Infrastructure
- Cloudflare D1: Relational data (sites, pages, users)
- Cloudflare R2: Object storage (images, files, backups)
- Vectorize: Semantic search & AI embeddings
- Durable Objects: Real-time collaboration & state
- Workers: API & edge compute
- Pages: Static site deployment
## Security Model
- Row-level security in D1
- JWT-based authentication
- API key management
- Rate limiting per tenant
## Performance Targets
- Admin panel: <200ms API response
- Site builder: <50ms UI interactions
- Deployment: <30 seconds to live
- AI responses: <2s first token
2. /types/index.ts - Complete Type System
typescript
// ============================================================================
// CORE ENTITIES
// ============================================================================
export interface Site {
id: string;
tenantId: string;
name: string;
domain: string | null;
customDomain: string | null;
status: SiteStatus;
deploymentId: string | null;
settings: SiteSettings;
createdAt: Date;
updatedAt: Date;
}
export type SiteStatus =
| 'draft'
| 'published'
| 'archived'
| 'deploying';
export interface SiteSettings {
theme: ThemeConfig;
seo: SEOConfig;
analytics: AnalyticsConfig;
ai: AIConfig;
}
export interface Page {
id: string;
siteId: string;
slug: string;
title: string;
type: PageType;
sections: Section[];
seo: PageSEO;
status: PageStatus;
publishedAt: Date | null;
createdAt: Date;
updatedAt: Date;
}
export type PageType =
| 'homepage'
| 'product'
| 'blog-post'
| 'blog-index'
| 'about'
| 'contact'
| 'custom';
export type PageStatus =
| 'draft'
| 'scheduled'
| 'published'
| 'archived';
export interface Section {
id: string;
pageId: string;
type: SectionType;
order: number;
content: SectionContent;
layout: LayoutConfig;
styling: StylingConfig;
}
export type SectionType =
| 'navigation'
| 'hero'
| 'content'
| 'grid'
| 'cards'
| 'form'
| 'footer'
| 'custom-component';
export interface SectionContent {
// Slate.js editor state for rich text
richText?: Descendant[];
// Or structured data for specific components
data?: Record<string, any>;
}
// ============================================================================
// BLOG SYSTEM
// ============================================================================
export interface BlogPost {
id: string;
siteId: string;
slug: string;
title: string;
excerpt: string;
content: Descendant[]; // Slate/MDX content
featuredImage: MediaAsset | null;
author: Author;
categories: Category[];
tags: Tag[];
seo: PostSEO;
status: PostStatus;
scheduledAt: Date | null;
publishedAt: Date | null;
createdAt: Date;
updatedAt: Date;
}
export type PostStatus =
| 'draft'
| 'in-review'
| 'scheduled'
| 'published';
export interface Category {
id: string;
siteId: string;
name: string;
slug: string;
description: string | null;
parent: string | null;
}
export interface Tag {
id: string;
siteId: string;
name: string;
slug: string;
}
// ============================================================================
// COMPONENT LIBRARY
// ============================================================================
export interface Component {
id: string;
name: string;
description: string;
category: ComponentCategory;
framework: Framework[];
code: ComponentCode;
props: ComponentProps;
preview: string; // URL to preview image
usage: number; // Usage count
rating: number;
tags: string[];
author: Author;
version: string;
createdAt: Date;
updatedAt: Date;
}
export type ComponentCategory =
| 'layout'
| 'navigation'
| 'forms'
| 'content'
| 'interactive'
| 'ai';
export type Framework =
| 'react'
| 'vue'
| 'svelte'
| 'vanilla'
| 'webcomponent';
export interface ComponentCode {
react?: string;
vue?: string;
svelte?: string;
vanilla?: string;
styles?: string;
dependencies?: string[];
}
// ============================================================================
// AI SYSTEM
// ============================================================================
export interface AIAssistant {
id: string;
tenantId: string;
name: string;
type: AssistantType;
config: AIConfig;
context: AssistantContext;
status: 'active' | 'paused';
createdAt: Date;
}
export type AssistantType =
| 'chat'
| 'content-writer'
| 'code-generator'
| 'seo-optimizer'
| 'customer-support'
| 'custom';
export interface AIConfig {
provider: AIProvider;
model: string;
temperature: number;
maxTokens: number;
systemPrompt: string;
tools: AITool[];
}
export type AIProvider =
| 'openrouter'
| 'claude'
| 'cloudflare-vibe'
| 'ollama';
export interface AITool {
name: string;
description: string;
parameters: Record<string, any>;
handler: string; // Function name to call
}
export interface Agent {
id: string;
tenantId: string;
name: string;
description: string;
workflow: AgentWorkflow;
triggers: AgentTrigger[];
status: 'active' | 'paused';
runs: number;
lastRun: Date | null;
}
export interface AgentWorkflow {
nodes: WorkflowNode[];
edges: WorkflowEdge[];
}
export interface WorkflowNode {
id: string;
type: NodeType;
position: { x: number; y: number };
data: NodeData;
}
export type NodeType =
| 'trigger'
| 'ai-action'
| 'api-call'
| 'condition'
| 'transform'
| 'output';
// ============================================================================
// MEDIA LIBRARY
// ============================================================================
export interface MediaAsset {
id: string;
tenantId: string;
siteId: string | null;
filename: string;
originalFilename: string;
mimeType: string;
size: number; // bytes
width: number | null;
height: number | null;
url: string; // R2 URL
cdnUrl: string; // Cloudflare CDN URL
alt: string | null;
tags: string[];
folder: string | null;
uploadedBy: string; // userId
createdAt: Date;
}
// ============================================================================
// USER & TENANT SYSTEM
// ============================================================================
export interface Tenant {
id: string;
name: string;
plan: PricingPlan;
sites: Site[];
users: TenantUser[];
settings: TenantSettings;
usage: UsageStats;
createdAt: Date;
}
export type PricingPlan =
| 'free'
| 'starter'
| 'professional'
| 'enterprise';
export interface TenantUser {
userId: string;
role: UserRole;
permissions: Permission[];
joinedAt: Date;
}
export type UserRole =
| 'owner'
| 'admin'
| 'editor'
| 'contributor'
| 'viewer';
export interface User {
id: string;
email: string;
name: string;
avatar: string | null;
tenants: string[]; // tenantIds
preferences: UserPreferences;
createdAt: Date;
}
// ============================================================================
// DEPLOYMENT SYSTEM
// ============================================================================
export interface Deployment {
id: string;
siteId: string;
status: DeploymentStatus;
environment: 'production' | 'preview' | 'staging';
url: string;
commitHash: string | null;
buildLog: string[];
startedAt: Date;
completedAt: Date | null;
duration: number | null; // seconds
}
export type DeploymentStatus =
| 'queued'
| 'building'
| 'deploying'
| 'success'
| 'failed'
| 'cancelled';
// ============================================================================
// THEME & STYLING
// ============================================================================
export interface ThemeConfig {
colors: ColorPalette;
typography: Typography;
spacing: SpacingScale;
breakpoints: Breakpoints;
customCSS: string | null;
}
export interface ColorPalette {
primary: string;
secondary: string;
accent: string;
background: string;
text: string;
// ... full color system
}
// ============================================================================
// SEO & ANALYTICS
// ============================================================================
export interface SEOConfig {
siteName: string;
siteDescription: string;
defaultImage: string;
twitterHandle: string | null;
analyticsId: string | null;
searchConsoleId: string | null;
}
export interface PageSEO {
title: string;
description: string;
keywords: string[];
ogImage: string | null;
canonical: string | null;
noindex: boolean;
nofollow: boolean;
}
// Add 100+ more types as needed...
3. /docs/DATABASE_SCHEMA.md - D1 Database Design
sql
-- Complete SQL schema for D1
-- Multi-tenant architecture with row-level security
-- TENANTS & USERS
CREATE TABLE tenants (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
plan TEXT NOT NULL,
settings JSON,
usage JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
avatar TEXT,
preferences JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE tenant_users (
tenant_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL,
permissions JSON,
joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (tenant_id, user_id),
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- SITES & PAGES
CREATE TABLE sites (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
domain TEXT,
custom_domain TEXT,
status TEXT NOT NULL,
deployment_id TEXT,
settings JSON NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (tenant_id) REFERENCES tenants(id)
);
CREATE TABLE pages (
id TEXT PRIMARY KEY,
site_id TEXT NOT NULL,
slug TEXT NOT NULL,
title TEXT NOT NULL,
type TEXT NOT NULL,
sections JSON NOT NULL,
seo JSON NOT NULL,
status TEXT NOT NULL,
published_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(site_id, slug),
FOREIGN KEY (site_id) REFERENCES sites(id)
);
-- BLOG SYSTEM
CREATE TABLE blog_posts (
id TEXT PRIMARY KEY,
site_id TEXT NOT NULL,
slug TEXT NOT NULL,
title TEXT NOT NULL,
excerpt TEXT,
content JSON NOT NULL,
featured_image TEXT,
author_id TEXT NOT NULL,
seo JSON NOT NULL,
status TEXT NOT NULL,
scheduled_at DATETIME,
published_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(site_id, slug),
FOREIGN KEY (site_id) REFERENCES sites(id),
FOREIGN KEY (author_id) REFERENCES users(id)
);
CREATE TABLE categories (
id TEXT PRIMARY KEY,
site_id TEXT NOT NULL,
name TEXT NOT NULL,
slug TEXT NOT NULL,
description TEXT,
parent_id TEXT,
UNIQUE(site_id, slug),
FOREIGN KEY (site_id) REFERENCES sites(id)
);
CREATE TABLE tags (
id TEXT PRIMARY KEY,
site_id TEXT NOT NULL,
name TEXT NOT NULL,
slug TEXT NOT NULL,
UNIQUE(site_id, slug),
FOREIGN KEY (site_id) REFERENCES sites(id)
);
CREATE TABLE post_categories (
post_id TEXT NOT NULL,
category_id TEXT NOT NULL,
PRIMARY KEY (post_id, category_id)
);
CREATE TABLE post_tags (
post_id TEXT NOT NULL,
tag_id TEXT NOT NULL,
PRIMARY KEY (post_id, tag_id)
);
-- COMPONENT LIBRARY
CREATE TABLE components (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
frameworks JSON NOT NULL,
code JSON NOT NULL,
props JSON,
preview TEXT,
usage INTEGER DEFAULT 0,
rating REAL DEFAULT 0,
tags JSON,
author_id TEXT NOT NULL,
version TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- AI SYSTEM
CREATE TABLE ai_assistants (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
config JSON NOT NULL,
context JSON,
status TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (tenant_id) REFERENCES tenants(id)
);
CREATE TABLE agents (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
workflow JSON NOT NULL,
triggers JSON NOT NULL,
status TEXT NOT NULL,
runs INTEGER DEFAULT 0,
last_run DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (tenant_id) REFERENCES tenants(id)
);
CREATE TABLE agent_runs (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL,
status TEXT NOT NULL,
input JSON,
output JSON,
error TEXT,
started_at DATETIME,
completed_at DATETIME,
duration INTEGER,
FOREIGN KEY (agent_id) REFERENCES agents(id)
);
-- MEDIA LIBRARY
CREATE TABLE media_assets (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
site_id TEXT,
filename TEXT NOT NULL,
original_filename TEXT NOT NULL,
mime_type TEXT NOT NULL,
size INTEGER NOT NULL,
width INTEGER,
height INTEGER,
url TEXT NOT NULL,
cdn_url TEXT NOT NULL,
alt TEXT,
tags JSON,
folder TEXT,
uploaded_by TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
FOREIGN KEY (site_id) REFERENCES sites(id),
FOREIGN KEY (uploaded_by) REFERENCES users(id)
);
-- DEPLOYMENTS
CREATE TABLE deployments (
id TEXT PRIMARY KEY,
site_id TEXT NOT NULL,
status TEXT NOT NULL,
environment TEXT NOT NULL,
url TEXT NOT NULL,
commit_hash TEXT,
build_log JSON,
started_at DATETIME,
completed_at DATETIME,
duration INTEGER,
FOREIGN KEY (site_id) REFERENCES sites(id)
);
-- Indexes for performance
CREATE INDEX idx_sites_tenant ON sites(tenant_id);
CREATE INDEX idx_pages_site ON pages(site_id);
CREATE INDEX idx_posts_site ON blog_posts(site_id);
CREATE INDEX idx_posts_status ON blog_posts(status);
CREATE INDEX idx_components_category ON components(category);
CREATE INDEX idx_media_tenant ON media_assets(tenant_id);
4. /docs/TESTING_PLAN.md - Comprehensive Test Strategy
markdown
# Testing Strategy
## Test Coverage Target: >85%
## Unit Tests (Vitest)
- All utility functions
- Type guards and validators
- Data transformations
- Business logic
## Integration Tests (React Testing Library)
- API routes (tRPC procedures)
- Component interactions
- State management
- Editor functionality
## E2E Tests (Playwright)
- Complete user workflows
- Multi-page scenarios
- Authentication flows
- Deployment process
## Performance Tests
- API response times
- Bundle size limits
- Lighthouse scores
- Load testing
## Test Organization
tests/ ├── unit/ │ ├── utils/ │ ├── validators/ │ └── helpers/ ├── integration/ │ ├── api/ │ ├── components/ │ └── stores/ ├── e2e/ │ ├── auth.spec.ts │ ├── site-creation.spec.ts │ ├── blog-publishing.spec.ts │ ├── ai-assistant.spec.ts │ └── deployment.spec.ts └── performance/ ├── api-benchmarks.ts └── bundle-analysis.ts
PROJECT STRUCTURE
cms-platform/
├── docs/
│ ├── ARCHITECTURE.md
│ ├── DATABASE_SCHEMA.md
│ ├── TESTING_PLAN.md
│ ├── API_SPEC.md
│ ├── DEPLOYMENT.md
│ └── CONTRIBUTING.md
│
├── types/
│ └── index.ts # ALL type definitions
│
├── packages/ # Monorepo structure
│ ├── shared/ # Shared utilities
│ │ ├── types/
│ │ ├── utils/
│ │ └── constants/
│ │
│ ├── admin/ # Admin dashboard app
│ │ ├── src/
│ │ │ ├── components/
│ │ │ ├── pages/
│ │ │ ├── store/
│ │ │ └── hooks/
│ │ └── package.json
│ │
│ ├── site-builder/ # Visual site builder
│ │ ├── src/
│ │ │ ├── canvas/
│ │ │ ├── editor/
│ │ │ ├── sidebar/
│ │ │ └── preview/
│ │ └── package.json
│ │
│ ├── agent-studio/ # AI agent builder
│ │ ├── src/
│ │ │ ├── workflow-builder/
│ │ │ ├── agent-editor/
│ │ │ └── testing-panel/
│ │ └── package.json
│ │
│ ├── api/ # tRPC API server
│ │ ├── src/
│ │ │ ├── routers/
│ │ │ │ ├── sites.ts
│ │ │ │ ├── pages.ts
│ │ │ │ ├── blog.ts
│ │ │ │ ├── components.ts
│ │ │ │ ├── media.ts
│ │ │ │ ├── ai.ts
│ │ │ │ └── agents.ts
│ │ │ ├── services/
│ │ │ ├── middleware/
│ │ │ └── utils/
│ │ └── wrangler.toml
│ │
│ ├── workers/ # Cloudflare Workers
│ │ ├── deployment/
│ │ ├── ai-assistant/
│ │ ├── image-optimization/
│ │ └── webhooks/
│ │
│ └── db/ # Database migrations
│ ├── migrations/
│ ├── seeds/
│ └── schema.sql
│
├── tests/
│ ├── unit/
│ ├── integration/
│ ├── e2e/
│ └── performance/
│
├── scripts/
│ ├── setup.ts
│ ├── migrate.ts
│ └── deploy.ts
│
├── .github/
│ └── workflows/
│ ├── test.yml
│ ├── deploy.yml
│ └── release.yml
│
├── package.json
├── turbo.json # Turborepo config
├── pnpm-workspace.yaml
└── README.md
TECHNOLOGY STACK
typescript
// Package versions and stack
{
"monorepo": "turborepo",
"packageManager": "pnpm",
"frontend": {
"framework": "React 18",
"language": "TypeScript 5+",
"build": "Vite",
"routing": "TanStack Router",
"ui": "Shadcn/ui + Tailwind CSS",
"forms": "React Hook Form + Zod",
"editor": {
"rich-text": "Slate.js",
"markdown": "MDX",
"code": "CodeMirror 6"
},
"drag-drop": "@dnd-kit/core",
"charts": "Recharts",
"icons": "Lucide React"
},
"backend": {
"api": "tRPC v11",
"runtime": "Cloudflare Workers",
"database": "Cloudflare D1 (SQLite)",
"storage": "Cloudflare R2",
"vectors": "Cloudflare Vectorize",
"realtime": "Durable Objects",
"queue": "Cloudflare Queues",
"cron": "Cron Triggers"
},
"ai": {
"primary": "Cloudflare Vibe SDK",
"fallback": "OpenRouter",
"premium": "Claude API Direct",
"local": "Ollama",
"embeddings": "text-embedding-3-small"
},
"state": {
"client": "Zustand",
"server": "TanStack Query (React Query)",
"cache": "tRPC client cache"
},
"testing": {
"unit": "Vitest",
"integration": "React Testing Library",
"e2e": "Playwright",
"coverage": "c8"
},
"deployment": {
"frontend": "Cloudflare Pages",
"api": "Cloudflare Workers",
"sites": "Cloudflare Pages (dynamic)"
},
"devTools": {
"linter": "ESLint + Prettier",
"typeCheck": "TypeScript strict mode",
"git-hooks": "Husky",
"commits": "Conventional Commits",
"ci-cd": "GitHub Actions"
}
}
CORE FEATURES & MODULES
Module 1: Multi-Site Management
typescript
// Key features
- Create/edit/delete sites
- Custom domain management
- SSL certificate automation
- Site cloning/templating
- Multi-environment support (prod/staging/preview)
- Rollback deployments
- Site analytics dashboard
// API endpoints (tRPC)
sites.create()
sites.list()
sites.get()
sites.update()
sites.delete()
sites.deploy()
sites.rollback()
sites.clone()
Module 2: Page Builder (Slate.js + Custom Elements)
typescript
// Key features
- Visual drag-and-drop interface
- Rich text editing with Slate
- Custom component insertion
- Responsive preview (mobile/tablet/desktop)
- Version history
- Real-time collaboration (Durable Objects)
- Template library
- Import/export pages
// Custom Slate elements
- Navigation bars
- Hero sections
- Content grids
- Card layouts
- Forms with validation
- Image galleries
- Video embeds
- Custom HTML blocks
Module 3: Blog Publishing System
typescript
// Key features
- MDX-powered blog posts
- Rich media support
- Category/tag management
- Multi-author support
- Editorial workflow (draft → review → publish)
- Scheduled publishing
- RSS feed generation
- SEO optimization
- Social media previews
- Comment system (optional)
- Newsletter integration
// API endpoints
blog.posts.create()
blog.posts.list()
blog.posts.publish()
blog.posts.schedule()
blog.categories.manage()
blog.tags.manage()
Module 4: AI Assistant (Cloudflare Vibe SDK)
typescript
// Key features
- Contextual chat interface
- Content generation (blog posts, product descriptions)
- Code generation (components, pages)
- SEO optimization suggestions
- Image alt text generation
- Accessibility audit
- Grammar/style checking
- Multi-language translation
- Custom AI tools
// Integration points
- Cloudflare Vibe SDK (primary)
- OpenRouter (multi-model fallback)
- Claude API (premium tasks)
- Ollama (local development)
// Context management
- Current site/page context
- User preferences
- Conversation history
- Site-specific knowledge base (via Vectorize)
Module 5: Agent Development Studio
typescript
// Key features
- Visual workflow builder (node-based)
- Pre-built agent templates
- Custom tool creation
- Agent testing environment
- Scheduling/triggers
- Error handling & retries
- Usage analytics
- Version control for agents
- Agent marketplace
// Agent types
- Content Writer (automated blog posts)
- SEO Optimizer (automated meta tags)
- Code Generator (component creation)
- Customer Support (FAQ automation)
- Analytics Reporter (weekly summaries)
- Social Media Publisher
- Image Optimizer
- Custom agents
// Workflow nodes
- Trigger (webhook, schedule, manual)
- AI Action (call LLM with prompt)
- API Call (external service)
- Condition (if/else logic)
- Transform (data manipulation)
- Loop (iterate over items)
- Output (save, publish, notify)
Module 6: Component Library System
typescript
// Key features
- Searchable component registry
- Multi-framework support (React, Vue, Svelte, vanilla)
- Live preview
- Copy-to-clipboard code
- Installation instructions
- Usage examples
- Props documentation
- Version history
- Community ratings/reviews
- Private team components
// Component categories
- Layout (grids, containers, sections)
- Navigation (menus, breadcrumbs, pagination)
- Forms (inputs, buttons, validation)
- Content (cards, lists, tables, galleries)
- Interactive (modals, tabs, accordions, tooltips)
- AI (chat widgets, voice interfaces, search)
- Marketing (CTAs, testimonials, pricing tables)
- E-commerce (product cards, cart, checkout)
// Component management
components.create()
components.publish()
components.version()
components.search()
components.install()
components.fork()
Module 7: Code Editor (MDX + CodeMirror)
typescript
// Key features
- Syntax highlighting (HTML, CSS, JS, MDX)
- Auto-completion with AI
- Multiple file tabs
- Split-pane view
- Live preview
- Git integration (commit, push, pull)
- File browser with search
- Find & replace
- Keyboard shortcuts
- Theme support (light/dark)
- Collaborative editing
// CodeMirror extensions
- Language support (JSX, TypeScript, CSS, HTML)
- Linting (ESLint, Stylelint)
- Auto-formatting (Prettier)
- Emmet abbreviations
- Bracket matching
- Code folding
- Mini-map
// MDX integration
- Component preview
- Frontmatter editing
- Import suggestions
Module 8: Media Library (R2 + CDN)
typescript
// Key features
- Drag-and-drop upload
- Bulk upload
- Image optimization (WebP conversion)
- Responsive images generation
- Video transcoding
- File organization (folders)
- Tagging system
- Search & filter
- Alt text management
- Usage tracking
- CDN integration
- External URL import
// Image transformations
- Resize
- Crop
- Compress
- Format conversion
- Quality adjustment
- Watermarking (optional)
// API endpoints
media.upload()
media.optimize()
media.transform()
media.search()
media.delete()
Module 9: Deployment Engine
typescript
// Key features
- One-click deployment to Cloudflare Pages
- Build pipeline with logs
- Environment variables management
- Custom build commands
- Post-deployment webhooks
- Automatic SSL
- CDN cache management
- Preview deployments
- Rollback capability
- Deployment history
// Build process
1. Trigger deployment
2. Clone site data from D1
3. Generate static HTML/CSS/JS
4. Optimize assets (images, fonts)
5. Upload to Cloudflare Pages
6. Invalidate CDN cache
7. Update DNS records
8. Health check
9. Notify user
// API endpoints
deployments.trigger()
deployments.status()
deployments.logs()
deployments.rollback()
deployments.preview()
Module 10: SEO & Analytics
typescript
// Key features
- Meta tag management
- Sitemap generation (XML)
- Robots.txt editor
- Schema.org structured data
- Open Graph tags
- Twitter cards
- Canonical URLs
- 301 redirects management
- Google Analytics integration
- Search Console integration
- Performance monitoring
- Accessibility scores
// SEO tools
- Keyword density checker
- Readability analysis
- Broken link detector
- Image alt text audit
- Page speed insights
DEVELOPMENT PHASES
Phase 1: Foundation (Weeks 1-4)
✓ Project setup (monorepo, tooling)
✓ Type system complete
✓ Database schema finalized
✓ Authentication system
✓ Basic API structure (tRPC)
✓ Admin dashboard shell
✓ CI/CD pipeline
Phase 2: Core CMS (Weeks 5-10)
✓ Site management (CRUD)
✓ Page builder with Slate.js
✓ Media library + R2 integration
✓ Template system
✓ Deployment engine (basic)
✓ Preview functionality
Phase 3: Blog System (Weeks 11-14)
✓ Blog post editor (MDX)
✓ Category/tag management
✓ Publishing workflow
✓ RSS feed generation
✓ SEO optimization
Phase 4: AI Integration (Weeks 15-20)
✓ Cloudflare Vibe SDK setup
✓ AI assistant interface
✓ Content generation tools
✓ Code generation
✓ Vectorize search
Phase 5: Agent Studio (Weeks 21-26)
✓ Visual workflow builder
✓ Agent templates
✓ Custom tool creation
✓ Testing environment
✓ Agent marketplace
Phase 6: Component Library (Weeks 27-30)
✓ Component registry
✓ Multi-framework support
✓ Documentation system
✓ Preview generation
✓ Community features
Phase 7: Advanced Features (Weeks 31-36)
✓ Code editor (CodeMirror)
✓ Real-time collaboration
✓ Advanced deployment
✓ Analytics dashboard
✓ Team management
Phase 8: Polish & Launch (Weeks 37-40)
✓ Performance optimization
✓ Security audit
✓ Documentation complete
✓ Tutorial videos
✓ Beta testing
✓ Public launch
CONSTRAINTS & BEST PRACTICES
Code Quality Standards
typescript
// Enforced by ESLint + TypeScript
✓ No 'any' types (use 'unknown' if needed)
✓ Strict null checking
✓ Explicit function return types
✓ Max function length: 50 lines
✓ Max file length: 300 lines
✓ Cyclomatic complexity: <10
✓ Test coverage: >85%
✓ No console.log in production
✓ Proper error handling everywhere
✓ Consistent naming conventions
Performance Requirements
typescript
// Monitored via Lighthouse + custom metrics
✓ Admin panel load: <1s
✓ API response time: <200ms
✓ Page builder interaction: <50ms
✓ Bundle size: <500KB (gzipped)
✓ Lighthouse score: >90
✓ Core Web Vitals: all green
✓ Database queries: <50ms
✓ Image optimization: automatic
Security Requirements
typescript
✓ JWT-based authentication
✓ Row-level security in D1
✓ Rate limiting on all APIs
✓ Input sanitization
✓ XSS prevention
✓ CSRF protection
✓ SQL injection prevention
✓ Secure headers (CSP, etc.)
✓ HTTPS only
✓ API key rotation
Accessibility Requirements
typescript
✓ WCAG 2.1 Level AA compliance
✓ Keyboard navigation throughout
✓ Screen reader support
✓ ARIA labels on interactive elements
✓ Focus management
✓ Color contrast ratios
✓ Semantic HTML
✓ Alt text for images
✓ Skip navigation links
DEPLOYMENT STRATEGY
Infrastructure Setup (Cloudflare)
bash
# Cloudflare account setup
1. Create account (if not exists)
2. Create D1 database: cms-platform-prod
3. Create R2 bucket: cms-media
4. Setup Vectorize index: cms-embeddings
5. Deploy Workers (API, deployment engine)
6. Deploy Pages (admin, site-builder, agent-studio)
7. Configure DNS records
8. Enable Cloudflare CDN
# Environment variables
CLOUDFLARE_ACCOUNT_ID=xxx
D1_DATABASE_ID=xxx
R2_BUCKET_NAME=cms-media
VECTORIZE_INDEX_ID=xxx
OPENROUTER_API_KEY=xxx
CLAUDE_API_KEY=xxx
JWT_SECRET=xxx
VIBE_SDK_KEY=xxx
Multi-Environment Strategy
typescript
// Environments
- development: Local + Ollama
- staging: Cloudflare Workers + D1 staging
- production: Cloudflare Workers + D1 prod
// Deployment flow
1. PR created → CI runs tests
2. PR merged → Deploy to staging
3. Manual approval → Deploy to production
4. Rollback available within 24h
MONITORING & OBSERVABILITY
typescript
// Metrics to track
✓ API response times (p50, p95, p99)
✓ Error rates by endpoint
✓ Database query performance
✓ Deployment success rate
✓ User signup/churn
✓ AI token usage & cost
✓ Storage usage (R2)
✓ Bandwidth usage
✓ Active sites count
✓ Average time to deploy
// Alerting
- API errors >1%
- Response time >500ms
- Deployment failures
- Database connection issues
- High cost anomalies
// Tools
- Cloudflare Analytics
- Custom Durable Objects for metrics
- Grafana dashboard (optional)
- Sentry for error tracking
EXECUTION INSTRUCTIONS FOR CLAUDE CODE
Using Multiple Terminal Agents
bash
# Agent 1: Documentation & Types
- Create all documentation files
- Build complete type system
- Write database schema
- Define API specifications
# Agent 2: Backend Infrastructure
- Setup Cloudflare Workers
- Create tRPC API routers
- Implement database layer
- Build authentication system
# Agent 3: Frontend - Admin Panel
- Setup React app with Vite
- Build dashboard components
- Implement site management
- Create media library UI
# Agent 4: Frontend - Site Builder
- Build Slate.js editor
- Create custom elements
- Implement drag-and-drop
- Add preview functionality
# Agent 5: AI Integration
- Setup Cloudflare Vibe SDK
- Build AI assistant interface
- Create agent studio
- Implement Vectorize search
# Agent 6: Testing & CI/CD
- Write unit tests
- Create integration tests
- Setup E2E tests
- Configure GitHub Actions
# Agents work in parallel, coordinating via shared types
FINAL PROMPT FOR CLAUDE CODE
Build a production-grade, multi-tenant CMS platform with the following specifications:
ARCHITECTURE-FIRST APPROACH:
1. Complete type system in /types/index.ts covering all entities
2. Full documentation in /docs/ (architecture, database, testing, API)
3. Database schema with migrations
4. Component specifications for all major features
TECHNOLOGY STACK:
- Monorepo: Turborepo + pnpm
- Frontend: React 18 + TypeScript + Vite + Shadcn/ui
- Backend: tRPC + Cloudflare Workers
- Database: Cloudflare D1 (SQLite)
- Storage: Cloudflare R2
- AI: Cloudflare Vibe SDK + OpenRouter + Claude API
- Editor: Slate.js + CodeMirror 6
- Testing: Vitest + Playwright
CORE MODULES (build in parallel):
1. Multi-site management with custom domains
2. Visual page builder (Slate.js + drag-drop)
3. Blog publishing system (MDX-powered)
4. AI assistant (Vibe SDK integration)
5. Agent development studio (visual workflow builder)
6. Component library (multi-framework support)
7. Code editor (CodeMirror with AI completion)
8. Media library (R2 + image optimization)
9. Deployment engine (Cloudflare Pages)
10. SEO & analytics tools
CONSTRAINTS:
- No 'any' types allowed
- >85% test coverage required
- <200ms API response times
- WCAG 2.1 AA compliance
- Production-ready code only
DEVELOPMENT PROCESS:
1. Phase 0: Complete documentation + types (DO FIRST)
2. Foundation: Auth, API structure, database
3. Core CMS: Sites, pages, media
4. Blog system: Posts, categories, publishing
5. AI features: Assistant, agents, search
6. Component library: Registry, multi-framework
7. Advanced: Editor, collaboration, analytics
8. Polish: Performance, security, testing
Use multiple terminal agents to work in parallel on different modules. Coordinate via shared types and documentation. Build with production quality from day one.
Create a full-stack CMS that rivals WordPress and Webflow but with AI-native features and modern edge-first architecture.