import fs from 'fs'; import path from 'path'; import { runBuild } from './build.js'; import { generateKundaliPdfBuffer } from '../src/pdf_kit_engine.js'; const PORT = Number(process.env.PORT) || 3000; const ROOT_DIR = process.cwd(); const SRC_DIR = path.join(ROOT_DIR, 'src'); const DIST_DIR = path.join(ROOT_DIR, 'dist'); // Set of active SSE client stream controllers for Live-Reload const sseClients = new Set(); function broadcastReload() { for (const controller of sseClients) { try { controller.enqueue(new TextEncoder().encode('data: reload\n\n')); } catch { sseClients.delete(controller); } } } // Perform initial build before starting the server console.log('⚔ Performing initial build for dev server...'); await runBuild({ isDev: true, silent: false }); // Live-reload client script injected into HTML during dev mode const LIVE_RELOAD_SNIPPET = ` `; // Start Bun Live HTTP Development Server const server = Bun.serve({ port: PORT, async fetch(req) { const url = new URL(req.url); let pathname = url.pathname; // 1. PDFKit Kundali Generation API Endpoint if (pathname === '/api/generate-pdf' && req.method === 'POST') { try { const body = await req.json(); const { data, lang } = body; if (!data) { return new Response(JSON.stringify({ error: 'Missing horoscope data payload' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const pdfBuffer = await generateKundaliPdfBuffer(data, lang || 'te'); const sanitizedName = (data.fullName || 'Jathakam').replace(/[\s\/\:\*\?\"\<\>\|]+/g, '_'); return new Response(pdfBuffer, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': `attachment; filename="${encodeURIComponent(sanitizedName)}_Kundali.pdf"`, 'Cache-Control': 'no-cache' } }); } catch (err) { console.error('āŒ [PDFKit API Error]:', err); return new Response(JSON.stringify({ error: (err && err.message) ? err.message : 'PDF Generation Failed' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } // 2. Live-Reload Server-Sent Events (SSE) Endpoint if (pathname === '/live-reload') { const stream = new ReadableStream({ start(controller) { sseClients.add(controller); controller.enqueue(new TextEncoder().encode('data: connected\n\n')); }, cancel(controller) { sseClients.delete(controller); } }); return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', 'Connection': 'keep-alive' } }); } // 3. Route root to index.html if (pathname === '/' || pathname === '') { pathname = '/index.html'; } // 4. Try dist folder first let filePath = path.join(DIST_DIR, pathname); let file = Bun.file(filePath); if (!(await file.exists())) { // Try root directory filePath = path.join(ROOT_DIR, pathname); file = Bun.file(filePath); } if (await file.exists()) { // Inject live-reload snippet into HTML files if (pathname.endsWith('.html')) { let htmlContent = await file.text(); if (!htmlContent.includes('__divya_live_reload__')) { if (htmlContent.includes('')) { htmlContent = htmlContent.replace('', `${LIVE_RELOAD_SNIPPET}\n`); } else { htmlContent += LIVE_RELOAD_SNIPPET; } } return new Response(htmlContent, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate' } }); } // Other assets (CSS, JS, Fonts, Images) return new Response(file, { headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate' } }); } return new Response('404 Not Found', { status: 404 }); } }); console.log(`\n================================================================`); console.log(`šŸš€ Divya Jyotisham Live Development Server running!`); console.log(`šŸ“” Local URL: http://localhost:${PORT}`); console.log(`šŸ“„ PDF Engine: PDFKit on Bun (Native /api/generate-pdf)`); console.log(`šŸ‘€ Watching: src/ for automatic builds & instant live reload`); console.log(`================================================================\n`); // 5. File Watcher on src/ with Debounced Rebuild & Live Reload let debounceTimer = null; let isBuilding = false; function onFileChange(eventType, filename) { if (!filename) return; // Ignore temporary files and editor artifacts if (filename.includes('~') || filename.startsWith('.') || filename.endsWith('.swp')) return; if (debounceTimer) clearTimeout(debounceTimer); debounceTimer = setTimeout(async () => { if (isBuilding) return; isBuilding = true; const startTime = Date.now(); console.log(`\nšŸ”„ [Watch] File changed: src/${filename} -> Rebuilding...`); try { const success = await runBuild({ isDev: true, silent: true }); const duration = Date.now() - startTime; if (success) { console.log(`āœ… [Watch] Rebuilt in ${duration}ms. Triggering live reload across ${sseClients.size} client(s)...`); broadcastReload(); } } catch (err) { console.error('āŒ [Watch] Rebuild error:', err); } finally { isBuilding = false; } }, 80); } try { fs.watch(SRC_DIR, { recursive: true }, onFileChange); console.log(`šŸ‘€ File watcher actively monitoring ${SRC_DIR}`); } catch (err) { console.error('Failed to start recursive file watcher on src/:', err); }