Jacek Kowalski
4 hours ago 6b9278a5d57091fce636dbb640b380cfb990db6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict';
 
const CACHE = 'inventory-v1';
const SHELL = {{ [
    path('inventory'),
    asset('js/inventory.js'),
    asset('css/inventory.css'),
    asset('css/spectre/spectre.min.css'),
]|json_encode(constant('JSON_UNESCAPED_SLASHES'))|raw }};
const SHELL_URLS = new Set(SHELL.map((url) => new URL(url, self.location).href));
 
self.addEventListener('install', (event) => {
    event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()));
});
 
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys()
            .then((keys) => Promise.all(keys.filter((key) => key.startsWith('inventory-') && key !== CACHE).map((key) => caches.delete(key))))
            .then(() => self.clients.claim()),
    );
});
 
self.addEventListener('fetch', (event) => {
    const request = event.request;
    const url = new URL(request.url);
    url.search = '';
 
    // The book list and the uploads are handled by the page itself.
    if (request.method !== 'GET' || !SHELL_URLS.has(url.href)) {
        return;
    }
 
    event.respondWith(
        fetch(request)
            .then((response) => {
                if (response.ok) {
                    const copy = response.clone();
                    caches.open(CACHE).then((cache) => cache.put(url.href, copy));
                }
 
                return response;
            })
            .catch(() => caches.match(url.href).then((cached) => cached || Response.error())),
    );
});