import { serviceLocator , setStoreItem } from '@cromwell/core' ; import { readCMSConfigSync } from '@cromwell/core-backend/dist/helpers/cms-settings' ; import { getLogger } from '@cromwell/core-backend/dist/helpers/logger' ; import http from 'http' ; import httpProxy from 'http-proxy' ; import nodeCleanup from 'node-cleanup' ; import yargs from 'yargs-parser' ; import { closeAllServers , getServerPort , launchServerManager , serverAliveWatcher } from './helpers/server-manager' ; const logger = getLogger ( ) ; async function main ( ) { const args = yargs ( process . argv . slice ( 2 ) ) ; let argsPort = parseInt ( args . port + '' ) ; if ( isNaN ( argsPort ) ) argsPort = undefined ; const config = readCMSConfigSync ( ) ; setStoreItem ( 'cmsSettings' , config ) ; const port = process . env . API_PORT ?? argsPort ?? 4016 ; const proxy = await httpProxy . createProxyServer ( ) ; proxy . on ( 'error' , function ( err ) { logger . error ( err ) ; } ) ; const server = http . createServer ( ( req , res ) => { const getErrorCallback = ( message ) => ( err ) => { logger . error ( message , err ) ; res . writeHead ( 500 , { 'Content-Type' : 'text/plain' } ) ; res . end ( JSON . stringify ( { message , code : 500 , } , null , 2 ) ) ; } ; const proxyApiServer = ( ) => { const serverPort = getServerPort ( ) ; if ( serverPort ) { proxy . web ( req , res , { target : `http://localhost:${ serverPort }` } , getErrorCallback ( 'INTERNAL SERVER ERROR. Proxy: Server is down' ) ) ; } else { res . writeHead ( 500 , { 'Content-Type' : 'text/plain' } ) ; res . end ( JSON . stringify ( { message : 'INTERNAL SERVER ERROR. Proxy: Server is down' , code : 500 , } , null , 2 ) ) ; } } ; if ( req ?. url ) { if ( req . url . startsWith ( '/admin/' ) || req . url === '/admin' || req . url . startsWith ( '/admin?' ) ) { proxy . web ( req , res , { target : serviceLocator . getAdminUrl ( ) } , getErrorCallback ( 'INTERNAL SERVER ERROR. Proxy: Admin service is down' ) ) ; } else if ( req . url . startsWith ( '/api/' ) || req . url === '/api' ) { proxyApiServer ( ) ; } else { proxy . web ( req , res , { target : serviceLocator . getFrontendUrl ( ) , } , getErrorCallback ( 'INTERNAL SERVER ERROR. Proxy: Renderer service is down' ) ) ; } } else { proxyApiServer ( ) ; } } ) ; await launchServerManager ( argsPort , args . init ) ; server . on ( "error" , err => logger . log ( err ) ) ; await server . listen ( port ) ; logger . info ( `Proxy Server is running on: http://localhost:${ port }` ) ; serverAliveWatcher ( ) ; } nodeCleanup ( ( ) => { closeAllServers ( ) ; } ) ; main ( ) ;