UNPKG

@cretadoc/server

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