import express, { type Express } from "express"; import fs from "fs"; import path from "path"; import { storage } from "./storage"; function escapeHtml(str: string): string { return str.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } export function serveStatic(app: Express) { const distPath = path.resolve(__dirname, "public"); if (!fs.existsSync(distPath)) { throw new Error( `Could not find the build directory: ${distPath}, make sure to build the client first`, ); } app.use(express.static(distPath)); app.use("/{*path}", async (req, res) => { const url = req.originalUrl; const indexPath = path.resolve(distPath, "index.html"); const articleMatch = url.match(/^\/article\/([^?#]+)/); if (articleMatch) { try { const slug = decodeURIComponent(articleMatch[1]); const article = await storage.getArticleBySlug(slug); if (article) { const host = req.get("host") || "folx.tv"; const protocol = req.get("x-forwarded-proto") || "https"; const baseUrl = `${protocol}://${host}`; const articleUrl = `${baseUrl}/article/${article.slug}`; const imageUrl = article.coverImage ? (article.coverImage.startsWith("http") ? article.coverImage : `${baseUrl}${article.coverImage}`) : ""; let template = await fs.promises.readFile(indexPath, "utf-8"); const ogTags = [ ``, ``, ``, ``, imageUrl ? `` : "", ``, ``, ``, ``, imageUrl ? `` : "", `${escapeHtml(article.title)} - Folx Music Television`, ].filter(Boolean).join("\n "); template = template.replace(/]*\/>\s*/g, ""); template = template.replace(/.*?<\/title>/, ogTags); res.status(200).set({ "Content-Type": "text/html" }).end(template); return; } } catch (e) { } } res.sendFile(indexPath); }); }