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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import * as uuidv4 from "uuid/v4"
  2. import * as T from "./Types";
  3. import * as I from "./Interfaces";
  4. import { SubscriptionResponse } from "./Types";
  5. /**
  6. * Translate an RPC to RPCInfo for serialization.
  7. * @param rpc The RPC to transform
  8. * @param owner The owning RPC group's name
  9. * @throws Error on RPC without name property
  10. */
  11. export const rpcToRpcinfo = <SubResT = {}>(rpc : T.RPC<any, any, SubResT>, owner: string, sesame?:T.SesameFunction):T.RpcInfo => {
  12. switch (typeof rpc){
  13. case "object":
  14. if(rpc['call']){
  15. return {
  16. owner: owner,
  17. argNames: extractArgs(rpc['call']),
  18. type: "Call",
  19. name: rpc.name,
  20. call: sesame?async (_sesame, ...args) => {if(sesame(_sesame)) return await rpc['call'].apply({}, args); throw new Error('Bad sesame')}:rpc['call'], // check & remove sesame
  21. }
  22. }else{
  23. const generator = hookGenerator(<T.HookRPC<any, any, any>>rpc, sesame)
  24. return {
  25. owner: owner,
  26. argNames: extractArgs(generator(undefined)),
  27. type: "Hook",
  28. name: rpc.name,
  29. generator: generator,
  30. }
  31. }
  32. case "function":
  33. if(!rpc.name) throw new Error(`
  34. RPC did not provide a name.
  35. \nUse 'funtion name(..){ .. }' syntax instead.
  36. \n
  37. \n<------------OFFENDING RPC:
  38. \n`+rpc.toString()+`
  39. \n>------------OFFENDING RPC`)
  40. return {
  41. owner : owner,
  42. argNames: extractArgs(rpc),
  43. type: "Call",
  44. name: rpc.name,
  45. call: sesame?async (_sesame, ...args) => {if(sesame(_sesame)) return await rpc.apply({}, args)}:rpc, // check & remove sesame
  46. }
  47. }
  48. throw new Error("Bad socketIORPC type "+ typeof rpc)
  49. }
  50. /**
  51. * Utility function to apply the RPCs of an {@link RPCExporter}.
  52. * @param socket The websocket (implementation: bsock) to hook on
  53. * @param exporter The exporter
  54. * @param makeUnique @default true Attach a suffix to RPC names
  55. */
  56. export function rpcHooker<SubResT = {}>(socket: I.Socket, exporter:I.RPCExporter<any, any, SubResT>, sesame?:T.SesameFunction, makeUnique = true):T.ExtendedRpcInfo[]{
  57. const owner = exporter.name
  58. const RPCs = [...exporter.exportRPCs()]
  59. return RPCs.map(rpc => rpcToRpcinfo(rpc, owner, sesame))
  60. .map(info => {
  61. const suffix = makeUnique?"-"+uuidv4().substr(0,4):""
  62. const ret:any = info
  63. ret.uniqueName = info.name+suffix
  64. switch(info.type){
  65. case "Hook":
  66. socket.hook(ret.uniqueName, info.generator(socket))
  67. break;
  68. case "Call":
  69. socket.hook(ret.uniqueName, info.call)
  70. break;
  71. }
  72. socket.on('close', () => socket.unhook(info.name))
  73. return ret
  74. })
  75. }
  76. /**
  77. * Utility function to generate {@link HookFunction} from a RPC for backend
  78. * @param rpc The RPC to transform
  79. * @returns A {@link HookFunction}
  80. */
  81. const hookGenerator = (rpc:T.HookRPC<any, any, any>, sesameFn?: T.SesameFunction): T.HookInfo['generator'] => {
  82. const argsArr = extractArgs(rpc.hook)
  83. argsArr.pop() //remove 'callback' from the end
  84. const argsStr = argsArr.join(',')
  85. if(sesameFn){
  86. const args = ['sesame', ...argsArr].join(',')
  87. const f = eval(`(socket) => async (`+args+`) => {
  88. if(!sesameFn(sesame)) return
  89. const res = await rpc.hook(`+argsStr+(argsStr.length!==0?',':'')+` (...cbargs) => {
  90. if(rpc.onCallback) rpc.onCallback.apply({}, cbargs)
  91. socket.call.apply(socket, [res.uuid, ...cbargs])
  92. })
  93. return res
  94. }`)
  95. return f
  96. }
  97. const args = argsArr.join(',')
  98. return eval(`(socket) => async (`+args+`) => {
  99. const res = await rpc.hook(`+args+(args.length!==0?',':'')+` (...cbargs) => {
  100. if(rpc.onCallback) rpc.onCallback.apply({}, cbargs)
  101. socket.call.apply(socket, [res.uuid, ...cbargs])
  102. })
  103. return res
  104. }`)
  105. }
  106. /**
  107. * Extract a string list of parameters from a function
  108. * @param f The source function
  109. */
  110. const extractArgs = (f:Function):string[] => {
  111. let fn:string
  112. return (fn = String(f)).substr(0, fn.indexOf(")")).substr(fn.indexOf("(")+1).split(",")
  113. }
  114. /**
  115. * Simple utility function to create basic {@link SubscriptionResponse}
  116. * @param uuid optional uuid to use, otherwise defaults to uuid/v4
  117. */
  118. export function makeSubResponse<T extends {} = {}>(extension:T):SubscriptionResponse & T{
  119. return {
  120. result: "Success",
  121. uuid: uuidv4(),
  122. ...extension
  123. }
  124. }
  125. export function makeSesameFunction (sesame : T.SesameFunction | string) : T.SesameFunction {
  126. if(typeof sesame === 'function'){
  127. return sesame
  128. }
  129. return (testSesame : string) => {
  130. return testSesame === sesame
  131. }
  132. }