From fbe2f927da203c019edb675f115508202ec471be Mon Sep 17 00:00:00 2001 From: Espen Hovlandsdal Date: Thu, 12 Sep 2024 16:10:34 -0700 Subject: [PATCH] refactor: apply favicon middleware early --- .../cli/server/vite/plugin-sanity-favicons.ts | 58 +++++++++---------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/packages/sanity/src/_internal/cli/server/vite/plugin-sanity-favicons.ts b/packages/sanity/src/_internal/cli/server/vite/plugin-sanity-favicons.ts index ef8667001d9..1d542573638 100644 --- a/packages/sanity/src/_internal/cli/server/vite/plugin-sanity-favicons.ts +++ b/packages/sanity/src/_internal/cli/server/vite/plugin-sanity-favicons.ts @@ -58,41 +58,39 @@ export function sanityFaviconsPlugin({ const webManifest = JSON.stringify(generateWebManifest(staticUrlPath), null, 2) const webManifestPath = `${staticUrlPath}/manifest.webmanifest` - return () => { - viteDevServer.middlewares.use(async (req, res, next) => { - if (req.url?.endsWith(webManifestPath)) { - res.writeHead(200, 'OK', {'content-type': 'application/manifest+json'}) - res.write(webManifest) - res.end() - return - } + viteDevServer.middlewares.use(async (req, res, next) => { + if (req.url?.endsWith(webManifestPath)) { + res.writeHead(200, 'OK', {'content-type': 'application/manifest+json'}) + res.write(webManifest) + res.end() + return + } - const parsedUrl = - ((req as any)._parsedUrl as URL) || new URL(req.url || '/', 'http://localhost:3333') + const parsedUrl = + ((req as any)._parsedUrl as URL) || new URL(req.url || '/', 'http://localhost:3333') - const pathName = parsedUrl.pathname || '' - const fileName = path.basename(pathName || '') - const icons = await getFavicons() - const isIconRequest = - pathName.startsWith('/favicon.ico') || - (icons.includes(fileName) && pathName.includes(staticUrlPath)) + const pathName = parsedUrl.pathname || '' + const fileName = path.basename(pathName || '') + const icons = await getFavicons() + const isIconRequest = + pathName.startsWith('/favicon.ico') || + (icons.includes(fileName) && pathName.includes(staticUrlPath)) - if (!isIconRequest) { - next() - return - } + if (!isIconRequest) { + next() + return + } - const faviconPath = - fileName === 'favicon.ico' && (await hasCustomFavicon()) - ? path.join(customFaviconsPath, 'favicon.ico') - : path.join(defaultFaviconsPath, fileName) + const faviconPath = + fileName === 'favicon.ico' && (await hasCustomFavicon()) + ? path.join(customFaviconsPath, 'favicon.ico') + : path.join(defaultFaviconsPath, fileName) - const mimeType = mimeTypes[path.extname(fileName)] || 'application/octet-stream' - res.writeHead(200, 'OK', {'content-type': mimeType}) - res.write(await fs.readFile(faviconPath)) - res.end() - }) - } + const mimeType = mimeTypes[path.extname(fileName)] || 'application/octet-stream' + res.writeHead(200, 'OK', {'content-type': mimeType}) + res.write(await fs.readFile(faviconPath)) + res.end() + }) }, } }