-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
328 lines (288 loc) · 9.98 KB
/
service-worker.js
File metadata and controls
328 lines (288 loc) · 9.98 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Bump this value on every production deploy.
// The cache name is derived from this constant so it updates automatically.
const CACHE_VERSION = 'v44';
const CACHE_PREFIX = 'ycopy-static';
const CACHE_NAME = `${CACHE_PREFIX}-${CACHE_VERSION}`;
// Core app shell assets needed for first paint/offline boot.
const CORE_ASSETS = [
'.',
'index.html',
'share.html',
'styles.css',
'app.js',
'fuse.min.js',
'manifest.json',
'icon.svg',
];
const DB_NAME = 'clip-vault';
const STORE = 'items';
const DB_VERSION = 1;
const MIME_TYPE_FILE_EXTENSIONS = Object.freeze({
'application/msword': 'doc',
'application/pdf': 'pdf',
'application/rtf': 'rtf',
'application/vnd.ms-excel': 'xls',
'application/vnd.ms-powerpoint': 'ppt',
'application/vnd.oasis.opendocument.presentation': 'odp',
'application/vnd.oasis.opendocument.spreadsheet': 'ods',
'application/vnd.oasis.opendocument.text': 'odt',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'text/csv': 'csv',
'text/plain': 'txt',
});
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
// Pre-cache core assets for reliable startup.
const cache = await caches.open(CACHE_NAME);
await cache.addAll(CORE_ASSETS.map((asset) => new Request(asset, { cache: 'reload' })));
// Activate the new worker as soon as install completes.
await self.skipWaiting();
})());
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
// Remove all prior app caches so users do not keep stale bundles.
const keys = await caches.keys();
const oldKeys = keys.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME);
await Promise.all(oldKeys.map((key) => caches.delete(key)));
// Start controlling all open tabs immediately.
await self.clients.claim();
})());
});
function openDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(STORE)) {
db.createObjectStore(STORE, { keyPath: 'id', autoIncrement: true });
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function normalizeShareUrlCandidate(value = '') {
const raw = value?.toString().trim();
if (!raw) return '';
let candidate = raw;
candidate = candidate.replace(/^<+/, '').replace(/>+$/, '');
candidate = candidate.replace(/^"+/, '').replace(/"+$/, '');
candidate = candidate.replace(/^'+/, '').replace(/'+$/, '');
candidate = candidate.replace(/[)\]}>'".,!?;:]+$/g, '');
if (/^www\./i.test(candidate)) {
candidate = `https://${candidate}`;
}
try {
const parsed = new URL(candidate);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return '';
return parsed.toString();
} catch {
return '';
}
}
function normalizeStoredText(value = '') {
return value?.toString().trim() || '';
}
function normalizeStoredUrl(value = '') {
return value?.toString().trim() || '';
}
function normalizeStoredFiles(value) {
return Array.isArray(value) ? value.filter(Boolean) : [];
}
function fileNameHasExtension(name = '') {
const trimmedName = name.toString().trim();
if (!trimmedName) return false;
const lastDot = trimmedName.lastIndexOf('.');
return lastDot > 0 && lastDot < trimmedName.length - 1;
}
function appendExtensionFromMimeType(name = '', mimeType = '') {
const normalizedName = name.toString().trim() || 'attachment';
if (fileNameHasExtension(normalizedName)) return normalizedName;
const normalizedMimeType = mimeType.toString().trim().toLowerCase();
const extension = MIME_TYPE_FILE_EXTENSIONS[normalizedMimeType];
if (!extension) return normalizedName;
const baseName = normalizedName.replace(/\.+$/g, '') || 'attachment';
return `${baseName}.${extension}`;
}
function getFileDedupSignature(file = {}) {
const blobSize = Number.isFinite(file?.blob?.size) ? file.blob.size : null;
const rawSize = Number.isFinite(file?.size) ? file.size : null;
return JSON.stringify([
file?.name || '',
file?.type || '',
blobSize ?? rawSize ?? 0,
]);
}
function getItemDedupSignature(item = {}) {
return JSON.stringify([
normalizeStoredText(item.text),
normalizeStoredUrl(item.url),
normalizeStoredFiles(item.files).map(getFileDedupSignature),
]);
}
async function saveShare(formData) {
let text = formData.get('text')?.toString().trim() || '';
let url = normalizeShareUrlCandidate(formData.get('url')?.toString().trim() || '');
// Only promote text -> url when the shared text is only a URL.
if (!url && text) {
const detectedUrl = normalizeShareUrlCandidate(text);
if (detectedUrl) {
url = detectedUrl;
text = '';
}
} else if (url && text === url) {
text = '';
}
const files = formData.getAll('files').map((file) => ({
name: appendExtensionFromMimeType(file.name, file.type),
type: file.type,
blob: file,
}));
const normalizedItem = {
text: normalizeStoredText(text),
url: normalizeStoredUrl(url),
files: normalizeStoredFiles(files),
};
const incomingSignature = getItemDedupSignature(normalizedItem);
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
const store = tx.objectStore(STORE);
const existingRequest = store.getAll();
let settled = false;
const rejectOnce = (error) => {
if (settled) return;
settled = true;
reject(error);
};
const resolveOnce = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
existingRequest.onsuccess = () => {
const existingItems = existingRequest.result || [];
const existing = existingItems.find((savedItem) => getItemDedupSignature(savedItem) === incomingSignature);
const now = Date.now();
if (existing) {
const updatedItem = {
...existing,
text: normalizedItem.text,
url: normalizedItem.url,
files: normalizedItem.files,
createdAt: now,
};
if (Number.isFinite(existing.pinnedAt) && existing.pinnedAt > 0) {
updatedItem.pinnedAt = now;
}
const putRequest = store.put(updatedItem);
putRequest.onsuccess = () => {
resolveOnce({
id: Number(existing.id),
createdAt: now,
});
};
putRequest.onerror = () => rejectOnce(putRequest.error || tx.error);
return;
}
const addRequest = store.add({
text: normalizedItem.text,
url: normalizedItem.url,
files: normalizedItem.files,
createdAt: now,
pinnedAt: null,
});
addRequest.onsuccess = () => {
resolveOnce({
id: Number(addRequest.result),
createdAt: now,
});
};
addRequest.onerror = () => rejectOnce(addRequest.error || tx.error);
};
existingRequest.onerror = () => rejectOnce(existingRequest.error || tx.error);
tx.onerror = () => rejectOnce(tx.error);
});
}
function isCacheableResponse(response) {
return Boolean(response) && (response.ok || response.type === 'opaque');
}
function isHtmlRequest(request, url) {
if (request.mode === 'navigate' || request.destination === 'document') {
return true;
}
const accept = request.headers.get('accept') || '';
return accept.includes('text/html') || url.pathname.endsWith('.html');
}
function isStaticAssetRequest(request, url) {
if (request.destination === 'style' || request.destination === 'script') return true;
if (request.destination === 'image' || request.destination === 'font') return true;
return (
url.pathname.endsWith('.css') ||
url.pathname.endsWith('.js') ||
url.pathname.endsWith('.svg') ||
url.pathname.endsWith('.png') ||
url.pathname.endsWith('.jpg') ||
url.pathname.endsWith('.jpeg') ||
url.pathname.endsWith('.webp') ||
url.pathname.endsWith('.gif') ||
url.pathname.endsWith('.ico') ||
url.pathname.endsWith('.woff') ||
url.pathname.endsWith('.woff2')
);
}
async function networkFirst(request) {
const cache = await caches.open(CACHE_NAME);
try {
const response = await fetch(request);
if (isCacheableResponse(response)) {
await cache.put(request, response.clone());
}
return response;
} catch {
const cached = await cache.match(request);
if (cached) return cached;
throw new Error('Network unavailable and no cached response found.');
}
}
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (url.pathname.endsWith('/share.html') && event.request.method === 'POST') {
event.respondWith(
(async () => {
const formData = await event.request.formData();
const savedItem = await saveShare(formData);
const redirectUrl = new URL('index.html', self.registration.scope);
redirectUrl.searchParams.set('shared', '1');
if (Number.isFinite(savedItem?.id)) {
redirectUrl.searchParams.set('sharedId', String(savedItem.id));
}
return Response.redirect(redirectUrl.toString(), 303);
})()
);
return;
}
if (event.request.method !== 'GET') {
return;
}
// Only apply app caching strategies for same-origin requests.
if (url.origin !== self.location.origin) {
return;
}
// Never intercept the SW script request itself.
if (url.pathname.endsWith('/service-worker.js')) {
return;
}
if (isHtmlRequest(event.request, url)) {
// HTML is network-first so deploys are picked up immediately.
event.respondWith(networkFirst(event.request));
return;
}
if (isStaticAssetRequest(event.request, url)) {
// Static assets are network-first to avoid stale bundles after deploy.
event.respondWith(networkFirst(event.request));
}
});