2021-05-12 20:36:53 +02:00
|
|
|
import {joinPaths} from '../utils.js';
|
|
|
|
|
|
|
|
const {UseServiceWorker, AppSubUrl, AssetUrlPrefix, AppVer} = window.config;
|
2020-05-24 09:36:40 +02:00
|
|
|
const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script
|
2021-05-12 20:36:53 +02:00
|
|
|
const workerAssetPath = joinPaths(AssetUrlPrefix, 'serviceworker.js');
|
2020-05-22 03:45:34 +02:00
|
|
|
|
2021-05-12 20:36:53 +02:00
|
|
|
async function unregisterAll() {
|
|
|
|
for (const registration of await navigator.serviceWorker.getRegistrations()) {
|
|
|
|
if (registration.active) await registration.unregister();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function unregisterOtherWorkers() {
|
|
|
|
for (const registration of await navigator.serviceWorker.getRegistrations()) {
|
|
|
|
const scriptURL = registration.active?.scriptURL || '';
|
|
|
|
if (!scriptURL.endsWith(workerAssetPath)) await registration.unregister();
|
|
|
|
}
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function invalidateCache() {
|
2021-05-12 20:36:53 +02:00
|
|
|
for (const key of await caches.keys()) {
|
|
|
|
if (key.startsWith(cachePrefix)) caches.delete(key);
|
|
|
|
}
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function checkCacheValidity() {
|
|
|
|
const cacheKey = AppVer;
|
|
|
|
const storedCacheKey = localStorage.getItem('staticCacheKey');
|
|
|
|
|
|
|
|
// invalidate cache if it belongs to a different gitea version
|
|
|
|
if (cacheKey && storedCacheKey !== cacheKey) {
|
2020-05-24 09:36:40 +02:00
|
|
|
await invalidateCache();
|
2020-05-22 03:45:34 +02:00
|
|
|
localStorage.setItem('staticCacheKey', cacheKey);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async function initServiceWorker() {
|
|
|
|
if (!('serviceWorker' in navigator)) return;
|
|
|
|
|
|
|
|
if (UseServiceWorker) {
|
2021-05-12 20:36:53 +02:00
|
|
|
// unregister all service workers where scriptURL does not match the current one
|
|
|
|
await unregisterOtherWorkers();
|
2020-05-22 03:45:34 +02:00
|
|
|
try {
|
2021-05-08 16:27:25 +02:00
|
|
|
// normally we'd serve the service worker as a static asset from AssetUrlPrefix but
|
2020-05-24 09:36:40 +02:00
|
|
|
// the spec strictly requires it to be same-origin so it has to be AppSubUrl to work
|
2021-05-12 20:36:53 +02:00
|
|
|
await checkCacheValidity();
|
|
|
|
await navigator.serviceWorker.register(joinPaths(AppSubUrl, workerAssetPath));
|
2020-05-22 03:45:34 +02:00
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
2021-05-12 20:36:53 +02:00
|
|
|
await invalidateCache();
|
|
|
|
await unregisterAll();
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
} else {
|
2021-05-12 20:36:53 +02:00
|
|
|
await invalidateCache();
|
|
|
|
await unregisterAll();
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
}
|