UNPKG

@strapi/strapi

Version:

An open source headless CMS solution to create and manage your own API. It provides a powerful dashboard and features to make your life easier. Databases supported: MySQL, MariaDB, PostgreSQL, SQLite

82 lines (76 loc) 3.31 kB
'use strict'; var path = require('node:path'); var fs = require('node:fs/promises'); var config = require('./config.js'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var path__default = /*#__PURE__*/_interopDefault(path); var fs__default = /*#__PURE__*/_interopDefault(fs); const watch = async (ctx)=>{ const finalConfig = await config.mergeConfigWithUserConfig(await config.resolveDevelopmentConfig(ctx), ctx); ctx.logger.debug('Vite config', finalConfig); const { createServer } = await import('vite'); const vite = await createServer(finalConfig); const viteMiddlewares = (koaCtx, next)=>{ return new Promise((resolve, reject)=>{ const prefix = ctx.basePath.replace(ctx.adminPath, '').replace(/\/+$/, ''); const originalPath = koaCtx.path; if (!koaCtx.path.startsWith(prefix)) { koaCtx.path = `${prefix}${koaCtx.path}`; } // Set cache-control headers to prevent caching issues during development restarts koaCtx.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); koaCtx.set('Pragma', 'no-cache'); koaCtx.set('Expires', '0'); koaCtx.set('Surrogate-Control', 'no-store'); vite.middlewares(koaCtx.req, koaCtx.res, (err)=>{ if (err) { reject(err); } else { if (!koaCtx.res.headersSent) { koaCtx.path = originalPath; } resolve(next()); } }); }); }; const serveAdmin = async (koaCtx, next)=>{ await next(); if (koaCtx.method !== 'HEAD' && koaCtx.method !== 'GET') { return; } if (koaCtx.body != null || koaCtx.status !== 404) { return; } const url = koaCtx.originalUrl; try { let template = await fs__default.default.readFile(path__default.default.relative(ctx.cwd, '.strapi/client/index.html'), 'utf-8'); template = await vite.transformIndexHtml(url, template); koaCtx.type = 'html'; koaCtx.body = template; } catch (error) { ctx.logger.error('Failed to serve admin panel in development mode:', error); // Don't fallback to other handlers in development mode to prevent MIME type conflicts koaCtx.status = 500; koaCtx.body = 'Admin panel temporarily unavailable during server restart'; } }; const adminRoute = `${ctx.adminPath}/:path*`; // Remove any existing admin routes to prevent conflicts during restart const existingRoutes = ctx.strapi.server.router.stack.filter((layer)=>layer.path === adminRoute); existingRoutes.forEach((route)=>{ const index = ctx.strapi.server.router.stack.indexOf(route); if (index > -1) { ctx.strapi.server.router.stack.splice(index, 1); } }); ctx.strapi.server.router.get(adminRoute, serveAdmin); ctx.strapi.server.router.use(adminRoute, viteMiddlewares); return { async close () { await vite.close(); } }; }; exports.watch = watch; //# sourceMappingURL=watch.js.map