import { Server as HTTPServer } from "http" ; import { Connection } from "@web-udp/client" ; import * as WS from "ws" ; import shortid from "shortid" ; import { Signal , Broker , CLIENT_MASTER , LocalTransport , WebSocketTransport , } from "@web-udp/protocol" ; import { Client , RTCConnectionProvider , PortRange , } from "@web-udp/client" ; function createLocalClient ( id , broker , onConnection , portRange ? ) { const { left , right } = LocalTransport . create ( ) ; const provider = new RTCConnectionProvider ( { onConnection , transport : right , portRange , } ) ; broker . register ( left , id ) ; return new Client ( { provider , transport : right , } ) ; } type ServerOptions = { server : HTTPServer ; keepAlivePeriod ? : number ; portRange ? : PortRange ; } ; const DEFAULT_KEEP_ALIVE_PERIOD = 30000 ; export class Server { private broker : Broker ; private master : Client ; private webSocketServer : WS . Server ; connections : Signal < Connection > = new Signal ( ) ; constructor ( options ) { const { server , keepAlivePeriod = DEFAULT_KEEP_ALIVE_PERIOD , portRange , } = options ; this . webSocketServer = new WS . Server ( { server } ) ; this . broker = new Broker ( { keepAlivePeriod } ) ; this . master = createLocalClient ( CLIENT_MASTER , this . broker , connection => this . connections . dispatch ( connection ) , portRange ) ; this . webSocketServer . on ( "connection" , ws => { const transport = new WebSocketTransport ( ( ws as any ) as WebSocket ) ; const id = this . broker . register ( transport , shortid ( ) ) ; ws . on ( "close" , ( ) => this . master . close ( id ) ) ; } ) ; } client ( ) { const client = createLocalClient ( shortid ( ) , this . broker , connection => client . connections . dispatch ( connection ) ) ; return client ; } }