import { type Express } from "express"; import { createServer as createViteServer, createLogger } from "vite"; import { type Server } from "http"; import viteConfig from "../vite.config"; import fs from "fs"; import path from "path"; import { nanoid } from "nanoid"; import { storage } from "./storage"; const viteLogger = createLogger(); function escapeHtml(str: string): string { return str.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } function ogImageUrl(coverImage: string, baseUrl: string): string { if (!coverImage) return ""; let imgPath = coverImage; if (imgPath.endsWith(".webp")) { imgPath = imgPath.replace(/\.webp$/, ".jpg"); } return imgPath.startsWith("http") ? imgPath : `${baseUrl}${imgPath}`; } function stripExistingMeta(html: string): string { html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); return html; } export async function setupVite(server: Server, app: Express) { const serverOptions = { middlewareMode: true, hmr: { server, path: "/vite-hmr" }, allowedHosts: true as const, }; const vite = await createViteServer({ ...viteConfig, configFile: false, customLogger: { ...viteLogger, error: (msg, options) => { viteLogger.error(msg, options); process.exit(1); }, }, server: serverOptions, appType: "custom", }); app.use(vite.middlewares); app.use("/{*path}", async (req, res, next) => { const url = req.originalUrl; const canonicalBase = "https://folx.tv"; try { const clientTemplate = path.resolve( import.meta.dirname, "..", "client", "index.html", ); let template = await fs.promises.readFile(clientTemplate, "utf-8"); template = template.replace( `src="/src/main.tsx"`, `src="/src/main.tsx?v=${nanoid()}"`, ); const articleMatch = url.match(/^\/article\/([^?#]+)/); if (articleMatch) { try { const slug = decodeURIComponent(articleMatch[1]); const article = await storage.getArticleBySlug(slug); if (article) { const articleUrl = `${canonicalBase}/article/${article.slug}`; const imageUrl = ogImageUrl(article.coverImage || "", canonicalBase); const finalImage = imageUrl || `${canonicalBase}/og-image.jpg`; template = stripExistingMeta(template); const ogTags = [ ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, `