2019-11-11 04:24:53 +01:00
|
|
|
/* global location */
|
2019-02-28 18:31:31 +01:00
|
|
|
|
2020-03-29 18:56:34 +02:00
|
|
|
import fetch from 'next/dist/build/polyfills/unfetch'
|
2019-06-05 20:15:42 +02:00
|
|
|
import { getEventSourceWrapper } from './error-overlay/eventsource'
|
2019-02-28 18:31:31 +01:00
|
|
|
|
|
|
|
let evtSource
|
|
|
|
export let currentPage
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
export function closePing() {
|
2019-03-02 23:51:14 +01:00
|
|
|
if (evtSource) evtSource.close()
|
2019-04-21 22:51:09 +02:00
|
|
|
evtSource = null
|
2019-03-02 23:51:14 +01:00
|
|
|
}
|
|
|
|
|
2019-11-11 04:24:53 +01:00
|
|
|
export function setupPing(assetPrefix, pathnameFn, retry) {
|
2019-02-28 18:31:31 +01:00
|
|
|
const pathname = pathnameFn()
|
|
|
|
|
|
|
|
// Make sure to only create new EventSource request if page has changed
|
|
|
|
if (pathname === currentPage && !retry) return
|
|
|
|
currentPage = pathname
|
2019-03-02 23:51:14 +01:00
|
|
|
// close current EventSource connection
|
|
|
|
closePing()
|
2019-02-28 18:31:31 +01:00
|
|
|
|
2019-04-21 22:51:09 +02:00
|
|
|
const url = `${assetPrefix}/_next/webpack-hmr?page=${currentPage}`
|
|
|
|
evtSource = getEventSourceWrapper({ path: url, timeout: 5000, ondemand: 1 })
|
2019-02-28 18:31:31 +01:00
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
evtSource.addMessageListener((event) => {
|
2019-04-21 22:51:09 +02:00
|
|
|
if (event.data.indexOf('{') === -1) return
|
2019-02-28 18:31:31 +01:00
|
|
|
try {
|
|
|
|
const payload = JSON.parse(event.data)
|
|
|
|
if (payload.invalid) {
|
|
|
|
// Payload can be invalid even if the page does not exist.
|
|
|
|
// So, we need to make sure it exists before reloading.
|
|
|
|
fetch(location.href, {
|
2019-11-11 04:24:53 +01:00
|
|
|
credentials: 'same-origin',
|
2020-05-18 21:24:37 +02:00
|
|
|
}).then((pageRes) => {
|
2019-02-28 18:31:31 +01:00
|
|
|
if (pageRes.status === 200) {
|
|
|
|
location.reload()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.error('on-demand-entries failed to parse response', err)
|
|
|
|
}
|
2019-04-21 22:51:09 +02:00
|
|
|
})
|
2019-02-28 18:31:31 +01:00
|
|
|
}
|