Files
2026-04-30 13:50:11 +09:00

85 lines
2.3 KiB
JavaScript
Executable File

// StemEngine Service Worker
// Conservative offline strategy:
// - precache shell assets
// - network-first for navigations
// - stale-while-revalidate for same-origin static assets
// - never cache API responses as durable truth
const CACHE_VERSION = '2026-04-30-v1'
const SHELL_CACHE = `stemengine-shell-${CACHE_VERSION}`
const STATIC_CACHE = `stemengine-static-${CACHE_VERSION}`
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg']
self.addEventListener('message', (event) => {
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting()
}
})
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL))
)
})
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((k) => k.startsWith('stemengine-shell-') || k.startsWith('stemengine-static-'))
.filter((k) => k !== SHELL_CACHE && k !== STATIC_CACHE)
.map((k) => caches.delete(k))
)
).then(() => self.clients.claim())
)
})
self.addEventListener('fetch', (event) => {
const { request } = event
const url = new URL(request.url)
const isSameOrigin = url.origin === self.location.origin
// Let API calls and non-GET requests go straight to the network
if (request.method !== 'GET' || url.pathname.startsWith('/api/')) {
event.respondWith(fetch(request))
return
}
// For navigation requests: network-first, fall back to cached shell
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
if (response.ok) {
const clone = response.clone()
caches.open(SHELL_CACHE).then((cache) => cache.put('/', clone))
}
return response
})
.catch(() => caches.match('/'))
)
return
}
if (!isSameOrigin) {
event.respondWith(fetch(request))
return
}
// For same-origin static assets: stale-while-revalidate
event.respondWith(
caches.match(request).then((cached) => {
const networkFetch = fetch(request).then((response) => {
if (response.ok) {
const clone = response.clone()
caches.open(STATIC_CACHE).then((cache) => cache.put(request, clone))
}
return response
})
return cached || networkFetch
})
)
})