1 import express, { IRouter, RequestHandler } from "express"
2 import fs from "fs"
3 import path from "path"
4 import type { InlineConfig, ViteDevServer } from "vite"
5
6 import { BundlerOptions } from "../types"
7 import { getViteConfig } from "../utils/config"
8
9 const router = express.Router()
10
11 function findTemplateFilePath(
12 reqPath: string,
13 root: string
14 ): string | undefined {
15 if (reqPath.endsWith(".html")) {
16 const pathToTest = path.join(root, reqPath)
17 if (fs.existsSync(pathToTest)) {
18 return pathToTest
19 }
20 }
21
22 const basePath = reqPath.slice(0, reqPath.lastIndexOf("/"))
23 const dirs = basePath.split("/")
24
25 while (dirs.length > 0) {
26 const pathToTest = path.join(root, ...dirs, "index.html")
27 if (fs.existsSync(pathToTest)) {
28 return pathToTest
29 }
30 dirs.pop()
31 }
32
33 return undefined
34 }
35
36 async function injectViteMiddleware(
37 router: express.Router,
38 middleware: RequestHandler
39 ) {
40 router.use((req, res, next) => {
41 // Block Vite's launch-editor endpoint (GHSA-v6wh-96g9-6wx3). It's registered
42 // unconditionally by Vite's dev server and only powers the "open in editor"
43 // overlay action, which the admin dashboard doesn't rely on. Match
44 // case-insensitively since Vite's connect router does too.
45 if (req.path.toLowerCase().startsWith("/__open-in-editor")) {
46 res.status(403).end()
47 return
48 }
49 req.path.endsWith(".html") ? next() : middleware(req, res, next)
50 })
51 }
52
53 async function injectHtmlMiddleware(
54 router: express.Router,
55 server: ViteDevServer
56 ) {
57 router.use(async (req, res, next) => {
58 if (req.method !== "GET") {
59 return next()
60 }
61
62 const templateFilePath = findTemplateFilePath(req.path, server.config.root)
63 if (!templateFilePath) {
64 return next()
65 }
66
67 const template = fs.readFileSync(templateFilePath, "utf8")
68 const html = await server.transformIndexHtml(
69 templateFilePath,
70 template,
71 req.originalUrl
72 )
73
74 res.send(html)
75 })
76 }
77
78 export async function develop(options: BundlerOptions): Promise<IRouter> {
79 const vite = await import("vite")
80
81 try {
82 const viteConfig = await getViteConfig(options)
83
84 const developConfig: InlineConfig = {
85 mode: "development",
86 logLevel: "error",
87 appType: "spa",
88 server: {
89 middlewareMode: true,
90 },
91 }
92
93 const mergedConfig = vite.mergeConfig(viteConfig, developConfig)
94 const server = await vite.createServer(mergedConfig)
95
96 await injectViteMiddleware(router, server.middlewares)
97 await injectHtmlMiddleware(router, server)
98 } catch (error) {
99 console.error(error)
100 throw new Error(
101 "Failed to start admin development server. See error above."
102 )
103 }
104
105 return router
106 }