209 lines
4.7 KiB
TypeScript
Raw Normal View History

2017-07-13 15:56:14 +00:00
// pack:ignore
2017-07-14 02:58:21 +00:00
const CACHE = "v-1"
const RELOADS = new Map<string, Promise<Response>>()
const ETAGS = new Map<string, string>()
2017-07-14 23:53:08 +00:00
const CACHEREFRESH = new Map<string, Promise<void>>()
2017-07-13 18:45:16 +00:00
2017-07-14 21:50:34 +00:00
self.addEventListener("install", (evt: InstallEvent) => {
2017-07-14 02:58:21 +00:00
console.log("Service worker install")
2017-07-13 22:11:25 +00:00
evt.waitUntil(
(self as any).skipWaiting().then(() => {
return installCache()
})
)
2017-07-13 18:45:16 +00:00
})
self.addEventListener("activate", (evt: any) => {
2017-07-14 02:58:21 +00:00
console.log("Service worker activate")
2017-07-14 23:32:06 +00:00
// Delete old cache
let cacheWhitelist = [CACHE]
let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key)
}
}))
})
let immediateClaim = (self as any).clients.claim()
// Immediate claim
2017-07-13 22:11:25 +00:00
evt.waitUntil(
2017-07-14 23:32:06 +00:00
Promise.all([
deleteOldCache,
immediateClaim
])
2017-07-13 22:11:25 +00:00
)
2017-07-13 18:45:16 +00:00
})
2017-07-14 02:58:21 +00:00
// controlling service worker
self.addEventListener("message", (evt: any) => {
let message = JSON.parse(evt.data)
let url = message.url
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
if(!refresh || !servedETag) {
return
}
evt.waitUntil(
refresh.then((response: Response) => {
// If the fresh copy was used to serve the request instead of the cache,
2017-07-14 21:50:34 +00:00
// we don"t need to tell the client to do a refresh.
2017-07-14 02:58:21 +00:00
if(response.bodyUsed) {
return
}
let eTag = response.headers.get("ETag")
if(eTag === servedETag) {
return
}
ETAGS.set(url, eTag)
let message = {
type: "new content",
url
}
2017-07-15 15:07:24 +00:00
// If a subpage has refreshed, refresh the main page cache, too.
2017-07-15 16:51:25 +00:00
// if(url.includes("/_/")) {
2017-07-15 15:07:24 +00:00
2017-07-15 16:51:25 +00:00
// }
2017-07-15 15:07:24 +00:00
2017-07-14 23:53:08 +00:00
let cacheRefresh = CACHEREFRESH.get(url)
if(!cacheRefresh) {
return evt.source.postMessage(JSON.stringify(message))
}
return cacheRefresh.then(() => {
evt.source.postMessage(JSON.stringify(message))
})
2017-07-14 02:58:21 +00:00
})
)
})
2017-07-14 21:50:34 +00:00
self.addEventListener("fetch", async (evt: FetchEvent) => {
2017-07-15 15:07:24 +00:00
let request = evt.request as Request
2017-07-13 22:11:25 +00:00
let isAuth = request.url.includes("/auth/") || request.url.includes("/logout")
2017-07-17 01:14:05 +00:00
let ignoreCache = request.url.includes("/api/") || request.url.includes("/paypal/") || request.url.includes("chrome-extension")
2017-07-13 18:45:16 +00:00
2017-07-13 22:11:25 +00:00
// Delete existing cache on authentication
if(isAuth) {
caches.delete(CACHE)
}
2017-07-13 18:45:16 +00:00
// Do not use cache in some cases
2017-07-14 21:50:34 +00:00
if(request.method !== "GET" || isAuth || ignoreCache) {
2017-07-13 18:45:16 +00:00
return evt.waitUntil(evt.respondWith(fetch(request)))
}
2017-07-13 22:11:25 +00:00
2017-07-14 02:58:21 +00:00
let servedETag = undefined
2017-07-13 18:45:16 +00:00
// Start fetching the request
let refresh = fetch(request).then(response => {
let clone = response.clone()
// Save the new version of the resource in the cache
2017-07-14 23:53:08 +00:00
let cacheRefresh = caches.open(CACHE).then(cache => {
2017-07-13 22:11:25 +00:00
return cache.put(request, clone)
2017-07-13 18:45:16 +00:00
})
2017-07-14 23:53:08 +00:00
CACHEREFRESH.set(request.url, cacheRefresh)
2017-07-13 18:45:16 +00:00
return response
})
2017-07-14 02:58:21 +00:00
// Save in map
RELOADS.set(request.url, refresh)
2017-07-13 22:11:25 +00:00
// Forced reload
if(request.headers.get("X-Reload") === "true") {
return evt.waitUntil(refresh)
}
2017-07-13 18:45:16 +00:00
// Try to serve cache first and fall back to network response
2017-07-13 22:11:25 +00:00
let networkOrCache = fromCache(request).then(response => {
2017-07-14 02:58:21 +00:00
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
2017-07-13 22:11:25 +00:00
return response
}).catch(error => {
// console.log("Cache MISS:", request.url)
2017-07-13 18:45:16 +00:00
return refresh
})
return evt.waitUntil(evt.respondWith(networkOrCache))
})
2017-07-14 21:50:34 +00:00
self.addEventListener("push", (evt: PushEvent) => {
2017-07-14 23:32:06 +00:00
var payload = evt.data ? evt.data.json() : {}
2017-07-14 21:50:34 +00:00
evt.waitUntil(
2017-07-14 23:32:06 +00:00
(self as any).registration.showNotification(payload.title, {
body: payload.message,
icon: payload.icon,
2017-07-15 00:32:54 +00:00
image: payload.image,
data: payload.link
2017-07-14 21:50:34 +00:00
})
)
})
self.addEventListener("pushsubscriptionchange", (evt: any) => {
console.log("pushsubscriptionchange", evt)
})
self.addEventListener("notificationclick", (evt: NotificationEvent) => {
2017-07-15 00:32:54 +00:00
let notification = evt.notification
notification.close()
2017-07-14 21:50:34 +00:00
evt.waitUntil(
(self as any).clients.matchAll().then(function(clientList) {
2017-07-15 00:32:54 +00:00
// If we have a link, use that link to open a new window.
let url = notification.data
if(url) {
return (self as any).clients.openWindow(url)
}
2017-07-14 21:50:34 +00:00
// If there is at least one client, focus it.
if(clientList.length > 0) {
return clientList[0].focus()
}
// Otherwise open a new window
return (self as any).clients.openWindow("https://notify.moe")
})
)
})
2017-07-13 18:45:16 +00:00
function installCache() {
return caches.open(CACHE).then(cache => {
return cache.addAll([
"./",
"./scripts",
"https://fonts.gstatic.com/s/ubuntu/v10/2Q-AW1e_taO6pHwMXcXW5w.ttf"
])
})
}
function fromCache(request) {
return caches.open(CACHE).then(cache => {
return cache.match(request).then(matching => {
if(matching) {
2017-07-13 22:11:25 +00:00
// console.log("Cache HIT:", request.url)
2017-07-13 18:45:16 +00:00
return Promise.resolve(matching)
}
return Promise.reject("no-match")
})
})
}