You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.3 KiB
JavaScript
62 lines
2.3 KiB
JavaScript
/*
|
|
* SiMS HQ service worker — makes the console installable (PWA) and fast on repeat
|
|
* visits, without pretending to be a fully offline app (it is an online ops console).
|
|
*
|
|
* Strategy, deliberately conservative:
|
|
* - /api and /share are NEVER touched — always straight to the network (live data,
|
|
* auth, the public PDF route). The SW must never cache or stale those.
|
|
* - Navigations (opening a page) are network-first, falling back to the cached app
|
|
* shell so a flaky connection still opens the UI instead of the browser error page.
|
|
* - Hashed static assets (/assets/*, icons) are cache-first: their names change every
|
|
* build, so a cached copy is always the right version and new builds self-populate.
|
|
* - Only GET, same-origin. Everything else falls through to the network.
|
|
*/
|
|
const CACHE = 'sims-hq-v1'
|
|
const SHELL = ['/', '/index.html', '/manifest.webmanifest', '/favicon.svg', '/icon.svg']
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()))
|
|
})
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
.then(() => self.clients.claim()),
|
|
)
|
|
})
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const req = event.request
|
|
if (req.method !== 'GET') return
|
|
const url = new URL(req.url)
|
|
if (url.origin !== self.location.origin) return
|
|
// Never intercept the API or the public share route — always live.
|
|
if (url.pathname.startsWith('/api') || url.pathname.startsWith('/share')) return
|
|
|
|
// App navigations: network-first with a shell fallback.
|
|
if (req.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(req)
|
|
.then((res) => {
|
|
const copy = res.clone()
|
|
caches.open(CACHE).then((c) => c.put('/', copy)).catch(() => {})
|
|
return res
|
|
})
|
|
.catch(() => caches.match('/').then((m) => m || caches.match('/index.html'))),
|
|
)
|
|
return
|
|
}
|
|
|
|
// Static assets: cache-first, then populate.
|
|
event.respondWith(
|
|
caches.match(req).then((hit) => hit || fetch(req).then((res) => {
|
|
if (res.ok && res.type === 'basic') {
|
|
const copy = res.clone()
|
|
caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {})
|
|
}
|
|
return res
|
|
}).catch(() => hit)),
|
|
)
|
|
})
|