'use strict' import http = require('http'); import bsock = require('bsock'); import * as T from './Types'; import * as U from './Utils'; import * as I from './Interfaces'; export class RPCServer{ private ws = http.createServer() private io = bsock.createServer() constructor( private port:number, private exporters: I.Exporter[] = [], private conf: T.SocketConf = { errorHandler: (socket:I.Socket) => (error:any) => { socket.destroy(); console.error(error) }, closeHandler: (socket:I.Socket) => () => { console.log("Socket closing") }, connectionHandler: (socket:I.Socket) => { console.log("New websocket connection in port "+socket.port)}, visibility: "127.0.0.1" } ){ this.startWebsocket() } private startWebsocket(){ try{ this.io.attach(this.ws) this.io.on('socket', (socket:I.Socket) => { socket.on('error', this.conf.errorHandler(socket)) socket.on('close', this.conf.closeHandler(socket)) if(this.conf.visibility === "127.0.0.1") this.initRPCs(socket) else this.initPublicRPCs(socket) }) this.ws.listen(this.port, this.conf.visibility) }catch(e){ //@ts-ignore this.errorHandler(undefined)("Unable to connect to socket") } } protected initRPCs(socket:I.Socket){ socket.hook('info', () => rpcInfos) const rpcInfos:T.ExtendedRpcInfo[] = [ ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter)) ] } protected initPublicRPCs(socket:I.Socket){ socket.hook('info', () => rpcInfos) const rpcInfos:T.ExtendedRpcInfo[] = [ ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter)) ] } }