9baee888af
Just cleans up some code, doesn't change the underlying mechanism ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. ## Documentation / Examples - [ ] Make sure the linting passes
66 lines
1.3 KiB
JavaScript
66 lines
1.3 KiB
JavaScript
const eventCallbacks = []
|
|
|
|
function EventSourceWrapper(options) {
|
|
var source
|
|
var lastActivity = new Date()
|
|
var listeners = []
|
|
|
|
if (!options.timeout) {
|
|
options.timeout = 20 * 1000
|
|
}
|
|
|
|
init()
|
|
var timer = setInterval(function () {
|
|
if (new Date() - lastActivity > options.timeout) {
|
|
handleDisconnect()
|
|
}
|
|
}, options.timeout / 2)
|
|
|
|
function init() {
|
|
source = new window.EventSource(options.path)
|
|
source.onopen = handleOnline
|
|
source.onerror = handleDisconnect
|
|
source.onmessage = handleMessage
|
|
}
|
|
|
|
function handleOnline() {
|
|
if (options.log) console.log('[HMR] connected')
|
|
lastActivity = new Date()
|
|
}
|
|
|
|
function handleMessage(event) {
|
|
lastActivity = new Date()
|
|
for (var i = 0; i < listeners.length; i++) {
|
|
listeners[i](event)
|
|
}
|
|
|
|
eventCallbacks.forEach((cb) => {
|
|
if (!cb.unfiltered && event.data.indexOf('action') === -1) return
|
|
cb(event)
|
|
})
|
|
}
|
|
|
|
function handleDisconnect() {
|
|
clearInterval(timer)
|
|
source.close()
|
|
setTimeout(init, options.timeout)
|
|
}
|
|
|
|
return {
|
|
close: () => {
|
|
clearInterval(timer)
|
|
source.close()
|
|
},
|
|
addMessageListener: function (fn) {
|
|
listeners.push(fn)
|
|
},
|
|
}
|
|
}
|
|
|
|
export function addMessageListener(cb) {
|
|
eventCallbacks.push(cb)
|
|
}
|
|
|
|
export function getEventSourceWrapper(options) {
|
|
return EventSourceWrapper(options)
|
|
}
|