-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
254 lines (218 loc) · 7.03 KB
/
Copy pathsw.js
File metadata and controls
254 lines (218 loc) · 7.03 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
// PAUSE SERVICE WORKER - Offline Caching v4.0 (Always-Fresh Network-First)
const CACHE_VERSION = 'v18';
const CACHE_NAME = `pause-cache-${CACHE_VERSION}`;
const RUNTIME_CACHE = `pause-runtime-${CACHE_VERSION}`;
// Files to precache on install (critical app files)
const PRECACHE_FILES = [
'./index.html',
'./app.js',
'./lucide.min.js',
'./manifest.json',
'./icons/pause_icon_192.png',
'./icons/pause_icon_512.png',
'./icons/pause_icon_180.png',
'./icons/favicon.ico',
'./icons/pause_favicon_16.png',
'./icons/pause_favicon_32.png'
];
// CDN resources to cache at runtime
const CDN_CACHE_PATTERNS = [
/^https:\/\/cdn\.tailwindcss\.com/,
/^https:\/\/cdn\.jsdelivr\.net/,
/^https:\/\/unpkg\.com/,
/^https:\/\/cdnjs\.cloudflare\.com/,
/^https:\/\/api\.fontshare\.com/,
/^https:\/\/fonts\.googleapis\.com/,
/^https:\/\/fonts\.gstatic\.com/
];
// ==================== INSTALL ====================
self.addEventListener('install', (e) => {
console.log('[SW] Installing version:', CACHE_VERSION);
e.waitUntil(
(async () => {
try {
const cache = await caches.open(CACHE_NAME);
console.log('[SW] Precaching files...');
// Cache files one by one with error handling
for (const file of PRECACHE_FILES) {
try {
await cache.add(file);
console.log('[SW] ✓ Cached:', file);
} catch (err) {
console.warn('[SW] ✗ Failed to cache:', file, err.message);
}
}
console.log('[SW] Precache complete');
return self.skipWaiting();
} catch (err) {
console.error('[SW] Precache failed:', err);
return self.skipWaiting();
}
})()
);
});
// ==================== ACTIVATE ====================
self.addEventListener('activate', (e) => {
console.log('[SW] Activating version:', CACHE_VERSION);
e.waitUntil(
(async () => {
// Delete old caches
const cacheNames = await caches.keys();
const deletePromises = cacheNames
.filter(name => name !== CACHE_NAME && name !== RUNTIME_CACHE)
.map(name => {
console.log('[SW] Deleting old cache:', name);
return caches.delete(name);
});
await Promise.all(deletePromises);
// Claim all clients immediately
await self.clients.claim();
console.log('[SW] Activation complete');
})()
);
});
// ==================== FETCH STRATEGIES ====================
// Helper: Check if URL should be cached from CDN
function isCDNUrl(url) {
return CDN_CACHE_PATTERNS.some(pattern => pattern.test(url));
}
// Helper: Is this a navigation request?
function isNavigationRequest(request) {
return request.mode === 'navigate' ||
(request.method === 'GET' && request.headers.get('accept')?.includes('text/html'));
}
// Strategy: Cache First with Network Fallback (for static assets)
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) {
return cached;
}
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
await cache.put(request, response.clone());
}
return response;
} catch (err) {
console.error('[SW] Fetch failed:', request.url, err);
throw err;
}
}
// Strategy: Network First with Cache Fallback (for HTML pages & dynamic scripts)
async function networkFirst(request) {
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
await cache.put(request, response.clone());
}
return response;
} catch (err) {
console.log('[SW] Network failed, trying cache:', request.url);
const cached = await caches.match(request);
if (cached) {
return cached;
}
// Return offline page for navigation requests
if (isNavigationRequest(request)) {
const offlinePage = await caches.match('./index.html');
if (offlinePage) return offlinePage;
}
throw err;
}
}
// Strategy: Stale While Revalidate (for CDN resources)
async function staleWhileRevalidate(request) {
const cache = await caches.open(RUNTIME_CACHE);
const cached = await cache.match(request);
const fetchPromise = fetch(request)
.then(async response => {
if (response.ok) {
await cache.put(request, response.clone());
}
return response;
})
.catch(err => {
console.log('[SW] CDN fetch failed:', request.url);
return cached;
});
return cached || fetchPromise;
}
// ==================== MAIN FETCH HANDLER ====================
self.addEventListener('fetch', (e) => {
try {
const url = new URL(e.request.url);
// Skip non-GET requests
if (e.request.method !== 'GET') {
return;
}
// Skip chrome-extension and other non-http(s) requests
if (!url.protocol.startsWith('http')) {
return;
}
// Skip cross-origin requests that aren't CDN
if (url.origin !== location.origin && !isCDNUrl(url.href)) {
return;
}
// Navigation requests (HTML pages) - Network First
if (isNavigationRequest(e.request)) {
e.respondWith(networkFirst(e.request));
return;
}
// Local code files (HTML, JS, CSS) - Network First for instant code updates
if (url.origin === location.origin) {
if (url.pathname.endsWith('.js') || url.pathname.endsWith('.html') || url.pathname.endsWith('.css') || url.pathname === '/') {
e.respondWith(networkFirst(e.request));
return;
}
e.respondWith(cacheFirst(e.request));
return;
}
// CDN resources - Stale While Revalidate
if (isCDNUrl(url.href)) {
e.respondWith(staleWhileRevalidate(e.request));
return;
}
// External requests - Network First with cache fallback
e.respondWith(networkFirst(e.request));
} catch (err) {
console.error('[SW] Fetch handler error:', err);
}
});
// ==================== MESSAGE HANDLER ====================
self.addEventListener('message', (e) => {
if (e.data && e.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (e.data && e.data.type === 'GET_CACHE_STATUS') {
caches.keys().then(names => {
// Check if our cache exists
const hasCache = names.includes(CACHE_NAME);
const hasRuntimeCache = names.includes(RUNTIME_CACHE);
if (e.ports && e.ports[0]) {
e.ports[0].postMessage({
version: CACHE_VERSION,
caches: names,
ready: hasCache && hasRuntimeCache
});
}
}).catch(err => {
console.error('[SW] Error getting cache status:', err);
});
}
if (e.data && e.data.type === 'CLEAR_CACHES') {
caches.keys().then(names => {
names.forEach(name => caches.delete(name));
console.log('[SW] All caches cleared');
});
}
});
// ==================== ERROR HANDLING ====================
self.addEventListener('error', (e) => {
console.error('[SW] Error:', e.error);
});
self.addEventListener('unhandledrejection', (e) => {
console.error('[SW] Unhandled rejection:', e.reason);
});
console.log('[SW] Service Worker v' + CACHE_VERSION + ' loaded');