Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
100 lines (91 loc) · 2.51 KB
/
Copy pathsw.js
File metadata and controls
100 lines (91 loc) · 2.51 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
const CACHE_NAME = 'studio-v1.0.0';
const API_HOSTS = new Set([
'openrouter.ai',
'generativelanguage.googleapis.com',
'api.tavily.com'
]);
const urlsToCache = [
'/',
'/index.html',
'/manifest.json'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(urlsToCache);
})
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames =>
Promise.all(
cacheNames
.filter(cacheName => cacheName !== CACHE_NAME)
.map(cacheName => caches.delete(cacheName))
)
).then(() => self.clients.claim())
);
});
self.addEventListener('message', event => {
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;
const requestUrl = new URL(event.request.url);
const isApiRequest = API_HOSTS.has(requestUrl.hostname);
if (isApiRequest) {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
const networkFetch = fetch(event.request)
.then(networkResponse => {
if (networkResponse.ok) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.put(event.request, networkResponse.clone()))
);
}
return networkResponse;
})
.catch(
() =>
cachedResponse ||
new Response('Service unavailable', {
status: 503,
headers: { 'Content-Type': 'text/plain' }
})
);
return cachedResponse || networkFetch;
})
);
return;
}
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
return fetch(event.request).catch(() => {
if (event.request.mode === 'navigate') {
return caches.match('/index.html').then(
cachedPage =>
cachedPage ||
new Response('Offline fallback unavailable', {
status: 503,
headers: { 'Content-Type': 'text/plain' }
})
);
}
return new Response('Network unavailable', {
status: 503,
headers: { 'Content-Type': 'text/plain' }
});
});
})
);
});