Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
58 lines (54 loc) · 2.39 KB
/
Copy pathsw.js
File metadata and controls
58 lines (54 loc) · 2.39 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
const CACHE = 'b64pro-v0.4.2';
const ASSETS = [
'./', './index.html', './manifest.json', './icon.svg', './icon-maskable.svg',
'./vendor/fflate-0.8.3.js', './vendor/qrcode-generator-1.4.4.js',
'./screenshots/desktop-wide.png', './screenshots/mobile-narrow.png',
];
const assetUrls = new Set(ASSETS.map(asset => new URL(asset, self.location.href).href));
self.addEventListener('install', event => {
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(ASSETS)).then(() => self.skipWaiting()));
});
self.addEventListener('activate', event => {
event.waitUntil(caches.keys().then(keys => Promise.all(
keys.filter(key => key.startsWith('b64pro-v') && key !== CACHE).map(key => caches.delete(key))
)).then(() => self.clients.claim()));
});
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
const entry = new URL('./index.html', self.location.href);
if (url.origin !== entry.origin) return;
if (event.request.method === 'POST' && url.pathname === entry.pathname && url.searchParams.has('share')) {
event.respondWith((async () => {
const form = await event.request.formData();
const file = form.get('file');
if (file && typeof file !== 'string') {
const cache = await caches.open('b64pro-share');
await cache.put(new URL('./shared-file', self.location.href), new Response(file, {
headers: { 'X-Filename': encodeURIComponent(file.name), 'Content-Type': file.type || 'application/octet-stream' }
}));
entry.searchParams.set('share', 'file');
} else {
const value = form.get('data') || form.get('url') || form.get('title') || '';
entry.searchParams.set('data', String(value));
entry.searchParams.set('mode', 'text');
}
return Response.redirect(entry.href, 303);
})());
return;
}
if (event.request.method !== 'GET') return;
// Query strings can contain user input. Never cache those URLs.
const plain = new URL(url);
plain.search = '';
if (!assetUrls.has(plain.href)) return;
event.respondWith(caches.open(CACHE).then(async cache => {
const cached = await cache.match(plain.href);
if (cached) return cached;
const response = await fetch(plain.href);
if (response.ok) await cache.put(plain.href, response.clone());
return response;
}));
});
self.addEventListener('message', event => {
if (event.data === 'skipWaiting') self.skipWaiting();
});