import { createReadStream } from "node:fs"; import { cp, stat } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import react from "@vitejs/plugin-react"; import { defineConfig, type Plugin } from "vite"; const appRoot = fileURLToPath(new URL(".", import.meta.url)); const pdfjsRoot = path.join(appRoot, "node_modules/pdfjs-dist"); const pdfjsAssetDirs = ["cmaps", "iccs", "standard_fonts", "wasm"]; function pdfjsAssetsPlugin(): Plugin { let outDir = path.join(appRoot, "dist"); function contentType(filePath: string) { if (filePath.endsWith(".wasm")) return "application/wasm"; if (filePath.endsWith(".mjs")) return "text/javascript"; if (filePath.endsWith(".bcmap")) return "application/octet-stream"; if (filePath.endsWith(".icc")) return "application/vnd.iccprofile"; if (filePath.endsWith(".ttf")) return "font/ttf"; if (filePath.endsWith(".pfb")) return "application/octet-stream"; return "application/octet-stream"; } return { name: "readabook-pdfjs-assets", configResolved(config) { outDir = path.resolve(config.root, config.build.outDir); }, configureServer(server) { server.middlewares.use("/pdfjs", async (request, response, next) => { try { const requestPath = new URL(request.url ?? "", "http://localhost").pathname; const relativePath = decodeURIComponent(requestPath) .replace(/^\/+/, "") .replace(/^pdfjs\/+/, ""); const assetPath = path.resolve(pdfjsRoot, relativePath); if (!assetPath.startsWith(pdfjsRoot)) { next(); return; } const asset = await stat(assetPath); if (!asset.isFile()) { next(); return; } response.setHeader("Content-Type", contentType(assetPath)); createReadStream(assetPath).pipe(response); } catch { next(); } }); }, async writeBundle() { await Promise.all( pdfjsAssetDirs.map((directory) => cp(path.join(pdfjsRoot, directory), path.join(outDir, "pdfjs", directory), { recursive: true, force: true }) ) ); } }; } export default defineConfig({ plugins: [react(), pdfjsAssetsPlugin()], server: { port: 5173, proxy: { "/auth": "http://127.0.0.1:3000", "/admin": "http://127.0.0.1:3000", "/books": "http://127.0.0.1:3000", "/series": "http://127.0.0.1:3000", "/progress": "http://127.0.0.1:3000", "/healthz": "http://127.0.0.1:3000" } } });