-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
262 lines (238 loc) · 8.27 KB
/
sw.js
File metadata and controls
262 lines (238 loc) · 8.27 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
const CACHE_NAME = 'calendar-method-tracker-v37';
const FONT_CACHE_NAME = 'fonts-v2';
const OFFLINE_FALLBACK_URLS = [
new URL('./index.html', self.location.href).toString(),
new URL('./', self.location.href).toString(),
'./index.html',
'./',
'/'
];
const OFFLINE_CACHE_KEY = OFFLINE_FALLBACK_URLS[0];
const ASSETS_TO_CACHE = [
'./',
'./index.html',
'./script.js',
'./styles.css',
'./responsive-fix.css',
'./manifest.json',
'./icon-192x192.png',
'./icon-512x512.png'
];
const FONTS_TO_CACHE = [
'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap',
'https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmSU5fBBc4.woff2',
'https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2'
];
// Install event - cache all assets
self.addEventListener('install', (event) => {
console.log('[SW] Installing service worker...');
event.waitUntil(
Promise.all([
// Cache main assets
caches.open(CACHE_NAME).then(async (cache) => {
console.log('[SW] Caching app assets');
await cache.addAll(ASSETS_TO_CACHE);
const offlineResponse = await cache.match('./index.html', { ignoreSearch: true });
if (offlineResponse) {
await Promise.all(
OFFLINE_FALLBACK_URLS.map(async (url) => {
const request = new Request(url, { cache: 'reload' });
await cache.put(request, offlineResponse.clone());
})
);
} else {
console.warn('[SW] Unable to seed offline fallbacks; index not cached yet.');
}
}),
// Cache fonts
caches.open(FONT_CACHE_NAME).then((cache) => {
console.log('[SW] Caching fonts');
return cache.addAll(FONTS_TO_CACHE).catch(err => {
console.warn('[SW] Some fonts failed to cache:', err);
// Don't fail installation if fonts fail
return Promise.resolve();
});
})
]).then(() => {
console.log('[SW] Installation complete');
return self.skipWaiting();
})
);
});
// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
console.log('[SW] Activating service worker...');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== CACHE_NAME && cache !== FONT_CACHE_NAME) {
console.log('[SW] Deleting old cache:', cache);
return caches.delete(cache);
}
})
);
}).then(() => {
console.log('[SW] Activation complete');
return self.clients.claim();
})
);
});
// Helper function to fetch with timeout
function fetchWithTimeout(request, timeout = 5000) {
return Promise.race([
fetch(request),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Network timeout')), timeout)
)
]);
}
async function getOfflinePage() {
for (const url of OFFLINE_FALLBACK_URLS) {
const match = await caches.match(url, { ignoreSearch: true });
if (match) {
return match;
}
}
return null;
}
// Fetch event - offline-first strategy with timeout handling
self.addEventListener('fetch', (event) => {
const { request } = event;
// Skip non-GET requests
if (request.method !== 'GET') {
return;
}
// Skip non-http(s) requests
if (!request.url.startsWith('http')) {
return;
}
// Handle favicon requests
if (request.url.endsWith('/favicon.ico')) {
event.respondWith(
caches.match('./icon-192x192.png')
.then(response => response || new Response(null, { status: 204 }))
);
return;
}
// Handle font requests - cache first, then network with timeout
if (request.url.includes('fonts.googleapis.com') || request.url.includes('fonts.gstatic.com')) {
event.respondWith(
caches.match(request, { cacheName: FONT_CACHE_NAME })
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
}
return fetchWithTimeout(request, 5000).then((response) => {
if (response && response.status === 200) {
const responseToCache = response.clone();
caches.open(FONT_CACHE_NAME).then((cache) => {
cache.put(request, responseToCache);
});
}
return response;
}).catch(() => {
// Return empty response if offline and not cached
return new Response('', { status: 200, statusText: 'OK' });
});
})
);
return;
}
// Handle navigation requests (for the app itself)
if (request.mode === 'navigate') {
event.respondWith((async () => {
const offlineResponse = await getOfflinePage();
try {
const networkResponse = await fetchWithTimeout(request, 5000);
if (networkResponse && networkResponse.status === 200) {
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
Promise.all(
OFFLINE_FALLBACK_URLS.map((url) => cache.put(url, responseToCache.clone()))
).catch((err) => console.warn('[SW] Failed to refresh offline fallbacks:', err));
});
}
return networkResponse;
} catch (error) {
if (offlineResponse) {
return offlineResponse;
}
console.warn('[SW] No offline fallback available for navigation:', error);
return new Response('Offline', {
status: 503,
statusText: 'Service Unavailable'
});
}
})());
return;
}
// For all other requests: Cache first, fall back to network with timeout
event.respondWith(
caches.match(request)
.then((cachedResponse) => {
if (cachedResponse) {
// Return cached version and update cache in background with timeout
fetchWithTimeout(request, 5000).then((response) => {
if (response && response.status === 200 && response.type === 'basic') {
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseToCache);
});
}
}).catch(() => {
// Network failed, but we already have cached version
console.log('[SW] Network timeout for:', request.url, '- using cached version');
});
return cachedResponse;
}
// Not in cache, try network with timeout
return fetchWithTimeout(request, 5000).then((response) => {
// Check if valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Cache the new response
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseToCache);
});
return response;
}).catch(() => {
// Network timeout and not in cache, try to return cached version as fallback
console.log('[SW] Network timeout for:', request.url, '- trying fallback cache');
return caches.match(request).then((fallbackResponse) => {
if (fallbackResponse) {
return fallbackResponse;
}
// If we really have nothing, return offline response
console.log('[SW] No cache available for:', request.url);
return new Response('Offline', {
status: 503,
statusText: 'Service Unavailable'
});
});
});
})
.catch(() => {
// Cache check failed, try network with timeout
return fetchWithTimeout(request, 5000).then((response) => {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseToCache);
});
return response;
}).catch(() => {
// Network failed, return offline response
console.log('[SW] Failed to fetch:', request.url);
return new Response('Offline', {
status: 503,
statusText: 'Service Unavailable'
});
});
})
);
});