eventsource.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. var parse = require('url').parse
  2. var events = require('events')
  3. var https = require('https')
  4. var http = require('http')
  5. var util = require('util')
  6. var httpsOptions = [
  7. 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
  8. 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'
  9. ]
  10. var bom = [239, 187, 191]
  11. var colon = 58
  12. var space = 32
  13. var lineFeed = 10
  14. var carriageReturn = 13
  15. // Beyond 256KB we could not observe any gain in performance
  16. var maxBufferAheadAllocation = 1024 * 256
  17. // Headers matching the pattern should be removed when redirecting to different origin
  18. var reUnsafeHeader = /^(cookie|authorization)$/i
  19. function hasBom (buf) {
  20. return bom.every(function (charCode, index) {
  21. return buf[index] === charCode
  22. })
  23. }
  24. /**
  25. * Creates a new EventSource object
  26. *
  27. * @param {String} url the URL to which to connect
  28. * @param {Object} [eventSourceInitDict] extra init params. See README for details.
  29. * @api public
  30. **/
  31. function EventSource (url, eventSourceInitDict) {
  32. var readyState = EventSource.CONNECTING
  33. var headers = eventSourceInitDict && eventSourceInitDict.headers
  34. var hasNewOrigin = false
  35. Object.defineProperty(this, 'readyState', {
  36. get: function () {
  37. return readyState
  38. }
  39. })
  40. Object.defineProperty(this, 'url', {
  41. get: function () {
  42. return url
  43. }
  44. })
  45. var self = this
  46. self.reconnectInterval = 1000
  47. self.connectionInProgress = false
  48. function onConnectionClosed (message) {
  49. if (readyState === EventSource.CLOSED) return
  50. readyState = EventSource.CONNECTING
  51. _emit('error', new Event('error', {message: message}))
  52. // The url may have been changed by a temporary redirect. If that's the case,
  53. // revert it now, and flag that we are no longer pointing to a new origin
  54. if (reconnectUrl) {
  55. url = reconnectUrl
  56. reconnectUrl = null
  57. hasNewOrigin = false
  58. }
  59. setTimeout(function () {
  60. if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
  61. return
  62. }
  63. self.connectionInProgress = true
  64. connect()
  65. }, self.reconnectInterval)
  66. }
  67. var req
  68. var lastEventId = ''
  69. if (headers && headers['Last-Event-ID']) {
  70. lastEventId = headers['Last-Event-ID']
  71. delete headers['Last-Event-ID']
  72. }
  73. var discardTrailingNewline = false
  74. var data = ''
  75. var eventName = ''
  76. var reconnectUrl = null
  77. function connect () {
  78. var options = parse(url)
  79. var isSecure = options.protocol === 'https:'
  80. options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' }
  81. if (lastEventId) options.headers['Last-Event-ID'] = lastEventId
  82. if (headers) {
  83. var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers
  84. for (var i in reqHeaders) {
  85. var header = reqHeaders[i]
  86. if (header) {
  87. options.headers[i] = header
  88. }
  89. }
  90. }
  91. // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
  92. // but for now exists as a backwards-compatibility layer
  93. options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)
  94. if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
  95. options.createConnection = eventSourceInitDict.createConnection
  96. }
  97. // If specify http proxy, make the request to sent to the proxy server,
  98. // and include the original url in path and Host headers
  99. var useProxy = eventSourceInitDict && eventSourceInitDict.proxy
  100. if (useProxy) {
  101. var proxy = parse(eventSourceInitDict.proxy)
  102. isSecure = proxy.protocol === 'https:'
  103. options.protocol = isSecure ? 'https:' : 'http:'
  104. options.path = url
  105. options.headers.Host = options.host
  106. options.hostname = proxy.hostname
  107. options.host = proxy.host
  108. options.port = proxy.port
  109. }
  110. // If https options are specified, merge them into the request options
  111. if (eventSourceInitDict && eventSourceInitDict.https) {
  112. for (var optName in eventSourceInitDict.https) {
  113. if (httpsOptions.indexOf(optName) === -1) {
  114. continue
  115. }
  116. var option = eventSourceInitDict.https[optName]
  117. if (option !== undefined) {
  118. options[optName] = option
  119. }
  120. }
  121. }
  122. // Pass this on to the XHR
  123. if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
  124. options.withCredentials = eventSourceInitDict.withCredentials
  125. }
  126. req = (isSecure ? https : http).request(options, function (res) {
  127. self.connectionInProgress = false
  128. // Handle HTTP errors
  129. if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
  130. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  131. onConnectionClosed()
  132. return
  133. }
  134. // Handle HTTP redirects
  135. if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
  136. var location = res.headers.location
  137. if (!location) {
  138. // Server sent redirect response without Location header.
  139. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  140. return
  141. }
  142. var prevOrigin = new URL(url).origin
  143. var nextOrigin = new URL(location).origin
  144. hasNewOrigin = prevOrigin !== nextOrigin
  145. if (res.statusCode === 307) reconnectUrl = url
  146. url = location
  147. process.nextTick(connect)
  148. return
  149. }
  150. if (res.statusCode !== 200) {
  151. _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
  152. return self.close()
  153. }
  154. readyState = EventSource.OPEN
  155. res.on('close', function () {
  156. res.removeAllListeners('close')
  157. res.removeAllListeners('end')
  158. onConnectionClosed()
  159. })
  160. res.on('end', function () {
  161. res.removeAllListeners('close')
  162. res.removeAllListeners('end')
  163. onConnectionClosed()
  164. })
  165. _emit('open', new Event('open'))
  166. // text/event-stream parser adapted from webkit's
  167. // Source/WebCore/page/EventSource.cpp
  168. var buf
  169. var newBuffer
  170. var startingPos = 0
  171. var startingFieldLength = -1
  172. var newBufferSize = 0
  173. var bytesUsed = 0
  174. res.on('data', function (chunk) {
  175. if (!buf) {
  176. buf = chunk
  177. if (hasBom(buf)) {
  178. buf = buf.slice(bom.length)
  179. }
  180. bytesUsed = buf.length
  181. } else {
  182. if (chunk.length > buf.length - bytesUsed) {
  183. newBufferSize = (buf.length * 2) + chunk.length
  184. if (newBufferSize > maxBufferAheadAllocation) {
  185. newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation
  186. }
  187. newBuffer = Buffer.alloc(newBufferSize)
  188. buf.copy(newBuffer, 0, 0, bytesUsed)
  189. buf = newBuffer
  190. }
  191. chunk.copy(buf, bytesUsed)
  192. bytesUsed += chunk.length
  193. }
  194. var pos = 0
  195. var length = bytesUsed
  196. while (pos < length) {
  197. if (discardTrailingNewline) {
  198. if (buf[pos] === lineFeed) {
  199. ++pos
  200. }
  201. discardTrailingNewline = false
  202. }
  203. var lineLength = -1
  204. var fieldLength = startingFieldLength
  205. var c
  206. for (var i = startingPos; lineLength < 0 && i < length; ++i) {
  207. c = buf[i]
  208. if (c === colon) {
  209. if (fieldLength < 0) {
  210. fieldLength = i - pos
  211. }
  212. } else if (c === carriageReturn) {
  213. discardTrailingNewline = true
  214. lineLength = i - pos
  215. } else if (c === lineFeed) {
  216. lineLength = i - pos
  217. }
  218. }
  219. if (lineLength < 0) {
  220. startingPos = length - pos
  221. startingFieldLength = fieldLength
  222. break
  223. } else {
  224. startingPos = 0
  225. startingFieldLength = -1
  226. }
  227. parseEventStreamLine(buf, pos, fieldLength, lineLength)
  228. pos += lineLength + 1
  229. }
  230. if (pos === length) {
  231. buf = void 0
  232. bytesUsed = 0
  233. } else if (pos > 0) {
  234. buf = buf.slice(pos, bytesUsed)
  235. bytesUsed = buf.length
  236. }
  237. })
  238. })
  239. req.on('error', function (err) {
  240. self.connectionInProgress = false
  241. onConnectionClosed(err.message)
  242. })
  243. if (req.setNoDelay) req.setNoDelay(true)
  244. req.end()
  245. }
  246. connect()
  247. function _emit () {
  248. if (self.listeners(arguments[0]).length > 0) {
  249. self.emit.apply(self, arguments)
  250. }
  251. }
  252. this._close = function () {
  253. if (readyState === EventSource.CLOSED) return
  254. readyState = EventSource.CLOSED
  255. if (req.abort) req.abort()
  256. if (req.xhr && req.xhr.abort) req.xhr.abort()
  257. }
  258. function parseEventStreamLine (buf, pos, fieldLength, lineLength) {
  259. if (lineLength === 0) {
  260. if (data.length > 0) {
  261. var type = eventName || 'message'
  262. _emit(type, new MessageEvent(type, {
  263. data: data.slice(0, -1), // remove trailing newline
  264. lastEventId: lastEventId,
  265. origin: new URL(url).origin
  266. }))
  267. data = ''
  268. }
  269. eventName = void 0
  270. } else if (fieldLength > 0) {
  271. var noValue = fieldLength < 0
  272. var step = 0
  273. var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString()
  274. if (noValue) {
  275. step = lineLength
  276. } else if (buf[pos + fieldLength + 1] !== space) {
  277. step = fieldLength + 1
  278. } else {
  279. step = fieldLength + 2
  280. }
  281. pos += step
  282. var valueLength = lineLength - step
  283. var value = buf.slice(pos, pos + valueLength).toString()
  284. if (field === 'data') {
  285. data += value + '\n'
  286. } else if (field === 'event') {
  287. eventName = value
  288. } else if (field === 'id') {
  289. lastEventId = value
  290. } else if (field === 'retry') {
  291. var retry = parseInt(value, 10)
  292. if (!Number.isNaN(retry)) {
  293. self.reconnectInterval = retry
  294. }
  295. }
  296. }
  297. }
  298. }
  299. module.exports = EventSource
  300. util.inherits(EventSource, events.EventEmitter)
  301. EventSource.prototype.constructor = EventSource; // make stacktraces readable
  302. ['open', 'error', 'message'].forEach(function (method) {
  303. Object.defineProperty(EventSource.prototype, 'on' + method, {
  304. /**
  305. * Returns the current listener
  306. *
  307. * @return {Mixed} the set function or undefined
  308. * @api private
  309. */
  310. get: function get () {
  311. var listener = this.listeners(method)[0]
  312. return listener ? (listener._listener ? listener._listener : listener) : undefined
  313. },
  314. /**
  315. * Start listening for events
  316. *
  317. * @param {Function} listener the listener
  318. * @return {Mixed} the set function or undefined
  319. * @api private
  320. */
  321. set: function set (listener) {
  322. this.removeAllListeners(method)
  323. this.addEventListener(method, listener)
  324. }
  325. })
  326. })
  327. /**
  328. * Ready states
  329. */
  330. Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0})
  331. Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1})
  332. Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2})
  333. EventSource.prototype.CONNECTING = 0
  334. EventSource.prototype.OPEN = 1
  335. EventSource.prototype.CLOSED = 2
  336. /**
  337. * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
  338. *
  339. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
  340. * @api public
  341. */
  342. EventSource.prototype.close = function () {
  343. this._close()
  344. }
  345. /**
  346. * Emulates the W3C Browser based WebSocket interface using addEventListener.
  347. *
  348. * @param {String} type A string representing the event type to listen out for
  349. * @param {Function} listener callback
  350. * @see https://developer.mozilla.org/en/DOM/element.addEventListener
  351. * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
  352. * @api public
  353. */
  354. EventSource.prototype.addEventListener = function addEventListener (type, listener) {
  355. if (typeof listener === 'function') {
  356. // store a reference so we can return the original function again
  357. listener._listener = listener
  358. this.on(type, listener)
  359. }
  360. }
  361. /**
  362. * Emulates the W3C Browser based WebSocket interface using dispatchEvent.
  363. *
  364. * @param {Event} event An event to be dispatched
  365. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
  366. * @api public
  367. */
  368. EventSource.prototype.dispatchEvent = function dispatchEvent (event) {
  369. if (!event.type) {
  370. throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
  371. }
  372. // if event is instance of an CustomEvent (or has 'details' property),
  373. // send the detail object as the payload for the event
  374. this.emit(event.type, event.detail)
  375. }
  376. /**
  377. * Emulates the W3C Browser based WebSocket interface using removeEventListener.
  378. *
  379. * @param {String} type A string representing the event type to remove
  380. * @param {Function} listener callback
  381. * @see https://developer.mozilla.org/en/DOM/element.removeEventListener
  382. * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
  383. * @api public
  384. */
  385. EventSource.prototype.removeEventListener = function removeEventListener (type, listener) {
  386. if (typeof listener === 'function') {
  387. listener._listener = undefined
  388. this.removeListener(type, listener)
  389. }
  390. }
  391. /**
  392. * W3C Event
  393. *
  394. * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
  395. * @api private
  396. */
  397. function Event (type, optionalProperties) {
  398. Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  399. if (optionalProperties) {
  400. for (var f in optionalProperties) {
  401. if (optionalProperties.hasOwnProperty(f)) {
  402. Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * W3C MessageEvent
  409. *
  410. * @see http://www.w3.org/TR/webmessaging/#event-definitions
  411. * @api private
  412. */
  413. function MessageEvent (type, eventInitDict) {
  414. Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
  415. for (var f in eventInitDict) {
  416. if (eventInitDict.hasOwnProperty(f)) {
  417. Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })
  418. }
  419. }
  420. }
  421. /**
  422. * Returns a new object of headers that does not include any authorization and cookie headers
  423. *
  424. * @param {Object} headers An object of headers ({[headerName]: headerValue})
  425. * @return {Object} a new object of headers
  426. * @api private
  427. */
  428. function removeUnsafeHeaders (headers) {
  429. var safe = {}
  430. for (var key in headers) {
  431. if (reUnsafeHeader.test(key)) {
  432. continue
  433. }
  434. safe[key] = headers[key]
  435. }
  436. return safe
  437. }