/** * ============================================================ * SVGarden — https://www.svgarden.dev * Author : Simon-Pierre Boucher * Contact: contact@spboucher.ai * File : server.mjs * Desc : Tiny Express static server for dist/ on 127.0.0.1:4321 (+ /healthz) * ============================================================ */ import { readFileSync, existsSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import express from 'express'; import compression from 'compression'; const ROOT = path.dirname(fileURLToPath(import.meta.url)); const DIST = path.join(ROOT, 'dist'); const PORT = Number(process.env.PORT ?? 4321); const HOST = process.env.HOST ?? '127.0.0.1'; if (!existsSync(DIST)) { console.error('server.mjs: dist/ not found — run `npm run build` first.'); process.exit(1); } const buildInfoPath = path.join(DIST, 'build-info.json'); const buildInfo = existsSync(buildInfoPath) ? JSON.parse(readFileSync(buildInfoPath, 'utf8')) : { built: null, snippets: null }; const app = express(); app.disable('x-powered-by'); app.use(compression()); app.get('/healthz', (_req, res) => { res.set('Cache-Control', 'no-store'); res.json({ status: 'ok', built: buildInfo.built, snippets: buildInfo.snippets }); }); app.use( express.static(DIST, { extensions: ['html'], setHeaders(res, filePath) { if (/\.(?:js|css|woff2?|svg|png|jpe?g|webp|avif)$/.test(filePath) && /_astro[\\/]/.test(filePath)) { // Astro emits content-hashed filenames under _astro/ — safe to cache forever res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } else if (filePath.endsWith('.html') || filePath.endsWith('.json')) { res.setHeader('Cache-Control', 'no-cache'); } else { res.setHeader('Cache-Control', 'public, max-age=3600'); } }, }) ); app.use((_req, res) => { res.status(404); const notFound = path.join(DIST, '404.html'); if (existsSync(notFound)) res.sendFile(notFound); else res.type('text').send('404 — not found'); }); app.listen(PORT, HOST, () => { console.log(`SVGarden serving ${DIST} on http://${HOST}:${PORT} (${buildInfo.snippets ?? '?'} snippets, built ${buildInfo.built ?? '?'})`); });