You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Frontend.ts 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. 'use strict'
  2. import { PromiseIOClient, defaultClientConfig } from './PromiseIO/Client'
  3. import * as T from './Types';
  4. import * as I from './Interfaces';
  5. import { stripAfterEquals, appendComma } from './Utils';
  6. /**
  7. * A websocket-on-steroids with built-in RPC capabilities
  8. */
  9. export class RPCSocket<Ifc extends T.RPCInterface = T.RPCInterface> implements I.Socket {
  10. static async makeSocket<T extends T.RPCInterface = T.RPCInterface>(port: number, server: string, sesame?: string, conf: T.ClientConfig = defaultClientConfig): Promise<T.ConnectedSocket<T>> {
  11. const socket = new RPCSocket<T>(port, server, conf)
  12. return await socket.connect(sesame)
  13. }
  14. private socket: I.Socket
  15. private handlers: {
  16. [name in string]: T.AnyFunction[]
  17. } = {
  18. error: [],
  19. close: []
  20. }
  21. private hooks: { [name in string]: T.AnyFunction } = {}
  22. /**
  23. *
  24. * @param port Port to connect to
  25. * @param server Server address
  26. * @param tls @default false use TLS
  27. */
  28. constructor(public port: number, public address: string, private conf: T.ClientConfig = defaultClientConfig) {
  29. Object.defineProperty(this, 'socket', { value: undefined, writable: true })
  30. this.hook("$UNKNOWNRPC$", (err) => this.handlers['error'].forEach(handler => handler(err)))
  31. }
  32. /**
  33. * Hooks a handler to a function name. Use {@link call} to trigger it.
  34. * @param name The function name to listen on
  35. * @param handler The handler to attach
  36. */
  37. public hook(name: string, handler: (...args: any[]) => any | Promise<any>) {
  38. if (!this.socket) {
  39. this.hooks[name] = handler
  40. } else {
  41. this.socket.hook(name, handler)
  42. }
  43. }
  44. /**
  45. * Hooks a handler to a function name. Use {@link call} to trigger it.
  46. * @param name The function name to listen on
  47. * @param handler The handler to attach
  48. */
  49. public bind(name: string, handler: (...args: any[]) => any | Promise<any>) {
  50. if (!this.socket) {
  51. this.hooks[name] = handler
  52. } else {
  53. this.socket.bind(name, handler)
  54. }
  55. }
  56. /**
  57. * Removes a {@link hook} listener by name.
  58. * @param name The function name
  59. */
  60. public unhook(name: string) {
  61. if (!this.socket) {
  62. delete this.hooks[name]
  63. } else {
  64. this.socket.unhook(name)
  65. }
  66. }
  67. /**
  68. * Attach a listener to error or close events
  69. * @param type 'error' or 'close'
  70. * @param f The listener to attach
  71. */
  72. public on(type: string, f: T.AnyFunction) {
  73. if (!this.socket) {
  74. if (!this.handlers[type])
  75. this.handlers[type] = []
  76. this.handlers[type].push(f)
  77. } else {
  78. this.socket.on(type, f)
  79. }
  80. }
  81. /**
  82. * Emit a LOCAL event
  83. * @param eventName The event name to emit under
  84. * @param data The data the event carries
  85. */
  86. public emit(eventName: string, data: any) {
  87. if (!this.socket) return
  88. this.socket.emit(eventName, data)
  89. }
  90. /**
  91. * Closes the socket. It may attempt to reconnect.
  92. */
  93. public close() {
  94. if (!this.socket) return;
  95. this.socket.close()
  96. }
  97. /**
  98. * Trigger a hooked handler on the server
  99. * @param rpcname The function to call
  100. * @param args other arguments
  101. */
  102. public async call(rpcname: string, ...args: any[]): Promise<any> {
  103. if (!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  104. try {
  105. const val = await this.socket.call.apply(this.socket, [rpcname, ...args])
  106. return val
  107. } catch (e) {
  108. this.emit('error', e)
  109. throw e
  110. }
  111. }
  112. /**
  113. * An alternative to call that does not wait for confirmation and doesn't return a value.
  114. * @param rpcname The function to call
  115. * @param args other arguments
  116. */
  117. public async fire(rpcname: string, ...args: any[]): Promise<void> {
  118. if (!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  119. await this.socket.fire.apply(this.socket, [rpcname, ...args])
  120. }
  121. /**
  122. * Connects to the server and attaches available RPCs to this object
  123. */
  124. public async connect(sesame?: string): Promise<T.ConnectedSocket<Ifc>> {
  125. try {
  126. this.socket = await PromiseIOClient.connect(this.port, this.address, this.conf)
  127. } catch (e) {
  128. this.handlers['error'].forEach(h => h(e))
  129. throw e
  130. }
  131. Object.entries(this.handlers).forEach(([k, v]) => {
  132. v.forEach(h => this.socket.on(k, h))
  133. })
  134. Object.entries(this.hooks).forEach((kv: [string, T.AnyFunction]) => {
  135. this.socket.hook(kv[0], kv[1])
  136. })
  137. const info: T.ExtendedRpcInfo[] = await this.info(sesame)
  138. info.forEach(i => {
  139. let f: any
  140. switch (i.type) {
  141. case 'Call':
  142. f = this.callGenerator(i.uniqueName, i.argNames, sesame)
  143. break
  144. case 'Hook':
  145. f = this.frontEndHookGenerator(i.uniqueName, i.argNames, sesame)
  146. break
  147. }
  148. if (this[i.owner] == null)
  149. this[i.owner] = {}
  150. this[i.owner][i.name] = f
  151. this[i.owner][i.name].bind(this)
  152. })
  153. return <T.ConnectedSocket<Ifc>>(this as any)
  154. }
  155. /**
  156. * Get a list of available RPCs from the server
  157. */
  158. public async info(sesame?: string) {
  159. if (!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  160. return await this.socket.call('info', sesame)
  161. }
  162. /**
  163. * Utility {@link AsyncFunction} generator
  164. * @param fnName The function name
  165. * @param fnArgs A string-list of parameters
  166. */
  167. private callGenerator(fnName: string, fnArgs: string[], sesame?: string): T.AnyFunction {
  168. const headerArgs = fnArgs.join(",")
  169. const argParams = fnArgs.map(stripAfterEquals).join(",")
  170. sesame = appendComma(sesame)
  171. return eval(`async (${headerArgs}) => {
  172. return await this.call("${fnName}", ${sesame} ${argParams})
  173. }`)
  174. }
  175. /**
  176. * Utility {@link HookFunction} generator
  177. * @param fnName The function name
  178. * @param fnArgs A string-list of parameters
  179. */
  180. private frontEndHookGenerator(fnName: string, fnArgs: string[], sesame?: string): T.HookFunction {
  181. if (sesame)
  182. fnArgs.shift()
  183. let headerArgs = fnArgs.join(",")
  184. const argParams = fnArgs.map(stripAfterEquals).join(",")
  185. sesame = appendComma(sesame, true)
  186. headerArgs = fnArgs.length > 0 ? headerArgs + "," : headerArgs
  187. const frontendHookStr = `
  188. async (${headerArgs} $__callback__$) => {
  189. const r = await this.call("${fnName}", ${sesame} ${argParams})
  190. try{
  191. if(r){
  192. if(r.uuid){
  193. $__callback__$['destroy'] = () => {
  194. this.socket.fire('destroy_'+r.uuid)
  195. this.socket.unhook(r.uuid)
  196. }
  197. this.socket.hook(r.uuid, $__callback__$)
  198. }
  199. return r.return
  200. }else{
  201. throw new Error("Empty response")
  202. }
  203. }catch(e){
  204. throw e
  205. }
  206. }`
  207. return eval(frontendHookStr)
  208. }
  209. }