SocketIoShim.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /* global io */
  2. class SocketShimBase {
  3. static connect(url, options) {
  4. return new SocketShimBase()
  5. }
  6. constructor(socket) {
  7. this._socket = socket
  8. }
  9. }
  10. const transparentMethods = [
  11. 'connect',
  12. 'disconnect',
  13. 'emit',
  14. 'on',
  15. 'removeListener',
  16. ]
  17. for (const method of transparentMethods) {
  18. SocketShimBase.prototype[method] = function () {
  19. this._socket[method].apply(this._socket, arguments)
  20. }
  21. }
  22. class SocketShimNoop extends SocketShimBase {
  23. static connect() {
  24. return new SocketShimNoop()
  25. }
  26. constructor(socket) {
  27. super(socket)
  28. this.socket = {
  29. get connected() {
  30. return false
  31. },
  32. get sessionid() {
  33. return undefined
  34. },
  35. get transport() {
  36. return {}
  37. },
  38. connect() {},
  39. disconnect(reason) {},
  40. }
  41. }
  42. connect() {}
  43. disconnect(reason) {}
  44. emit() {}
  45. on() {}
  46. removeListener() {}
  47. }
  48. class SocketShimV0 extends SocketShimBase {
  49. static connect(url, options) {
  50. return new SocketShimV0(io.connect(url, options))
  51. }
  52. constructor(socket) {
  53. super(socket)
  54. this.socket = this._socket.socket
  55. }
  56. }
  57. class SocketShimV2 extends SocketShimBase {
  58. static connect(url, options) {
  59. options.forceNew = options['force new connection']
  60. // .resource has no leading slash, path wants to see one.
  61. options.path = '/' + options.resource
  62. options.reconnection = options.reconnect
  63. options.timeout = options['connect timeout']
  64. return new SocketShimV2(url, options)
  65. }
  66. static get EVENT_MAP() {
  67. // Use the v2 event names transparently to the frontend.
  68. const connectionFailureEvents = [
  69. 'connect_error',
  70. 'connect_timeout',
  71. 'error',
  72. ]
  73. return new Map([
  74. ['connect_failed', connectionFailureEvents],
  75. ['error', connectionFailureEvents],
  76. ])
  77. }
  78. _on(event, handler) {
  79. // Keep track of our event listeners.
  80. // We move them to a new socket in ._replaceSocketWithNewInstance()
  81. if (!this._events.has(event)) {
  82. this._events.set(event, [handler])
  83. } else {
  84. this._events.get(event).push(handler)
  85. }
  86. this._socket.on(event, handler)
  87. }
  88. on(event, handler) {
  89. if (SocketShimV2.EVENT_MAP.has(event)) {
  90. for (const v2Event of SocketShimV2.EVENT_MAP.get(event)) {
  91. this._on(v2Event, handler)
  92. }
  93. } else {
  94. this._on(event, handler)
  95. }
  96. }
  97. _removeListener(event, handler) {
  98. // Keep track of our event listeners.
  99. // We move them to a new socket in ._replaceSocketWithNewInstance()
  100. if (this._events.has(event)) {
  101. const listeners = this._events.get(event)
  102. const pos = listeners.indexOf(handler)
  103. if (pos !== -1) {
  104. listeners.splice(pos, 1)
  105. }
  106. }
  107. this._socket.removeListener(event, handler)
  108. }
  109. removeListener(event, handler) {
  110. if (SocketShimV2.EVENT_MAP.has(event)) {
  111. for (const v2Event of SocketShimV2.EVENT_MAP.get(event)) {
  112. this._removeListener(v2Event, handler)
  113. }
  114. } else {
  115. this._removeListener(event, handler)
  116. }
  117. }
  118. static createNewSocket(url, options) {
  119. // open a brand new connection for the default namespace '/'
  120. // The old socket can still leak 'disconnect' events from the teardown
  121. // of the old transport. The leaking 'disconnect' events interfere with
  122. // the _new_ connection and cancel the new connect attempt.
  123. // Also skip the caching in these locations:
  124. // - `io.connect()` caches `io.Manager`s in `io.managers`
  125. // - `io.Manager().socket()` caches `io.Socket`s in its `this.nsps`
  126. return io.Manager(url, options).socket('/', options)
  127. }
  128. _replaceSocketWithNewInstance() {
  129. const oldSocket = this._socket
  130. const newSocket = SocketShimV2.createNewSocket(this._url, this._options)
  131. // move our existing event handlers to the new socket
  132. this._events.forEach((listeners, event) => {
  133. for (const listener of listeners) {
  134. oldSocket.removeListener(event, listener)
  135. newSocket.on(event, listener)
  136. }
  137. })
  138. if (oldSocket.connected) {
  139. // We overwrite the reference to oldSocket soon.
  140. // Make sure we are disconnected.
  141. oldSocket.disconnect()
  142. }
  143. this._socket = newSocket
  144. }
  145. connect() {
  146. // have the same logic behind socket.connect and socket.socket.connect
  147. this._replaceSocketWithNewInstance()
  148. }
  149. constructor(url, options) {
  150. super(SocketShimV2.createNewSocket(url, options))
  151. this._url = url
  152. this._options = options
  153. this._events = new Map()
  154. const self = this
  155. function _getEngine() {
  156. return (self._socket.io && self._socket.io.engine) || {}
  157. }
  158. this.socket = {
  159. get connected() {
  160. return self._socket.connected
  161. },
  162. get sessionid() {
  163. if (self._socket.id) {
  164. return self._socket.id
  165. }
  166. // socket.id is discarded upon disconnect
  167. // the id is still available in the internal state
  168. return _getEngine().id
  169. },
  170. get transport() {
  171. return _getEngine().transport
  172. },
  173. connect() {
  174. self._replaceSocketWithNewInstance()
  175. },
  176. disconnect(reason) {
  177. return self._socket.disconnect(reason)
  178. },
  179. }
  180. }
  181. }
  182. let current
  183. if (typeof io === 'undefined' || !io) {
  184. sl_console.log('[socket.io] Shim: socket.io is not loaded, returning noop')
  185. current = SocketShimNoop
  186. } else if (typeof io.version === 'string' && io.version.slice(0, 1) === '0') {
  187. sl_console.log('[socket.io] Shim: detected v0')
  188. current = SocketShimV0
  189. } else {
  190. // socket.io v2 does not have a global io.version attribute.
  191. sl_console.log('[socket.io] Shim: detected v2')
  192. current = SocketShimV2
  193. }
  194. export default {
  195. SocketShimNoop,
  196. SocketShimV0,
  197. SocketShimV2,
  198. current,
  199. connect: current.connect,
  200. stub: () => new SocketShimNoop(),
  201. }