2019-05-27 22:59:25 +02:00
|
|
|
const eventCallbacks = []
|
2019-04-21 22:51:09 +02:00
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
function EventSourceWrapper(options) {
|
2018-07-24 11:24:40 +02:00
|
|
|
var source
|
|
|
|
var lastActivity = new Date()
|
|
|
|
var listeners = []
|
|
|
|
|
|
|
|
if (!options.timeout) {
|
|
|
|
options.timeout = 20 * 1000
|
|
|
|
}
|
|
|
|
|
|
|
|
init()
|
2019-11-11 04:24:53 +01:00
|
|
|
var timer = setInterval(function() {
|
2019-05-29 13:57:26 +02:00
|
|
|
if (new Date() - lastActivity > options.timeout) {
|
2018-07-24 11:24:40 +02:00
|
|
|
handleDisconnect()
|
|
|
|
}
|
|
|
|
}, options.timeout / 2)
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
function init() {
|
2018-07-24 11:24:40 +02:00
|
|
|
source = new window.EventSource(options.path)
|
|
|
|
source.onopen = handleOnline
|
|
|
|
source.onerror = handleDisconnect
|
|
|
|
source.onmessage = handleMessage
|
|
|
|
}
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
function handleOnline() {
|
2018-07-24 11:24:40 +02:00
|
|
|
if (options.log) console.log('[HMR] connected')
|
|
|
|
lastActivity = new Date()
|
|
|
|
}
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
function handleMessage(event) {
|
2018-07-24 11:24:40 +02:00
|
|
|
lastActivity = new Date()
|
|
|
|
for (var i = 0; i < listeners.length; i++) {
|
|
|
|
listeners[i](event)
|
|
|
|
}
|
2019-05-27 22:59:25 +02:00
|
|
|
if (event.data.indexOf('action') !== -1) {
|
|
|
|
eventCallbacks.forEach(cb => cb(event))
|
2019-04-21 22:51:09 +02:00
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
function handleDisconnect() {
|
2018-07-24 11:24:40 +02:00
|
|
|
clearInterval(timer)
|
|
|
|
source.close()
|
|
|
|
setTimeout(init, options.timeout)
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2019-04-21 22:51:09 +02:00
|
|
|
close: () => {
|
2020-02-19 18:39:22 +01:00
|
|
|
clearInterval(timer)
|
2019-04-21 22:51:09 +02:00
|
|
|
source.close()
|
|
|
|
},
|
2019-11-11 04:24:53 +01:00
|
|
|
addMessageListener: function(fn) {
|
2018-07-24 11:24:40 +02:00
|
|
|
listeners.push(fn)
|
2019-11-11 04:24:53 +01:00
|
|
|
},
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
export function getEventSourceWrapper(options) {
|
2019-04-21 22:51:09 +02:00
|
|
|
if (!options.ondemand) {
|
|
|
|
return {
|
|
|
|
addMessageListener: cb => {
|
2019-05-27 22:59:25 +02:00
|
|
|
eventCallbacks.push(cb)
|
2019-11-11 04:24:53 +01:00
|
|
|
},
|
2019-04-21 22:51:09 +02:00
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
2019-04-21 22:51:09 +02:00
|
|
|
return EventSourceWrapper(options)
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|