From e5bae08d518ea76bc65db7bba4e0f919bb2d5e5f Mon Sep 17 00:00:00 2001 From: Dan Fabulich Date: Sat, 27 Nov 2021 00:37:48 -0800 Subject: [PATCH] Generate a service worker Fixes #6 --- .gitignore | 2 ++ index.html | 14 ++++++++ tools/generate-service-worker.mjs | 57 +++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100755 tools/generate-service-worker.mjs diff --git a/.gitignore b/.gitignore index 150fac23..ce21a2d2 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ dist/inform7/Parchment dist/lectrote node_modules +serviceworker.js + package-lock.json /*.js diff --git a/index.html b/index.html index a8f8eddf..c3f2ece8 100644 --- a/index.html +++ b/index.html @@ -7,6 +7,20 @@ + diff --git a/tools/generate-service-worker.mjs b/tools/generate-service-worker.mjs new file mode 100755 index 00000000..e5711433 --- /dev/null +++ b/tools/generate-service-worker.mjs @@ -0,0 +1,57 @@ +#!/usr/bin/env node + +import {readdir, writeFile} from 'fs/promises'; + +const cacheKey = Date.now(); +const files = await readdir('dist/web'); + +const code = ` +const CACHE_NAME="${cacheKey}"; +const urls = [".", ${files.map(file => `"dist/web/${file}"`).join(',')}]; + +self.addEventListener('install', function(event) { + event.waitUntil( + caches.open(CACHE_NAME) + .then(function(cache) { + return cache.addAll(urls); + }).then(() => console.log("[ServiceWorker] installed, possibly waiting")) + ); +}); + +self.addEventListener('fetch', function(event) { + event.respondWith((async () => { + if (event.request.mode === "navigate" && + event.request.method === "GET" && + registration.waiting && + (await clients.matchAll()).length < 2 + ) { + registration.waiting.postMessage('skipWaiting'); + console.log("[ServiceWorker] refreshing and skipping waiting"); + return new Response("", {headers: {"Refresh": "0"}}); + } + return await caches.match(event.request) || + fetch(event.request); + })()); +}); + +self.addEventListener('activate', function(e) { + console.log('[ServiceWorker] Activate'); + e.waitUntil( + caches.keys().then(keyList => Promise.all(keyList.map(key => { + if (key !== CACHE_NAME) { + console.log("[ServiceWorker] deleting", key); + return caches.delete(key); + } + }))) + ); +}); + +self.addEventListener('message', event => { + if (event.data === 'skipWaiting') { + console.log("[ServiceWorker]", CACHE_NAME, 'skipWaiting'); + skipWaiting(); + } +}); +`; + +await writeFile('serviceworker.js', code, 'utf8');