about summary refs log tree commit diff stats
path: root/src/worker.js
blob: 44ea5b1c8390bbf0034ecaa084a298e6335a52f1 (plain) (blame)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/// <reference lib="webworker" />

/** @type {ServiceWorkerGlobalScope} */
const sw = (/** @type {any} */ (self));

const CACHE_PREFIX = 'epube';

const CACHE_VERSION = BUILD_CACHE_VERSION;
const CACHE_NAME = CACHE_PREFIX + "-" + CACHE_VERSION;
const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS;

// Install: precache all assets from manifest
sw.addEventListener('install', (event) => {
    event.waitUntil(
        (async () => {
            console.log('[worker] install started', CACHE_NAME);

            const cache = await caches.open(CACHE_NAME);

            try {
                // 1. Fetch all assets concurrently with version parameters
                const fetchPromises = MANIFEST_ASSETS.map(async (url) => {
                    const cleanUrl = new URL(url, location.href);

                    // normalize = strip CACHE_VERSION suffix from pathname
                    cleanUrl.pathname = cleanUrl.pathname.replace("_" + CACHE_VERSION, "");

                    // this is our original URL from manifest (with suffix if set)
                    const networkUrl = new URL(url, location.href);

                    const response = await fetch(networkUrl.toString(), { cache: 'reload' });

                    // Emulate cache.addAll behavior: fail if any status is not 200-299
                    if (!response.ok) {
                        throw new Error(`Failed to fetch ${cleanUrl} (Status: ${response.status})`);
                    }

                    return {
                        cleanUrlStr: cleanUrl.toString(),
                        response: response.clone()
                    };
                });

                const results = await Promise.all(fetchPromises);
                await Promise.all(results.map(({ cleanUrlStr, response }) => cache.put(cleanUrlStr, response)));

                console.log('[worker] all assets cached successfully');

                // Only skip waiting if the entire cache was successfully built
                sw.skipWaiting();
            } catch (err) {
                console.error('[worker] Critical precache failed! Critical asset missing:', err);
                // Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe.

                // we need to tell the browser the install failed so it throws away this worker, otherwise it gets stuck in waiting
                throw err;
            }
        })()
    );
});

sw.addEventListener('message', (event) => {
    if (event.data && event.data.type === 'GET_CACHE_NAME') {
        // Respond directly to the specific frontend window/tab that asked
        event.ports[0].postMessage({ cacheName: CACHE_NAME });
    } else if (event.data && event.data.type === 'GET_CACHE_VERSION') {
        // Respond directly to the specific frontend window/tab that asked
        event.ports[0].postMessage({ cacheName: CACHE_VERSION });
    }
});

// Activate: clean up old caches and take control of all pages
sw.addEventListener('activate', (event) => {
    console.log('[worker] activate');

    // Create the async task block
    const activationTask = async () => {
        // await loadConfig();

        const keyList = await caches.keys();
        for (const key of keyList) {
            if (key.includes(CACHE_PREFIX) && key !== CACHE_NAME) {
                /* eslint-disable no-await-in-loop */
                await caches.delete(key);
            }
        }

        await sw.clients.claim();
    };

    // Hand the executed promise directly to the event
    event.waitUntil(activationTask());
});

// Fetch: cache-first for static assets, network-first for API
sw.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // console.log('[fetch]', url);

    // /assets/ belong to android app
    if (url.pathname.startsWith('/assets/')) return;

    // request API endpoints from the network if possible and cache them locally
    if (url.pathname.match('backend.php')) {
        event.respondWith(
            // @ts-ignore-next-line
            (async () => {
                try {
                    const networkResp = await fetch(event.request);

                    if (networkResp.ok) {
                        const cache = await caches.open(CACHE_NAME);
                        await cache.put(networkResp.url, networkResp.clone());
                    }

                    return networkResp;
                } catch (err) {
                    // Network failed, try to get the cached API response
                    const cachedResp = await caches.match(event.request);
                    if (cachedResp) return cachedResp;
                }
            })()
        );
        return;
    }

    // index & read UI: online first; if offline, map index pages to offline.html & map all read.html?* to offline read.html
    if (url.pathname == "/" || url.pathname.match("index.html|offline.html|read.html")) {
        event.respondWith(
            // @ts-ignore-next-line
            (async () => {
                try {
                    const networkResp = await fetch(event.request);

                    if (networkResp.ok) {
                        const cache = await caches.open(CACHE_NAME);
                        await cache.put(networkResp.url, networkResp.clone());
                    }

                    return networkResp;
                } catch (err) {
                    // i.e. read.html?id=1234&b=1234
                    if (url.pathname.includes("read.html")) {
                        return caches.match("read.html");
                    } else {
                        return caches.match('/offline.html');
                    }
                }
            })()
        );

        return;
    }

    // everything else: cache-first with network fallback
    event.respondWith(
        (async () => {
            const cache = await caches.open(CACHE_NAME);
            const cached = await cache.match(event.request);

            if (cached) {
                // if cached, try to update: fire background network check without waiting for it (no await)
                fetch(event.request)
                    .then((networkResp) => {
                        if (networkResp.ok) cache.put(event.request, networkResp.clone());
                    })
                    .catch((e) => console.warn('[worker] Background update failed:', e));

                // Return cached asset immediately
                return cached;
            }

            // Cache miss: fetch from network and cache it
            const networkResp = await fetch(event.request);

            /* if (networkResp.ok) { -- we don't cache all responses
                await cache.put(event.request, networkResp.clone());
            } */

            return networkResp;
        })()
    );
});