import { setBasePath } from "@thorium/db-fs" ; import { databaseName , thoriumPath , rootPath } from "./utils/appPaths" ; import buildHTTPServer from "./init/httpServer" ; import path from "path" ; import { setUpAPI } from "./init/setUpAPI" ; import { ServerDataModel } from "./classes/ServerDataModel" ; import randomWords from "@thorium/random-words" ; import { applyDataChannel } from "./init/dataChannel" ; import chalk from "chalk" ; import { FlightDataModel } from "./classes/FlightDataModel" ; import { promises as fs , existsSync } from "fs" ; import { unzip } from "./utils/unzipFolder" ; setBasePath ( thoriumPath ) ; const isHeadless = ! process . env . FORK ; export async function startServer ( ) { if ( ! existsSync ( thoriumPath ) ) { await fs . mkdir ( thoriumPath , { recursive : true } ) ; await fs . mkdir ( path . join ( thoriumPath , "plugins" ) , { recursive : true } ) ; await unzip ( path . join ( rootPath , isHeadless ? "./" : "../../app" , "defaultPlugin.zip" ) , path . join ( thoriumPath , "plugins/" ) ) ; } const serverModel = new ServerDataModel ( { thoriumId : randomWords ( 3 ) . join ( "-" ) , activeFlightName : null } , { path : databaseName } ) ; let flight = null ; if ( serverModel . activeFlightName ) { const flightName = serverModel . activeFlightName ; flight = new FlightDataModel ( { name : flightName , initialLoad : true , entities : [ ] , serverDataModel : serverModel , } , { path : `/flights/${ flightName }.flight` } ) ; flight . initEcs ( serverModel ) ; } const database = { server : serverModel , flight } ; const app = buildHTTPServer ( { staticRoot : path . join ( rootPath , "public/" ) , } ) ; await applyDataChannel ( app , database ) ; setUpAPI ( app , database ) ; const PORT = process . env . PORT || ( process . env . NODE_ENV === "production" ? 4444 : 3001 ) ; try { await app . listen ( PORT , "0.0.0.0" ) ; console . info ( chalk . greenBright ( `Access app at http://localhost:${ PORT }` ) ) ; console . info ( chalk . cyan ( `Doing port forwarding? Open this port in your router:` ) ) ; console . info ( chalk . cyan ( `  - TCP ${ PORT } for web app access` ) ) ; process . send ?. ( "ready" ) ; } catch ( err ) { process . send ?. ( "error" ) ; console . error ( err ) ; app . log . error ( err ) ; } } startServer ( ) ;