@cretadoc/server
Version:
3 lines (2 loc) • 2.82 kB
JavaScript
import E from"express";import{createServer as u}from"vite";import{HTTP_STATUS_CODE as l,deepFreeze as d,isObject as O,isObjKeyExist as S}from"@cretadoc/utils";import m from"cors";import f from"helmet";import{existsSync as y}from"fs";import{join as N}from"path";const _=(r,e,t,o)=>{r instanceof Error?(console.error(r.stack),t.status(l.INTERNAL_SERVER_ERROR).send(`${r.name}: ${r.message}`)):o(r)},D=r=>(e,t,o)=>{r(e,t).catch(o)},v=r=>(e,t,o)=>{try{r==="production"?(m({origin:!1}),f()):m({origin:"*"}),o()}catch(s){o(s)}},R={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},A="localhost",g=R.DEVELOPMENT,w=3e3,C="index.html",I="/",F="/static",a={api:void 0,hmr:void 0,hostname:A,mode:g,port:w,ssr:void 0,staticDir:void 0},h={BAD_CONFIGURATION:"BAD_CONFIGURATION",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class T extends Error{constructor(e,t){super(`${e}: ${t}`),this.name="CretadocServerError"}}class c extends T{constructor(e){super(h.BAD_CONFIGURATION,e)}}const L=r=>{if(r){if(!r.path)throw new c("The static directory path is mandatory.");if(!y(r.path))throw new c(`The static directory path does not exist. Received: ${r.path}`);return{entrypoint:r.entrypoint??C,path:r.path,route:r.route??F}}},U=(r,e)=>r===!1?r:r?{port:r.port}:e==="production"?!1:void 0,x=r=>{if(r){if(!r.entrypoint)throw new c("In SSR mode, the server entrypoint is mandatory.");return{entrypoint:r.entrypoint,route:r.route??I}}},M=r=>{const e=r?.mode??a.mode;if(!r)return d(a);const t={api:r.api,hmr:U(r.hmr,e),hostname:r.hostname??a.hostname,mode:e,port:r.port??a.port,ssr:x(r.ssr),staticDir:L(r.staticDir)};return d(t)},V=(r,e)=>r.startsWith(e)?r:N(e,r),P=({entrypoint:r,path:e})=>(t,o,s)=>{try{E.static(e,{index:!1}),o.sendFile(V(r,e))}catch(n){s(n)}},$=r=>typeof r=="function",b=r=>!(!O(r)||!S(r,"render")||!$(r.render)),G=async(r,e)=>{const t=e?await e.ssrLoadModule(r):await import(r);if(!b(t))throw new T(h.INTERNAL_SERVER_ERROR,"The server entrypoint must export a render function.");return t.render},H=(r,e)=>async(t,o,s)=>{try{await(await G(r.entrypoint,e))({req:t,res:o,viteServer:e})}catch(n){e&&n instanceof Error&&e.ssrFixStacktrace(n),s(n)}},j=async r=>u({appType:"custom",server:{hmr:r,middlewareMode:!0}}),B=async({api:r,hmr:e,mode:t,ssr:o,staticDir:s})=>{const n=E();n.disable("x-powered-by");const i=t===R.DEVELOPMENT?await j(e):void 0;return n.use(v(t)),r&&n.use(r.graphqlEndpoint,D(r)),i&&n.use(i.middlewares),s&&n.use(s.route,P(s)),o&&n.use(o.route,H(o,i)),n.use(_),n},k=async r=>{const e=M(r),{hostname:t,port:o,...s}=e,n=await B(s);let i;return{config:e,start:()=>{i=n.listen(o,()=>{console.log(`[server]: Server is running at http://${t}:${o}`)})},stop:()=>{i?.close(p=>{p?console.error(p):console.log("[server]: Server is stopped.")})}}};export{k as createServer};
//# sourceMappingURL=server.mjs.map