<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microservices Live Dev Environment</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts: Inter & JetBrains Mono -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- Lucide Icons -->
<script src="https://unpkg.com/lucide@latest"></script>
<!-- Lenis Scroll -->
<script src="https://unpkg.com/lenis@1.0.45/dist/lenis.min.js"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
background: '#0a0a0a',
surface: '#171717',
border: '#262626',
primary: '#3b82f6',
'primary-hover': '#2563eb',
success: '#10b981',
warning: '#f59e0b',
danger: '#ef4444',
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
boxShadow: {
glow: '0 0 20px rgba(59, 130, 246, 0.15)',
}
}
}
}
</script>
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #0a0a0a;
color: #e5e5e5;
overflow-x: hidden;
}
/* Grain Noise Overlay */
.bg-noise {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none;
opacity: 0.03;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
z-index: 0;
}
/* Mesh Gradient Background */
.mesh-gradient {
position: absolute;
top: 0; left: 0; width: 100%; height: 100%;
background: radial-gradient(circle at 15% 50%, rgba(56, 189, 248, 0.08) 0%, transparent 25%),
radial-gradient(circle at 85% 30%, rgba(236, 72, 153, 0.08) 0%, transparent 25%);
z-index: -1;
pointer-events: none;
}
/* Glassmorphism */
.glass {
background: rgba(23, 23, 23, 0.6);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255,255,255,0.08);
}
.glass-dark {
background: rgba(10, 10, 10, 0.7);
backdrop-filter: blur(16px);
border: 1px solid rgba(255,255,255,0.05);
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #0a0a0a;
}
::-webkit-scrollbar-thumb {
background: #333;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #444;
}
/* Smooth scroll (Lenis) */
html.lenis {
height: auto;
}
.lenis.lenis-smooth {
scroll-behavior: auto !important;
}
.lenis.lenis-stopped {
overflow: hidden;
}
/* Text Utilities */
.text-muted { color: #a1a1aa; }
.text-primary { color: #3b82f6; }
.border-muted { border-color: #262626; }
/* Badge variants */
.badge {
display: inline-flex;
align-items: center;
padding: 0.125rem 0.5rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 500;
border: 1px solid currentColor;
}
.badge.success { color: #10b981; background: rgba(16, 185, 129, 0.1); }
.badge.stopped { color: #6b7280; background: rgba(107, 114, 128, 0.1); }
.badge.running { color: #3b82f6; background: rgba(59, 130, 246, 0.1); }
.badge.rebuilding { color: #f59e0b; background: rgba(245, 158, 11, 0.1); }
/* Log viewer */
.log-line {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
line-height: 1.5;
padding: 2px 4px;
border-bottom: 1px solid rgba(255,255,255,0.02);
}
.log-ts { color: #6b7280; margin-right: 8px; }
.log-info { color: #e5e5e5; }
.log-warn { color: #fbbf24; }
.log-error { color: #f87171; }
.log-service { color: #60a5fa; margin-right: 4px; }
/* Canvas for traffic chart */
#traffic-chart {
width: 100%;
height: 180px;
border-radius: 0.5rem;
background: rgba(0,0,0,0.2);
}
/* Custom button base */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
white-space: nowrap;
border-radius: 0.375rem;
font-size: 0.875rem;
font-weight: 500;
transition: all 150ms;
cursor: pointer;
border: 1px solid transparent;
outline: none;
padding: 0.375rem 0.75rem;
height: 2rem;
}
.btn:focus-visible { ring: 2px solid #3b82f6; ring-offset: 2px; }
.btn-primary {
background: white;
color: black;
}
.btn-primary:hover { background: #e5e5e5; }
.btn-secondary {
background: #27272a;
color: #e5e5e5;
border: 1px solid #3f3f46;
}
.btn-secondary:hover { background: #3f3f46; }
.btn-ghost {
background: transparent;
color: #e5e5e5;
}
.btn-ghost:hover { background: rgba(255,255,255,0.05); }
.btn-icon { padding: 0.375rem; }
.btn-sm { height: 1.75rem; padding: 0.25rem 0.5rem; font-size: 0.75rem; }
.btn-block { width: 100%; }
/* Service Card Hover */
.service-card:hover .service-actions {
opacity: 1;
}
/* Tooltip */
[data-tooltip] {
position: relative;
}
[data-tooltip]:hover::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 4px 8px;
background: #000;
color: #fff;
font-size: 12px;
border-radius: 4px;
white-space: nowrap;
margin-bottom: 4px;
z-index: 50;
}
</style>
</head>
<body>
<!-- Effects -->
<div class="bg-noise"></div>
<div class="mesh-gradient"></div>
<canvas id="three-canvas" class="fixed top-0 left-0 w-full h-full pointer-events-none z-0"></canvas>
<!-- App Container -->
<div id="app" class="relative z-10 flex h-screen overflow-hidden">
<!-- Sidebar -->
<aside class="flex flex-col w-64 border-r border-zinc-800 bg-surface/80 backdrop-blur">
<div class="flex items-center h-14 px-4 border-b border-zinc-800">
<!-- Icon: Cube -->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-primary mr-2">
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
</svg>
<span class="font-semibold text-sm tracking-tight text-white">DevEnv</span>
</div>
<nav class="flex-1 overflow-y-auto py-4">
<ul class="space-y-1 px-2">
<li>
<a href="#" data-page="dashboard" class="nav-item group flex items-center px-3 py-2 text-sm font-medium rounded-md text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors">
<i data-lucide="layout-dashboard" class="mr-3 h-4 w-4"></i>
Dashboard
</a>
</li>
<li>
<a href="#" data-page="services" class="nav-item group flex items-center px-3 py-2 text-sm font-medium rounded-md text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors">
<i data-lucide="box" class="mr-3 h-4 w-4"></i>
Services
</a>
</li>
<li>
<a href="#" data-page="mocks" class="nav-item group flex items-center px-3 py-2 text-sm font-medium rounded-md text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors">
<i data-lucide="git-branch" class="mr-3 h-4 w-4"></i>
Dependency Virtualization
</a>
</li>
<li>
<a href="#" data-page="traffic" class="nav-item group flex items-center px-3 py-2 text-sm font-medium rounded-md text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors">
<i data-lucide="activity" class="mr-3 h-4 w-4"></i>
Traffic Mirroring
</a>
</li>
<li>
<a href="#" data-page="logs" class="nav-item group flex items-center px-3 py-2 text-sm font-medium rounded-md text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors">
<i data-lucide="file-text" class="mr-3 h-4 w-4"></i>
Logs
</a>
</li>
</ul>
</nav>
<div class="p-4 border-t border-zinc-800">
<div class="flex items-center">
<div class="h-2 w-2 rounded-full bg-green-500 mr-2 animate-pulse"></div>
<span class="text-xs text-zinc-500">Environment: Development</span>
</div>
</div>
</aside>
<!-- Main Content -->
<main class="flex-1 overflow-y-auto relative">
<div id="content" class="p-8 max-w-7xl mx-auto">
<!-- Dynamic Content Injected Here -->
</div>
</main>
</div>
<script>
// ================= STATE MANAGEMENT =================
const state = {
currentPage: 'dashboard',
services: [
{
id: 'user-svc',
name: 'user-service',
language: 'node',
port: 3001,
status: 'stopped', // stopped, running, rebuilding, error
command: 'npm run dev',
env: 'NODE_ENV=development',
logs: [],
lastActivity: null
},
{
id: 'order-svc',
name: 'order-service',
language: 'node',
port: 3002,
status: 'stopped',
command: 'npm run dev',
env: 'NODE_ENV=development',
logs: [],
lastActivity: null
},
{
id: 'inventory-svc',
name: 'inventory-service',
language: 'node',
port: 3003,
status: 'stopped',
command: 'npm run dev',
env: 'NODE_ENV=development',
logs: [],
lastActivity: null
},
{
id: 'payment-svc',
name: 'payment-service',
language: 'node',
port: 3004,
status: 'stopped',
command: 'npm run dev',
env: 'NODE_ENV=development',
logs: [],
lastActivity: null
}
],
mocks: [
{
id: 'm1',
serviceId: 'order-svc',
target: 'payment-service',
method: 'POST',
path: '/api/payments',
response: '{"id":"pay_123","status":"succeeded"}',
delay: 200,
enabled: true
}
],
traffic: {
active: false,
targetServiceId: 'order-svc',
rate: 10, // reqs per second
piiMasking: true,
stats: {
sent: 0,
success: 0,
errors: 0
},
capturedRequests: [
{ method: 'GET', path: '/orders', body: null },
{ method: 'GET', path: '/orders/123', body: null },
{ method: 'POST', path: '/orders', body: '{"item":"book","qty":1}' },
{ method: 'GET', path: '/inventory', body: null },
{ method: 'POST', path: '/order/items', body: '{"productId":"p1"}' }
]
},
trafficInterval: null
};
// ================= UTILITY FUNCTIONS =================
const generateId = () => Math.random().toString(36).substr(2, 9);
const now = () => new Date().toLocaleTimeString('en-US', { hour12: false });
const addLog = (serviceId, level, message) => {
const service = state.services.find(s => s.id === serviceId);
if (service) {
const logEntry = { ts: now(), level, message, serviceId };
service.logs.push(logEntry);
// Keep only last 200 logs per service
if (service.logs.length > 200) service.logs.shift();
// Also push to global logs (for logs page)
globalLogs.unshift(logEntry);
if (globalLogs.length > 1000) globalLogs.pop();
updateLogsDOM(); // inefficient but fine for demo
}
};
const addGlobalLog = (level, message) => {
globalLogs.unshift({ ts: now(), level, message, serviceId: 'system' });
if (globalLogs.length > 1000) globalLogs.pop();
updateLogsDOM();
};
let globalLogs = [];
// ================= SERVICE CONTROLLERS =================
const startService = (serviceId) => {
const service = state.services.find(s => s.id === serviceId);
if (service.status === 'running') return;
service.status = 'running';
addLog(serviceId, 'info', `Starting ${service.name} on port ${service.port}...`);
setTimeout(() => {
addLog(serviceId, 'info', `Dependencies loaded.`);
setTimeout(() => {
addLog(serviceId, 'info', `Listening on http://localhost:${service.port}`);
addLog(serviceId, 'info', `Process ready (PID ${Math.floor(Math.random()*9000)+1000})`);
}, 800);
}, 600);
};
const stopService = (serviceId) => {
const service = state.services.find(s => s.id === serviceId);
if (service.status === 'stopped') return;
service.status = 'stopped';
addLog(serviceId, 'warn', `Received SIGTERM, shutting down gracefully...`);
setTimeout(() => {
addLog(serviceId, 'info', `Service stopped.`);
}, 800);
};
const hotReload = (serviceId) => {
const service = state.services.find(s => s.id === serviceId);
if (service.status !== 'running') return;
service.status = 'rebuilding';
addLog(serviceId, 'info', `File change detected. Triggering hot reload...`);
// Simulate rebuild
setTimeout(() => {
addLog(serviceId, 'info', `Compiling modules...`);
setTimeout(() => {
addLog(serviceId, 'info', `Rebuild successful. Restarting runtime...`);
service.status = 'running';
setTimeout(() => {
addLog(serviceId, 'info', `Service ready.`);
}, 800);
}, 1000);
}, 500);
};
// ================= MOCK HANDLING =================
const mockEnabledFor = (serviceId, target, path) => {
return state.mocks.find(m =>
m.serviceId === serviceId &&
m.target === target &&
m.path === path &&
m.enabled
);
};
const handleRequest = (serviceId, method, path, body = null) => {
const service = state.services.find(s => s.id === serviceId);
if (!service) return;
// Determine if this is an internal call to another service
// For simplicity, we assume pattern: /{service-name}/...
// But our mocks are defined by target and path.
// We'll check mocks: if mock exists for this service and matches path
const mock = state.mocks.find(m => m.serviceId === serviceId && m.path === path && m.enabled);
if (mock) {
addLog(serviceId, 'info', `Outgoing ${method} ${path} (to ${mock.target}) => MOCKED (${mock.delay}ms)`);
setTimeout(() => {
addLog(serviceId, 'info', `Received mock response from ${mock.target}: ${mock.response}`);
}, mock.delay);
return;
}
// Normal internal routing simulation (if service is running)
// Extract target from path? For demo, we just log generic
addLog(serviceId, 'info', `Outgoing ${method} ${path}`);
// Simulate network latency (random)
const latency = Math.floor(Math.random() * 200) + 50;
setTimeout(() => {
// Determine success/failure randomly
const success = Math.random() > 0.1;
if (success) {
addLog(serviceId, 'info', `Received response from ${path.split('/')[1] || 'unknown'}: 200 OK`);
} else {
addLog(serviceId, 'error', `Request failed: timeout or error`);
}
}, latency);
};
// ================= TRAFFIC REPLAY =================
const startTrafficReplay = () => {
if (state.traffic.active) return;
state.traffic.active = true;
state.traffic.stats = { sent: 0, success: 0, errors: 0 };
addGlobalLog('info', `Traffic replay started on ${state.traffic.targetServiceId} at ${state.traffic.rate} rps`);
const intervalMs = 1000 / state.traffic.rate;
const targetSvc = state.traffic.targetServiceId;
state.trafficInterval = setInterval(() => {
// Pick random request from captured set
const req = state.traffic.capturedRequests[Math.floor(Math.random() * state.traffic.capturedRequests.length)];
state.traffic.stats.sent++;
// Simulate request handling
const method = req.method;
const path = req.path;
const body = req.body;
// If there is a mock for this path, it will be handled
// But we also want to simulate errors occasionally
const shouldError = Math.random() < 0.05; // 5% error rate
if (shouldError) {
state.traffic.stats.errors++;
} else {
state.traffic.stats.success++;
}
// Trigger request through service
// We'll log directly to the service's logs and global logs
addLog(targetSvc, 'info', `Incoming ${method} ${path} (mirrored traffic)`);
// Simulate processing inside service which might make outgoing calls
// For simplicity, we call handleRequest directly which will log outgoing and response
handleRequest(targetSvc, method, path, body);
// Update chart
updateTrafficChart();
}, intervalMs);
};
const stopTrafficReplay = () => {
if (!state.traffic.active) return;
state.traffic.active = false;
clearInterval(state.trafficInterval);
addGlobalLog('info', `Traffic replay stopped. Total sent: ${state.traffic.stats.sent}`);
};
// ================= CHARTING =================
let trafficChartCtx = null;
let trafficChartData = new Array(50).fill(0);
function initTrafficChart() {
const canvas = document.getElementById('traffic-chart');
trafficChartCtx = canvas.getContext('2d');
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
}
function resizeCanvas() {
const canvas = document.getElementById('traffic-chart');
canvas.width = canvas.offsetWidth * 2; // retina
canvas.height = canvas.offsetHeight * 2;
trafficChartCtx.scale(2,2);
}
function updateTrafficChart() {
if (!trafficChartCtx) return;
const w = trafficChartCtx.canvas.width / 2;
const h = trafficChartCtx.canvas.height / 2;
trafficChartData.shift();
trafficChartData.push(state.traffic.stats.sent % 100); // use modulo for demo?
// Actually show recent requests per interval
// but we want a moving window. We'll just feed current rate
const currentRate = state.traffic.active ? state.traffic.rate * (Math.random()*0.5+0.75) : 0;
trafficChartData.shift();
trafficChartData.push(currentRate);
// Clear
trafficChartCtx.clearRect(0,0,w,h);
// Draw grid
trafficChartCtx.strokeStyle = 'rgba(255,255,255,0.05)';
trafficChartCtx.lineWidth = 1;
for(let i=0; i<5; i++) {
const y = (h/4)*i;
trafficChartCtx.beginPath();
trafficChartCtx.moveTo(0, y);
trafficChartCtx.lineTo(w, y);
trafficChartCtx.stroke();
}
// Draw line
trafficChartCtx.strokeStyle = '#3b82f6';
trafficChartCtx.lineWidth = 2;
trafficChartCtx.beginPath();
const step = w / (trafficChartData.length-1);
trafficChartData.forEach((val, i) => {
const x = i * step;
const y = h - (val / 50) * h; // scale max 50
if (i===0) trafficChartCtx.moveTo(x, y);
else trafficChartCtx.lineTo(x, y);
});
trafficChartCtx.stroke();
// Fill area
trafficChartCtx.lineTo(w, h);
trafficChartCtx.lineTo(0, h);
trafficChartCtx.fillStyle = 'rgba(59,130,246,0.1)';
trafficChartCtx.fill();
}
// ================= RENDERING =================
// Global logs array used by all pages
let globalLogs = [];
// Icons re-render helper
const refreshIcons = () => {
if (window.lucide) window.lucide.createIcons();
};
// Render Dashboard
const renderDashboard = () => {
const runningCount = state.services.filter(s => s.status === 'running').length;
const totalRequests = state.traffic.stats.sent;
const activeMocks = state.mocks.filter(m => m.enabled).length;
const html = `
<div class="space-y-6">
<div class="flex justify-between items-end">
<div>
<h1 class="text-2xl font-bold tracking-tight text-white">System Overview</h1>
<p class="text-muted text-sm">Real-time monitoring of your microservices development environment.</p>
</div>
<div class="flex items-center space-x-2 text-sm text-muted">
<span>${new Date().toLocaleDateString()}</span>
<span>•</span>
<span>Dev Cluster</span>
</div>
</div>
<!-- Stats Cards -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
${renderCard('Services', runningCount + '/' + state.services.length, 'flex items-center text-muted', (runningCount===state.services.length?'text-success':'text-warning'))}
${renderCard('Active Mocks', activeMocks, 'flex items-center text-muted', '')}
${renderCard('Mirrored Requests', totalRequests.toLocaleString(), 'flex items-center text-muted', '')}
${renderCard('System Status', 'Nominal', 'flex items-center text-muted', 'text-success')}
</div>
<!-- Main Visual: 3D Globe + Recent Activity -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 h-80">
<!-- 3D Container -->
<div class="lg:col-span-2 glass rounded-xl overflow-hidden relative">
<div id="globe-container" class="absolute inset-0"></div>
<div class="absolute bottom-4 left-4 bg-black/30 backdrop-blur rounded px-3 py-1 text-xs text-zinc-300 border border-white/10">
Interactive Globe · Drag to rotate
</div>
</div>
<!-- Recent Activity Feed -->
<div class="glass rounded-xl flex flex-col">
<div class="p-4 border-b border-zinc-800 flex justify-between items-center">
<h3 class="font-medium text-sm">Recent Activity</h3>
<a href="#" data-page="logs" class="text-xs text-primary hover:underline">View all</a>
</div>
<div class="flex-1 overflow-y-auto p-4 space-y-4">
${globalLogs.slice(0, 10).map(log => renderLogLine(log)).join('')}
</div>
</div>
</div>
<!-- Quick Actions -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="glass p-4 rounded-xl border border-zinc-800/50 hover:border-primary/50 transition-colors group cursor-pointer" data-page="services">
<div class="flex items-center mb-2">
<i data-lucide="play-circle" class="h-5 w-5 text-primary mr-2"></i>
<h4 class="font-medium text-sm">Start All Services</h4>
</div>
<p class="text-xs text-muted">Boot up all microservices with one click.</p>
</div>
<div class="glass p-4 rounded-xl border border-zinc-800/50 hover:border-primary/50 transition-colors group cursor-pointer" data-page="mocks">
<div class="flex items-center mb-2">
<i data-lucide="git-branch" class="h-5 w-5 text-primary mr-2"></i>
<h4 class="font-medium text-sm">Configure Mocks</h4>
</div>
<p class="text-xs text-muted">Define virtualized dependencies for isolated development.</p>
</div>
<div class="glass p-4 rounded-xl border border-zinc-800/50 hover:border-primary/50 transition-colors group cursor-pointer" data-page="traffic">
<div class="flex items-center mb-2">
<i data-lucide="activity" class="h-5 w-5 text-primary mr-2"></i>
<h4 class="font-medium text-sm">Replay Traffic</h4>
</div>
<p class="text-xs text-muted">Mirror production traffic safely to test your changes.</p>
</div>
</div>
</div>
`;
return html;
};
// Render Card helper
function renderCard(title, value, extraClasses = '', valueClass = '') {
return `
<div class="glass p-4 rounded-xl border border-zinc-800/50">
<div class="text-sm font-medium text-muted mb-1">${title}</div>
<div class="text-2xl font-bold text-white ${valueClass}">${value}</div>
<div class="${extraClasses} mt-2 text-xs">
${title === 'System Status' ?
'<span class="flex items-center"><span class="h-2 w-2 rounded-full bg-green-500 mr-1"></span>All systems operational</span>' : ''}
</div>
</div>
`;
}
// Render Services Page
const renderServices = () => {
const html = `
<div class="space-y-6">
<div class="flex justify-between items-center">
<div>
<h1 class="text-2xl font-bold tracking-tight text-white">Services</h1>
<p class="text-muted text-sm">Manage and monitor your local microservices.</p>
</div>
<button onclick="startAllServices()" class="btn btn-primary">
<i data-lucide="play" class="h-4 w-4 mr-2"></i> Start All
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
${state.services.map(svc => `
<div class="service-card glass rounded-xl p-5 border shadow-lg transition-all hover:border-primary/30">
<div class="flex justify-between items-start mb-3">
<div class="flex items-center">
<div class="h-10 w-10 rounded-lg bg-zinc-800 flex items-center justify-center mr-3 border border-zinc-700">
<i data-lucide="box" class="h-5 w-5 text-zinc-400"></i>
</div>
<div>
<h3 class="font-medium text-white">${svc.name}</h3>
<div class="text-xs text-muted">Port ${svc.port} · ${svc.language}</div>
</div>
</div>
<span class="badge ${svc.status}">${svc.status}</span>
</div>
<div class="mb-4">
<div class="text-xs font-mono text-zinc-500 bg-black/30 p-2 rounded mb-2 overflow-x-auto">
${svc.command}
</div>
<div class="text-xs text-muted">ENV: ${svc.env}</div>
</div>
<div class="flex items-center space-x-2 overflow-x-auto pb-2">
${svc.status === 'running'
? `<button onclick="stopService('${svc.id}')" class="btn btn-secondary btn-sm">
<i data-lucide="square" class="h-3 w-3"></i>
Stop</button>
<button onclick="hotReload('${svc.id}')" class="btn btn-secondary btn-sm">
<i data-lucide="refresh-cw" class="h-3 w-3"></i>
Hot Reload</button>`
: `<button onclick="startService('${svc.id}')" class="btn btn-primary btn-sm">
<i data-lucide="play" class="h-3 w-3"></i>
Start</button>`
}
<button class="btn btn-ghost btn-sm" data-tooltip="Live Terminal">
<i data-lucide="terminal" class="h-3 w-3"></i>
</button>
</div>
<!-- Mini Log Tail -->
<div class="mt-4 h-24 overflow-y-auto bg-black/40 border border-zinc-800/50 rounded p-2 text-xs font-mono custom-scrollbar">
${svc.logs.slice(-5).reverse().map(l => renderLogLine(l)).join('')}
</div>
</div>
`).join('')}
</div>
</div>
`;
return html;
};
// Render Mocks Page
const renderMocks = () => {
const html = `
<div class="space-y-6">
<div class="flex justify-between items-center">
<div>
<h1 class="text-2xl font-bold tracking-tight text-white">Dependency Virtualization</h1>
<p class="text-muted text-sm">Define mocks to simulate downstream services without hitting real endpoints.</p>
</div>
<button onclick="addMockModal()" class="btn btn-primary">
<i data-lucide="plus" class="h-4 w-4 mr-2"></i> Add Mock
</button>
</div>
<div class="glass rounded-xl border border-zinc-800 overflow-hidden">
<table class="w-full text-sm text-left">
<thead class="bg-zinc-900/50 text-zinc-400">
<tr>
<th class="px-4 py-3 font-medium">Source Service</th>
<th class="px-4 py-3 font-medium">Target</th>
<th class="px-4 py-3 font-medium">Route</th>
<th class="px-4 py-3 font-medium">Response (JSON)</th>
<th class="px-4 py-3 font-medium">Delay</th>
<th class="px-4 py-3 font-medium">Status</th>
<th class="px-4 py-3 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-800">
${state.mocks.map(m => {
const source = state.services.find(s => s.id === m.serviceId);
return `
<tr class="hover:bg-zinc-800/30 transition-colors">
<td class="px-4 py-3">
<span class="font-mono text-primary">${source ? source.name : m.serviceId}</span>
</td>
<td class="px-4 py-3">
<span class="text-white">${m.target}</span>
</td>
<td class="px-4 py-3">
<span class="font-mono text-zinc-300">${m.method} ${m.path}</span>
</td>
<td class="px-4 py-3 max-w-xs truncate">
<code class="text-xs bg-black/30 px-1 py-0.5 rounded text-zinc-300 truncate block">${m.response}</code>
</td>
<td class="px-4 py-3">
<span class="text-zinc-400">${m.delay}ms</span>
</td>
<td class="px-4 py-3">
<button onclick="toggleMock('${m.id}')" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${m.enabled ? 'bg-primary' : 'bg-zinc-700'}">
<span aria-hidden="true" class="translate-x-0 inline-block h-4 w-4 transform rounded-full bg-white transition duration-200 ease-in-out ${m.enabled ? 'translate-x-4' : 'translate-x-0'}"></span>
</button>
</td>
<td class="px-4 py-3 text-right space-x-1">
<button onclick="editMock('${m.id}')" class="btn btn-ghost btn-icon">
<i data-lucide="pencil" class="h-3.5 w-3.5"></i>
</button>
<button onclick="deleteMock('${m.id}')" class="btn btn-ghost btn-icon text-danger">
<i data-lucide="trash" class="h-3.5 w-3.5"></i>
</button>
</td>
</tr>
`}).join('')}
</tbody>
</table>
</div>
<div class="glass p-4 rounded-xl border border-zinc-800">
<h3 class="font-medium text-sm mb-2">How it works</h3>
<ul class="list-disc list-inside text-sm text-muted space-y-1">
<li>When a service makes an HTTP request that matches a configured mock, the request is intercepted and the defined response is returned after the specified delay.</li>
<li>This allows you to develop against stable, predictable downstream behavior without starting those services.</li>
<li>Mocks can be toggled on/off instantly.</li>
</ul>
</div>
</div>
`;
return html;
};
// Render Traffic Page
const renderTraffic = () => {
const servicesOptions = state.services.map(s =>
`<option value="${s.id}" ${state.traffic.targetServiceId === s.id ? 'selected' : ''}>${s.name}</option>`
).join('');
const html = `
<div class="space-y-6">
<div>
<h1 class="text-2xl font-bold tracking-tight text-white">Safe Traffic Mirroring</h1>
<p class="text-muted text-sm">Replay captured production traffic to your local environment for realistic testing.</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Controls -->
<div class="lg:col-span-1 space-y-4">
<div class="glass p-5 rounded-xl border border-zinc-800">
<h3 class="font-medium text-sm mb-4">Replay Configuration</h3>
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-zinc-400 mb-1">Target Service</label>
<select id="traffic-target" class="w-full bg-zinc-900 border border-zinc-700 rounded px-3 py-2 text-sm text-white focus:border-primary focus:outline-none transition-colors">
${servicesOptions}
</select>
</div>
<div>
<label class="block text-xs font-medium text-zinc-400 mb-1">Rate (requests/second)</label>
<div class="flex items-center space-x-2">
<input type="range" id="traffic-rate" min="1" max="100" value="${state.traffic.rate}" class="flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-primary">
<span id="rate-value" class="text-sm font-mono w-8 text-right">${state.traffic.rate}</span>
</div>
</div>
<div>
<div class="flex items-center justify-between mb-1">
<label class="block text-xs font-medium text-zinc-400">PII Masking</label>
<button id="pii-toggle" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${state.traffic.piiMasking ? 'bg-primary' : 'bg-zinc-700'}">
<span class="sr-only">Toggle PII Masking</span>
<span class="translate-x-0 inline-block h-4 w-4 transform rounded-full bg-white transition duration-200 ease-in-out ${state.traffic.piiMasking ? 'translate-x-4' : 'translate-x-0'}"></span>
</button>
</div>
<p class="text-xs text-muted">Redacts email addresses and sensitive fields from payloads.</p>
</div>
<div>
<label class="block text-xs font-medium text-zinc-400 mb-1">Captured Traffic</label>
<div class="bg-black/30 border border-zinc-700 rounded p-3 text-xs font-mono text-zinc-300 flex-1 min-h-[80px]">
${state.traffic.capturedRequests.length} requests ready to replay.<br>
<span class="text-zinc-500">Methods: GET, POST</span>
</div>
</div>
<div class="pt-2">
<button id="traffic-start-btn" onclick="toggleTraffic()" class="btn btn-primary w-full">
<i data-lucide="play" class="h-4 w-4 mr-2"></i> Start Replay
</button>
</div>
</div>
</div>
</div>
<!-- Stats & Chart -->
<div class="lg:col-span-2 space-y-4">
<div class="grid grid-cols-3 gap-4">
${renderStatCard('Requests Sent', state.traffic.stats.sent, 'text-primary')}
${renderStatCard('Success', state.traffic.stats.success, 'text-success')}
${renderStatCard('Errors', state.traffic.stats.errors, 'text-danger')}
</div>
<div class="glass rounded-xl p-4 border border-zinc-800">
<h3 class="text-sm font-medium mb-2">Request Rate (last 50 intervals)</h3>
<canvas id="traffic-chart"></canvas>
</div>
<div class="glass rounded-xl p-4 border border-zinc-800">
<h3 class="text-sm font-medium mb-2">Live Log Feed</h3>
<div id="traffic-live-logs" class="h-40 overflow-y-auto font-mono text-xs space-y-1">
<!-- logs will appear -->
</div>
</div>
</div>
</div>
</div>
`;
return html;
};
const renderStatCard = (title, value, colorClass = '') => `
<div class="glass rounded-xl p-4 border border-zinc-800/50">
<div class="text-xs font-medium text-muted mb-1">${title}</div>
<div class="text-2xl font-bold ${colorClass}">${value}</div>
</div>
`;
// Render Logs Page
const renderLogs = () => {
const html = `
<div class="space-y-4">
<div class="flex justify-between items-center">
<div>
<h1 class="text-2xl font-bold tracking-tight text-white">Logs</h1>
<p class="text-muted text-sm">Unified event stream from all services and the environment.</p>
</div>
<div class="flex space-x-2">
<select id="log-service-filter" class="bg-zinc-900 border border-zinc-700 rounded px-3 py-2 text-sm text-white focus:border-primary">
<option value="all">All Services</option>
${state.services.map(s => `<option value="${s.id}">${s.name}</option>`).join('')}
</select>
<button onclick="clearLogs()" class="btn btn-secondary btn-sm">Clear</button>
</div>
</div>
<div id="logs-container" class="glass rounded-xl border border-zinc-800 overflow-hidden">
${globalLogs.slice(0, 200).map(log => renderLogLine(log)).join('')}
</div>
</div>
`;
return html;
};
const renderLogLine = (log) => {
const levelClass = `log-${log.level}`;
const serviceName = log.serviceId === 'system' ? 'SYSTEM' : state.services.find(s=>s.id===log.serviceId)?.name.toUpperCase() || log.serviceId.toUpperCase();
return `
<div class="log-line flex items-start">
<span class="log-ts">[${log.ts}]</span>
${log.serviceId !== 'system' ? `<span class="log-service font-bold">[${serviceName}]</span>` : ''}
<span class="${levelClass}">${log.message}</span>
</div>
`;
};
const updateLogsDOM = () => {
const container = document.getElementById('logs-container');
if (!container) return; // not on logs page
// Re-render filtered logs? For demo, just append new ones could be more efficient but re-rendering slice okay for small.
const filterVal = document.getElementById('log-service-filter') ? document.getElementById('log-service-filter').value : 'all';
const filtered = globalLogs.filter(l => filterVal === 'all' || l.serviceId === filterVal);
container.innerHTML = filtered.slice(0, 1000).map(l => renderLogLine(l)).join('');
// Auto scroll bottom only if we are at bottom
if (container.scrollTop + container.clientHeight >= container.scrollHeight - 50) {
container.scrollTop = container.scrollHeight;
}
};
// ================= PAGE NAVIGATION =================
const navigateTo = (page) => {
state.currentPage = page;
const contentEl = document.getElementById('content');
let html = '';
switch(page) {
case 'dashboard': html = renderDashboard(); break;
case 'services': html = renderServices(); break;
case 'mocks': html = renderMocks(); break;
case 'traffic': html = renderTraffic(); break;
case 'logs': html = renderLogs(); break;
default: html = renderDashboard();
}
contentEl.innerHTML = html;
refreshIcons();
// Page-specific initializations
if (page === 'dashboard') {
// Globe is always there, but ensure it's visible
}
if (page === 'traffic') {
initTrafficChart();
// Update live logs container? We'll bind later
}
if (page === 'logs') {
updateLogsDOM();
}
};
// ================= EVENT LISTENERS =================
document.addEventListener('DOMContentLoaded', () => {
// Init Lenis
const lenis = new Lenis({
duration: 1.2,
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
direction: 'vertical',
gestureDirection: 'vertical',
smooth: true,
mouseMultiplier: 1,
smoothTouch: false,
touchMultiplier: 2,
});
function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);
// Sidebar navigation
document.querySelectorAll('.nav-item').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const page = link.getAttribute('data-page');
navigateTo(page);
// Update active state
document.querySelectorAll('.nav-item').forEach(l => {
l.classList.remove('bg-zinc-800/50', 'text-white');
l.classList.add('text-zinc-400');
});
link.classList.remove('text-zinc-400');
link.classList.add('bg-zinc-800/50', 'text-white', 'text-white'); // Ensure white
});
});
// Set initial active
document.querySelector(`.nav-item[data-page="${state.currentPage}"]`).classList.add('bg-zinc-800/50', 'text-white');
document.querySelectorAll('.nav-item').forEach(l => l.classList.add('text-zinc-400'));
// Dashboard page initial
navigateTo('dashboard');
// Start global log simulation
setInterval(() => {
// Randomly add logs to running services to simulate activity
state.services.forEach(svc => {
if (svc.status === 'running' && Math.random() > 0.7) {
const msgs = [
'GET /health 200',
'Received event from order-service',
'Cache hit for key user:123',
'Database query: SELECT * FROM users WHERE id=123',
'Processing background job',
'GC pause: 12ms',
'Publishing metrics'
];
const msg = msgs[Math.floor(Math.random() * msgs.length)];
addLog(svc.id, 'info', msg);
}
});
}, 2000);
// Global stats updates for traffic page (if visible)
setInterval(() => {
if (state.currentPage === 'traffic') {
// Update displayed stats
const sentEl = document.getElementById('stat-sent');
const successEl = document.getElementById('stat-success');
const errorEl = document.getElementById('stat-errors');
// We'll embed these IDs in renderTraffic if needed, but we are re-rendering stats via a function?
// Simpler: update directly
if (sentEl) sentEl.textContent = state.traffic.stats.sent;
if (successEl) successEl.textContent = state.traffic.stats.success;
if (errorEl) errorEl.textContent = state.traffic.stats.errors;
}
}, 500);
});
// =========================================
// 3D GLOBE (THREE.JS)
// =========================================
let scene, camera, renderer, particles, globeGroup;
const initGlobe = () => {
const canvas = document.getElementById('three-canvas');
const container = document.getElementById('globe-container') || document.body;
scene = new THREE.Scene();
// Fog for depth
scene.fog = new THREE.FogExp2(0x0a0a0a, 0.002);
camera = new THREE.PerspectiveCamera(55, container.offsetWidth / container.offsetHeight, 0.1, 1000);
camera.position.z = 250;
renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
renderer.setSize(container.offsetWidth, container.offsetHeight);
renderer.setClearColor(0x000000, 0);
// Create globe particles
const geometry = new THREE.BufferGeometry();
const particleCount = 2000;
const posArray = new Float32Array(particleCount * 3);
const radius = 80;
for(let i = 0; i < particleCount * 3; i++) {
// Random point on sphere surface
const phi = Math.acos(-1 + (2 * i) / particleCount);
const theta = Math.sqrt(particleCount * Math.PI) * phi;
const r = radius + (Math.random() - 0.5) * 0.5;
posArray[i] = r * Math.cos(theta) * Math.sin(phi);
posArray[i+1] = r * Math.sin(theta) * Math.sin(phi);
posArray[i+2] = r * Math.cos(phi);
// But above is not correct indexing; easier:
}
// Better: generate correctly
for (let i = 0; i < particleCount; i++) {
const theta = THREE.MathUtils.randFloatSpread(360);
const phi = THREE.MathUtils.randFloatSpread(360);
// Actually spherical coords
const u = Math.random();
const v = Math.random();
const theta2 = 2 * Math.PI * u;
const phi2 = Math.acos(2 * v - 1);
const x = radius * Math.sin(phi2) * Math.cos(theta2);
const y = radius * Math.sin(phi2) * Math.sin(theta2);
const z = radius * Math.cos(phi2);
posArray[i*3] = x;
posArray[i*3+1] = y;
posArray[i*3+2] = z;
}
geometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
const material = new THREE.PointsMaterial({
size: 1.2,
color: 0x3b82f6,
transparent: true,
opacity: 0.8,
blending: THREE.AdditiveBlending
});
particles = new THREE.Points(geometry, material);
globeGroup = new THREE.Group();
globeGroup.add(particles);
scene.add(globeGroup);
// Add inner sphere (dark core)
const innerGeo = new THREE.SphereGeometry(radius - 2, 32, 32);
const innerMat = new THREE.MeshBasicMaterial({ color: 0x0a0a0a });
const innerSphere = new THREE.Mesh(innerGeo, innerMat);
globeGroup.add(innerSphere);
// Ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Define mouse rotation
let mouseX = 0;
let mouseY = 0;
let targetRotationX = 0;
let targetRotationY = 0;
container.addEventListener('mousemove', (e) => {
if (!container) return;
const rect = container.getBoundingClientRect();
mouseX = ((e.clientX - rect.left) / rect.width) * 2 - 1;
mouseY = -((e.clientY - rect.top) / rect.height) * 2 + 1;
targetRotationX = mouseY * 0.5;
targetRotationY = mouseX * 0.5;
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
globeGroup.rotation.y += 0.001; // slow auto rotate
globeGroup.rotation.x += (targetRotationX - globeGroup.rotation.x) * 0.05;
globeGroup.rotation.y += (targetRotationY - globeGroup.rotation.y) * 0.05;
renderer.render(scene, camera);
}
animate();
// Resize handling
window.addEventListener('resize', () => {
if (container && container.offsetWidth && container.offsetHeight) {
camera.aspect = container.offsetWidth / container.offsetHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.offsetWidth, container.offsetHeight);
}
});
};
// Call init after a delay to ensure DOM ready
setTimeout(initGlobe, 100);
// ================= MOCK & TRAFFIC CONTROLS =================
window.startAllServices = () => {
state.services.forEach(s => {
if (s.status === 'stopped') startService(s.id);
});
};
window.toggleMock = (mockId) => {
const mock = state.mocks.find(m => m.id === mockId);
if (mock) {
mock.enabled = !mock.enabled;
// Re-render if on mocks page
if (state.currentPage === 'mocks') navigateTo('mocks');
}
};
window.deleteMock = (mockId) => {
state.mocks = state.mocks.filter(m => m.id !== mockId);
if (state.currentPage === 'mocks') navigateTo('mocks');
};
window.addMockModal = () => {
// For demo, we'll just add a default mock for the first running service or any
const targetService = state.services[0];
const newMock = {
id: generateId(),
serviceId: targetService.id,
target: 'external-api',
method: 'POST',
path: '/api/external',
response: '{"status":"ok"}',
delay: 100,
enabled: true
};
state.mocks.push(newMock);
navigateTo('mocks');
addGlobalLog('info', 'Created new mock for ' + targetService.name);
};
window.editMock = (mockId) => {
// Very simple: just toggle something for demonstration
addGlobalLog('info', 'Edit mock ' + mockId + ' (not implemented in demo)');
};
window.toggleTraffic = () => {
if (state.traffic.active) {
stopTrafficReplay();
} else {
// Update config from UI elements if present
const targetSelect = document.getElementById('traffic-target');
const rateSlider = document.getElementById('traffic-rate');
const piiToggle = document.getElementById('pii-toggle');
if (targetSelect) state.traffic.targetServiceId = targetSelect.value;
if (rateSlider) state.traffic.rate = parseInt(rateSlider.value);
if (piiToggle) state.traffic.piiMasking = piiToggle.classList.contains('bg-primary');
startTrafficReplay();
}
if (state.currentPage === 'traffic') navigateTo('traffic'); // refresh UI
};
// Listeners for slider & toggle on traffic page rendering
// We'll attach globally because after render we can query
document.addEventListener('click', (e) => {
// PII toggle
if (e.target.id === 'pii-toggle' || e.target.parentElement.id === 'pii-toggle') {
const btn = e.target.id === 'pii-toggle' ? e.target : e.target.parentElement;
const isActive = btn.classList.contains('bg-primary');
if (isActive) {
btn.classList.remove('bg-primary');
btn.classList.add('bg-zinc-700');
btn.querySelector('span').classList.remove('translate-x-4');
btn.querySelector('span').classList.add('translate-x-0');
state.traffic.piiMasking = false;
} else {
btn.classList.remove('bg-zinc-700');
btn.classList.add('bg-primary');
btn.querySelector('span').classList.remove('translate-x-0');
btn.querySelector('span').classList.add('translate-x-4');
state.traffic.piiMasking = true;
}
}
});
// Slider value update
const originalRenderTraffic = renderTraffic;
renderTraffic = () => {
const html = originalRenderTraffic();
// After insert, attach event for slider
setTimeout(() => {
const slider = document.getElementById('traffic-rate');
const display = document.getElementById('rate-value');
if (slider && display) {
slider.addEventListener('input', () => {
display.textContent = slider.value;
});
}
}, 0);
return html;
};
// ================= LOG FILTER =================
window.clearLogs = () => {
globalLogs = [];
updateLogsDOM();
};
// Watch for service filter change
document.addEventListener('change', (e) => {
if (e.target && e.target.id === 'log-service-filter') {
updateLogsDOM();
}
});
// ================= FINAL INIT =================
// Ensure icons are rendered after each page load
const originalNavigate = navigateTo;
navigateTo = (page) => {
originalNavigate(page);
setTimeout(refreshIcons, 50);
};
</script>
</body>
</html>