123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- 'use strict'
-
- import bsock = require('bsock');
-
- import * as T from './Types';
- import * as I from './Interfaces';
- import { stripAfterEquals, appendComma } from './Utils';
-
-
-
- /**
- * A websocket-on-steroids with built-in RPC capabilities
- */
- export class RPCSocket implements I.Socket{
- static async makeSocket<T extends T.RPCInterface = T.RPCInterface>(port:number, server: string, sesame?:string, conf?:T.SocketConf): Promise<RPCSocket & T> {
- const socket = new RPCSocket(port, server, conf)
- return await socket.connect<T>(sesame)
- }
-
- private socket: I.Socket
- private closeHandlers: T.FrontEndHandlerType['close'][] = []
- private errorHandlers: T.FrontEndHandlerType['error'][] = []
- private hooks : {[name in string]: T.AnyFunction} = {}
-
- /**
- *
- * @param port Port to connect to
- * @param server Server address
- * @param tls @default false use TLS
- */
- constructor(public port:number, private server: string, private conf:T.SocketConf = { tls: false }){
- Object.defineProperty(this, 'socket', {value: undefined, writable: true})
- }
-
- /**
- * Hooks a handler to a function name. Use {@link call} to trigger it.
- * @param name The function name to listen on
- * @param handler The handler to attach
- */
- public hook(name: string, handler: (...args:any[]) => any | Promise<any>){
- if(!this.socket){
- this.hooks[name] = handler
- }else{
- this.socket.hook(name, handler)
- }
- }
-
- /**
- * Removes a {@link hook} listener by name.
- * @param name The function name
- */
- public unhook(name: string){
- if(!this.socket){
- delete this.hooks[name]
- }else{
- this.socket.unhook(name)
- }
- }
-
- /**
- * Attach a listener to error or close events
- * @param type 'error' or 'close'
- * @param f The listener to attach
- */
- public on<T extends "error" | "close">(type: T, f: T.FrontEndHandlerType[T]){
- if(!this.socket){
- switch(type){
- case "error": this.errorHandlers.push(<T.FrontEndHandlerType['error']> f); break;
- case "close": this.closeHandlers.push(<T.FrontEndHandlerType['close']> f); break;
- default: throw new Error('socket.on only supports ´error´ and ´close´ as first parameter. Got: ´'+type+'´')
- }
- }else{
- this.socket.on(type, f)
- }
- }
-
- /**
- * Emit a LOCAL event
- * @param eventName The event name to emit under
- * @param data The data the event carries
- */
- public emit(eventName:string, data:any){
- if(!this.socket) return
- this.socket.emit(eventName, data)
- }
-
- /**
- * Destroys the socket
- */
- public destroy(){
- if(!this.socket) return;
- this.socket.destroy()
- }
-
- /**
- * Closes the socket. It may attempt to reconnect.
- */
- public close(){
- if(!this.socket) return;
- this.socket.close()
- }
-
- /**
- * Trigger a hooked handler on the server
- * @param rpcname The function to call
- * @param args other arguments
- */
- public async call (rpcname: string, ...args: any[]) : Promise<any>{
- if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
- try{
- return await this.socket.call.apply(this.socket, [rpcname, ...args])
- }catch(e){
- this.emit('error', e)
- throw e
- }
- }
-
- /**
- * An alternative to call that does not wait for confirmation and doesn't return a value.
- * @param rpcname The function to call
- * @param args other arguments
- */
- public async fire(rpcname: string, ...args: any[]) : Promise<void>{
- if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
- await this.socket.fire.apply(this.socket, [rpcname, ...args])
- }
-
- /**
- * Connects to the server and attaches available RPCs to this object
- */
- public async connect<T extends T.RPCInterface= T.RPCInterface>( sesame?: string ) : Promise<RPCSocket & T>{
- this.socket = await bsock.connect(this.port, this.server, this.conf.tls?this.conf.tls:false)
- this.errorHandlers.forEach(h => this.socket.on('error', h))
- this.closeHandlers.forEach(h => this.socket.on('close', h))
- Object.entries(this.hooks).forEach((kv: [string, T.AnyFunction]) => {
- this.socket.hook(kv[0], kv[1])
- })
-
- const info:T.ExtendedRpcInfo[] = await this.info(sesame)
- info.forEach(i => {
- let f: any
-
- switch (i.type) {
- case 'Call':
- f = this.callGenerator(i.uniqueName, i.argNames, sesame)
- break
- case 'Hook':
- f = this.frontEndHookGenerator(i.uniqueName, i.argNames, sesame)
- break
- }
- if(this[i.owner] == null)
- this[i.owner] = {}
- this[i.owner][i.name] = f
- this[i.owner][i.name].bind(this)
- })
- return <RPCSocket & T.RPCInterface<T>> (this as any)
- }
-
- /**
- * Get a list of available RPCs from the server
- */
- public async info(sesame?:string){
- if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
- return await this.socket.call('info', sesame)
- }
-
- /**
- * Utility {@link AsyncFunction} generator
- * @param fnName The function name
- * @param fnArgs A string-list of parameters
- */
- private callGenerator(fnName: string, fnArgs:string[], sesame?:string): T.AnyFunction{
- const headerArgs = fnArgs.join(",")
- const argParams = fnArgs.map(stripAfterEquals).join(",")
- sesame = appendComma(sesame)
-
- return eval(`async (${headerArgs}) => {
- return await this.call("${fnName}", ${sesame} ${argParams})
- }`)
- }
-
- /**
- * Utility {@link HookFunction} generator
- * @param fnName The function name
- * @param fnArgs A string-list of parameters
- */
- private frontEndHookGenerator(fnName: string, fnArgs:string[], sesame?:string): T.HookFunction{
-
- if(sesame)
- fnArgs.shift()
-
- let headerArgs = fnArgs.join(",")
- const argParams = fnArgs.map(stripAfterEquals).join(",")
- sesame = appendComma(sesame, true)
- headerArgs = fnArgs.length>0?headerArgs+",":headerArgs
-
- return eval( `
- async (${headerArgs} callback) => {
- const r = await this.call("${fnName}", ${sesame} ${argParams})
- if(r && r.result === 'Success'){
- this.socket.hook(r.uuid, callback)
- }
- return r
- }`)
- }
- }
|