import { NodeCG } from "nodecg-types/types/server" ; import { Result , emptySuccess , success , error , ServiceBundle , Logger } from "nodecg-io-core" ; import * as WebSocket from "ws" ; interface WSServerServiceConfig { port : number ; } export type WSServerServiceClient = WebSocket . Server ; module . exports = ( nodecg ) => { new WSServerService ( nodecg , "websocket-server" , __dirname , "../ws-schema.json" ) . register ( ) ; } ; class WSServerService extends ServiceBundle < WSServerServiceConfig , WSServerServiceClient > { async getServer ( config ) { const client = new WebSocket . Server ( { port : config . port } ) ; return await new Promise < Result < WebSocket . Server > > ( ( resolve ) => { client . once ( "listening" , ( ) => { resolve ( success ( client ) ) ; } ) ; client . once ( "error" , ( err ) => { resolve ( error ( err . message ) ) ; } ) ; } ) ; } async validateConfig ( config ) { const client = await this . getServer ( config ) ; if ( ! client . failed ) { client . result . close ( ) ; return emptySuccess ( ) ; } else { return client ; } } async createClient ( config , logger ) { const client = await this . getServer ( config ) ; if ( client . failed ) { return client ; } logger . info ( "Successfully started WebSocket server." ) ; return success ( client . result ) ; } stopClient ( client ) { client . close ( ) ; } removeHandlers ( client ) { client . removeAllListeners ( ) ; client . clients . forEach ( ( client ) => { client . close ( ) ; } ) ; } }