avtopost.kultmost.ru/static/service-worker.js

177 lines
5.4 KiB
JavaScript

const CACHE_NAME = 'app-cache-v2.1.4';
const ASSETS_TO_CACHE = [
'/pwa2',
'/icon-192x192.png',
'/icon-512x512.png',
'/offline.html',
'/static/Inter-Bold.woff2',
'/static/Inter-SemiBold.woff2',
'/static/Inter-Regular.woff2',
'/static/painter.svg',
'/static/event1.jpg',
'/static/event2.jpg',
'/static/event3.jpg',
'/static/event4.jpg',
'/static/event5.jpg',
'/static/event6.jpg',
'/static/event7.webp',
];
const MIN_VALID_SIZE = 500;
const NOCACHE_PATHS = [
'/api',
'/form',
'/profile',
'/competitions',
'/competition',
'/exhibitions',
'/exhibition',
'/login',
'/registration'
];
const VALIDATE_ON_MODIFY_PATHS = [
'/artists',
'/partner',
'/news',
'/',
'/pwa',
'/paintings',
];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log('Caching static assets...');
return cache.addAll(ASSETS_TO_CACHE);
})
.then(() => {
console.log('All assets cached successfully.');
return self.skipWaiting();
})
.catch((error) => {
console.error('Failed to cache assets during install:', error);
})
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) {
console.log(`Deleting old cache: ${key}`);
return caches.delete(key);
}
})
)
)
.then(() => {
console.log('Service Worker activated.');
return self.clients.claim();
})
.then(() => {
return self.clients.matchAll().then((clients) => {
clients.forEach((client) =>
client.postMessage({ type: 'SW_UPDATED' })
);
});
})
);
});
self.addEventListener('fetch', (e) => {
if (e.request.method !== 'GET') return;
const url = new URL(e.request.url);
if (NOCACHE_PATHS.some(path =>
url.pathname === path || url.pathname.startsWith(path + '/')
)) {
return;
}
e.respondWith(
(async () => {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await caches.match(e.request);
const shouldValidate = VALIDATE_ON_MODIFY_PATHS.some(path =>
url.pathname === path || url.pathname.startsWith(path + '/')
);
let isCachedTooSmall = false;
if (cachedResponse) {
const contentLength = parseInt(cachedResponse.headers.get('Content-Length') || '0', 10);
isCachedTooSmall = contentLength > 0 && contentLength < MIN_VALID_SIZE;
}
if (cachedResponse && !shouldValidate && !isCachedTooSmall) {
return cachedResponse;
}
try {
const networkResponse = await fetch(e.request);
if (networkResponse && networkResponse.status === 200) {
const responseClone = networkResponse.clone();
let shouldUpdateCache = true;
if (shouldValidate && cachedResponse) {
const [cachedModified, netModified] = await Promise.all([
cachedResponse.headers.get('Last-Modified'),
networkResponse.headers.get('Last-Modified')
]);
const [cachedLen, netLen] = await Promise.all([
cachedResponse.headers.get('Content-Length'),
networkResponse.headers.get('Content-Length')
]);
if (cachedModified === netModified && cachedLen === netLen) {
shouldUpdateCache = false;
console.log(`Content unchanged for ${url.pathname}, keeping cached version`);
}
}
if (isCachedTooSmall) {
console.warn(`Cached file ${url.pathname} was too small (${cachedResponse.headers.get('Content-Length')} bytes). Forcing update.`);
shouldUpdateCache = true;
}
if (shouldUpdateCache) {
console.log(`Caching/updating: ${url.pathname}`);
await cache.put(e.request, responseClone);
}
return networkResponse;
}
if (cachedResponse) return cachedResponse;
throw new Error('Network response was not ok');
} catch (err) {
console.error('Fetch failed:', err);
if (e.request.mode === 'navigate') {
const offlinePage = await caches.match('/offline.html');
if (offlinePage) return offlinePage;
const rootPage = await caches.match('/');
if (rootPage) return rootPage;
}
if (cachedResponse) {
console.warn(`Returning cached response despite small size due to offline state: ${url.pathname}`);
return cachedResponse;
}
throw err;
}
})()
);
});