Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
452 lines (411 loc) Β· 20.3 KB
/
Copy pathsw.js
File metadata and controls
452 lines (411 loc) Β· 20.3 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// ============================================================
// WorldScript Studio β Advanced Service Worker v3.0
// Strategy: Stale-While-Revalidate + Cache-First + Network-Only
// Features: Versioned caches, background sync, periodic updates,
// offline fallback, push notifications, share target
// ============================================================
// QNBS-v3: version bump auto-synced from package.json by scripts/sync-sw-version.mjs β every CACHE_STATIC/CACHE_DYNAMIC name changes too, so this alone invalidates all prior caches on next activate.
const APP_VERSION = '1.29.7';
const CACHE_STATIC = `worldscript-static-v${APP_VERSION}`;
const CACHE_DYNAMIC = `worldscript-dynamic-v${APP_VERSION}`;
const CACHE_IMAGES = `worldscript-images-v${APP_VERSION}`;
const ALL_CACHES = [CACHE_STATIC, CACHE_DYNAMIC, CACHE_IMAGES];
// QNBS-v3: anchored regex β startsWith('worldscript-static-v') also matched 'worldscript-static-vendor-cache'.
const OWNED_CACHE_NAME_RE = /^worldscript-(?:static|dynamic|images)-v\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;
function isWorldScriptOwnedCache(name) {
return OWNED_CACHE_NAME_RE.test(name);
}
const BASE = self.location.pathname.replace(/sw\.js$/, '');
// QNBS-v3: Detect the Tauri desktop WebView (served from tauri://localhost or https://tauri.localhost).
// Inside Tauri the app is bundled locally and is already offline-first; a Service Worker only
// intercepts navigations and β when its cache is empty β serves the "<APP> ist offline." fallback
// (this exact regression). So under Tauri the SW precaches nothing, never intercepts fetches, and
// self-unregisters on activate so any SW a prior build installed stops hijacking navigation.
const IS_TAURI =
self.location.protocol === 'tauri:' || self.location.hostname === 'tauri.localhost';
const swLogger = {
log: (...args) => self.console.log('[SW]', ...args),
warn: (...args) => self.console.warn('[SW]', ...args),
error: (...args) => self.console.error('[SW]', ...args),
};
// ββ Pre-cache shell assets βββββββββββββββββββββββββββββββββββ
// VitePWA (injectManifest) replaces self.__WB_MANIFEST at build time with
// the full hashed asset list. In dev / standalone mode the array is empty
// and we fall back to the minimal shell URLs below.
// eslint-disable-next-line no-underscore-dangle
const _WB_MANIFEST = self.__WB_MANIFEST || [];
const EXPLICIT_SHELL_URLS = [BASE, `${BASE}index.html`, `${BASE}manifest.json`, `${BASE}favicon.svg`, `${BASE}offline.html`];
// QNBS-v3: keep these files in the injected manifest (their content hash still changes sw.js's own bytes, triggering an update with no version bump) but drop them here so cache.addAll() never sees the same resolved URL twice β tracked against every URL seen so far, not just the explicit list, since two manifest entries could otherwise collide with each other.
const seenResolvedUrls = new Set(EXPLICIT_SHELL_URLS.map((url) => new URL(url, self.location.href).href));
const manifestUrls = _WB_MANIFEST
.map((entry) => (typeof entry === 'string' ? entry : entry.url))
.filter((url) => {
const resolved = new URL(url, self.location.href).href;
if (seenResolvedUrls.has(resolved)) return false;
seenResolvedUrls.add(resolved);
return true;
});
const PRECACHE_URLS = [...EXPLICIT_SHELL_URLS, ...manifestUrls];
// QNBS-v3: marker written into CACHE_STATIC only once precache fully succeeds; activate checks it before pruning an older generation.
const PRECACHE_ADMISSION_URL = `${BASE}__sw-precache-complete__`;
// ββ Max age / entry limits βββββββββββββββββββββββββββββββββββ
const MAX_AGE_DYNAMIC = 7 * 24 * 60 * 60 * 1000; // 7 days
const MAX_AGE_IMAGES = 30 * 24 * 60 * 60 * 1000; // 30 days
const MAX_ENTRIES_DYN = 60;
const MAX_ENTRIES_IMG = 40;
// ββ Stamp a response with a cached-at timestamp ββββββββββββββ
function stampedResponse(response) {
const cloned = response.clone();
const headers = new Headers(cloned.headers);
headers.set('sw-cached-at', Date.now().toString());
return new Response(cloned.body, {
status: cloned.status,
statusText: cloned.statusText,
headers,
});
}
function isExpired(response, maxAge) {
const cachedAt = response?.headers?.get('sw-cached-at');
if (!cachedAt) return false;
return Date.now() - parseInt(cachedAt, 10) > maxAge;
}
// ββ Trim oldest entries when cache exceeds maxEntries ββββββββ
async function trimCache(cacheName, maxEntries) {
const cache = await caches.open(cacheName);
const keys = await cache.keys();
if (keys.length > maxEntries) {
await cache.delete(keys[0]);
return trimCache(cacheName, maxEntries);
}
}
// ββ Offline fallback per resource type βββββββββββββββββββββββ
// QNBS-v3: right after an update the new CACHE_DYNAMIC is empty, but every locale bundle is precached in CACHE_STATIC β fall back to it so going offline after an update never loses translations.
async function cachedLocaleBundle(dynamicCache, request) {
return (
(await dynamicCache.match(request)) ||
(await caches.match(request, { cacheName: CACHE_STATIC }))
);
}
async function offlineFallback(request) {
if (request.destination === 'document') {
// QNBS-v3: scoped to CACHE_STATIC (where offline.html is precached) β an unscoped caches.match() searches every cache on the shared qnbs.github.io origin, not just this app's own.
const cached = await caches.match(`${BASE}offline.html`, { cacheName: CACHE_STATIC });
return cached || new Response('<!doctype html><title>Offline</title><p>WorldScript Studio ist offline.</p>', {
headers: { 'Content-Type': 'text/html' },
status: 503,
});
}
if (request.destination === 'image') {
return new Response(
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect width="200" height="200" fill="#1e293b"/>
<text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle"
fill="#64748b" font-family="sans-serif" font-size="14">Offline</text>
</svg>`,
{ headers: { 'Content-Type': 'image/svg+xml' } }
);
}
return new Response('', { status: 408 });
}
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// INSTALL β Precache shell
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('install', (event) => {
// QNBS-v3: Never precache inside Tauri β the desktop app serves its shell from the bundle.
if (IS_TAURI) {
self.skipWaiting();
return;
}
event.waitUntil(
caches.open(CACHE_STATIC)
.then((cache) => cache.addAll(PRECACHE_URLS).then(() => cache.put(PRECACHE_ADMISSION_URL, new Response('ok'))))
.then(() => {
// QNBS-v3: only claim the update once precache fully succeeded; register-sw.ts owns the pre-reload flush mitigation for the resulting reload.
self.skipWaiting();
})
.catch((err) => {
// QNBS-v3: rethrow so install() itself fails β a worker that never reaches "installed" can never be waited-on, activated, or SKIP_WAITING'd.
swLogger.warn('Precache failed β this installation will not complete:', err);
throw err;
})
);
});
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ACTIVATE β Prune stale caches, claim all clients
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('activate', (event) => {
// QNBS-v3: Self-destruct inside Tauri β wipe every cache and unregister this SW so a previously
// installed worker stops intercepting navigation and serving "<APP> ist offline." in the desktop
// app. After unregister the WebView loads the real bundled index.html directly (no SW control).
if (IS_TAURI) {
event.waitUntil(
(async () => {
try {
// QNBS-v3: Tauri origin exclusivity is unproven here β apply the same ownership predicate.
const keys = await caches.keys();
await Promise.all(keys.filter(isWorldScriptOwnedCache).map((name) => caches.delete(name)));
} catch (err) {
swLogger.warn('Tauri cache cleanup failed (non-fatal):', err);
}
try {
await self.registration.unregister();
} catch (err) {
swLogger.warn('Tauri SW unregister failed (non-fatal):', err);
}
await self.clients.claim();
})()
);
return;
}
event.waitUntil(
(async () => {
// QNBS-v3: admission gate β only an admitted generation may prune stale caches or claim clients.
const staticCache = await caches.open(CACHE_STATIC);
const precacheComplete = Boolean(await staticCache.match(PRECACHE_ADMISSION_URL));
if (!precacheComplete) {
swLogger.warn('Skipping cache-generation cutover: this generation\'s precache never completed');
return;
}
const cacheNames = await caches.keys();
await Promise.all(
cacheNames
// QNBS-v3: prune only owned-and-stale β never delete a cache we don't positively own.
.filter((name) => isWorldScriptOwnedCache(name) && !ALL_CACHES.includes(name))
.map((name) => {
swLogger.log('Pruning old cache:', name);
return caches.delete(name);
})
);
await self.clients.claim();
})()
);
});
/** URLs that must never pass through SW caching strategies.
* Large runtime assets (duckdb-eh.wasm, ONNX/MiniLM) are loaded on demand β never add to precache manifest. */
function isNetworkOnlyUrl(url) {
if (url.protocol === 'chrome-extension:') return true;
const h = url.hostname;
// QNBS-v3: use exact host/endsWith instead of includes() to prevent subdomain bypass (CodeQL js/incomplete-url-substring-sanitization)
if (
h === 'generativelanguage.googleapis.com' ||
h.endsWith('.generativelanguage.googleapis.com') ||
h === 'generativeai.googleapis.com' ||
h.endsWith('.generativeai.googleapis.com')
) {
return true;
}
if (h === 'api.openai.com' || h.endsWith('.openai.com')) return true;
if (h === 'api.anthropic.com' || h.endsWith('.anthropic.com')) return true;
if (h === 'openrouter.ai' || h.endsWith('.openrouter.ai')) return true;
if (h === 'api.deepseek.com' || h.endsWith('.deepseek.com')) return true;
if (h === 'localhost' || h === '127.0.0.1' || h === '[::1]') return true;
return false;
}
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// FETCH β Multi-strategy routing
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('fetch', (event) => {
// QNBS-v3: In Tauri, never intercept β let the WebView load bundled assets directly so the SW
// can't serve a stale/empty-cache offline fallback over the real app. (Belt to activate's unregister.)
if (IS_TAURI) return;
const { request } = event;
const url = new URL(request.url);
// Non-GET: passthrough
if (request.method !== 'GET') return;
// 1. External AI, extensions & local inference β Network Only (never cache GET metadata calls)
// QNBS-v3: Broad hostname allowlist keeps hybrid/OpenAI-compatible flows off stale-while-revalidate path.
if (isNetworkOnlyUrl(url)) {
return;
}
// 2. Image files β Cache First with expiry + offline SVG fallback
if (
request.destination === 'image' ||
/\.(png|jpg|jpeg|gif|webp|avif|svg|ico)(\?|$)/i.test(url.pathname)
) {
event.respondWith(
caches.open(CACHE_IMAGES).then(async (cache) => {
const cached = await cache.match(request);
if (cached && !isExpired(cached, MAX_AGE_IMAGES)) return cached;
try {
const response = await fetch(request);
if (response.ok) {
cache.put(request, stampedResponse(response.clone()));
trimCache(CACHE_IMAGES, MAX_ENTRIES_IMG);
}
return response;
} catch {
return cached || offlineFallback(request);
}
})
);
return;
}
// 3. JS / CSS bundles β Cache First (Vite hashes these; stale = always valid)
if (
url.origin === self.location.origin &&
(request.destination === 'script' || request.destination === 'style')
) {
event.respondWith(
// QNBS-v3: scoped to CACHE_STATIC (where the network path below stores it) β same shared-origin rationale as offlineFallback's fix above.
caches.match(request, { cacheName: CACHE_STATIC }).then((cached) => {
const networkFetch = fetch(request).then((response) => {
if (response.ok) {
caches.open(CACHE_STATIC).then((c) => c.put(request, response.clone()));
}
return response;
});
return cached || networkFetch;
}).catch(() => offlineFallback(request))
);
return;
}
// 4. Locale JSON β Network-First (always-fresh translations; cache fallback when offline)
// QNBS-v3: SWR returned the *cached* bundle first, so returning users kept STALE translations
// after an i18n update (e.g. ar/he stub β full Beta) until a second reload β the cache name is
// pinned to APP_VERSION, which doesn't bump on content-only i18n changes. Network-first
// guarantees fresh strings whenever online while preserving offline support via cache fallback.
if (url.pathname.includes('/locales/')) {
event.respondWith(
caches.open(CACHE_DYNAMIC).then(async (cache) => {
try {
const response = await fetch(request);
if (response.ok) {
cache.put(request, response.clone());
return response;
}
// QNBS-v3: HTTP 5xx/404 don't throw β prefer a valid cached bundle over a broken
// response so transient backend/CDN errors never wipe out translations.
return (await cachedLocaleBundle(cache, request)) || response;
} catch {
return (await cachedLocaleBundle(cache, request)) || offlineFallback(request);
}
})
);
return;
}
// 5. Navigation β Network First, SPA fallback to index.html
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
if (response.ok) {
caches.open(CACHE_DYNAMIC).then((c) => c.put(request, response.clone()));
}
return response;
})
.catch(async () =>
// QNBS-v3: each lookup scoped to the cache it's actually written to (CACHE_DYNAMIC for the navigated URL, CACHE_STATIC for the precached SPA shell) β same shared-origin rationale as above.
(await caches.match(request, { cacheName: CACHE_DYNAMIC })) ||
(await caches.match(`${BASE}index.html`, { cacheName: CACHE_STATIC })) ||
offlineFallback(request)
)
);
return;
}
// 6. Everything else β Stale-While-Revalidate with expiry
event.respondWith(
caches.open(CACHE_DYNAMIC).then(async (cache) => {
const cached = await cache.match(request);
const fetchPr = fetch(request).then((response) => {
if (response.ok) {
cache.put(request, stampedResponse(response.clone()));
trimCache(CACHE_DYNAMIC, MAX_ENTRIES_DYN);
}
return response;
}).catch(() => null);
if (cached && !isExpired(cached, MAX_AGE_DYNAMIC)) return cached;
return await fetchPr || cached || offlineFallback(request);
})
);
});
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// MESSAGE β Handle commands from the app
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('message', (event) => {
const { type } = event.data || {};
if (type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (type === 'CLEAR_CACHE') {
// QNBS-v3: clear only owned caches β a shared origin can host unrelated apps' caches too.
caches.keys()
.then((keys) => Promise.all(keys.filter(isWorldScriptOwnedCache).map((k) => caches.delete(k))))
.then(() => event.source?.postMessage({ type: 'CACHE_CLEARED' }));
}
if (type === 'GET_VERSION') {
event.source?.postMessage({ type: 'SW_VERSION', version: APP_VERSION });
}
if (type === 'PRECACHE_URLS') {
const urls = event.data.urls || [];
caches.open(CACHE_DYNAMIC).then((cache) =>
Promise.allSettled(urls.map((url) => cache.add(url)))
);
}
});
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PUSH NOTIFICATIONS β Future-ready handler
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('push', (event) => {
if (!event.data) return;
let data;
try { data = event.data.json(); } catch { data = { title: 'WorldScript Studio', body: event.data.text() }; }
const options = {
body: data.body || 'New notification',
icon: `${BASE}favicon.svg`,
badge: `${BASE}favicon.svg`,
tag: data.tag || 'worldscript-notification',
data: data.data || {},
actions: data.actions || [],
vibrate: [100, 50, 100],
renotify: false,
requireInteraction: false,
};
event.waitUntil(
self.registration.showNotification(data.title || 'WorldScript Studio', options)
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const targetUrl = event.notification.data?.url || BASE;
event.waitUntil(
self.clients
.matchAll({ type: 'window', includeUncontrolled: true })
.then((clients) => {
const focused = clients.find((c) => c.url === targetUrl && 'focus' in c);
if (focused) return focused.focus();
return self.clients.openWindow(targetUrl);
})
);
});
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// BACKGROUND SYNC β Retry deferred autosave operations
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('sync', (event) => {
if (event.tag === 'worldscript-autosave') {
event.waitUntil(
self.clients.matchAll().then((clients) =>
clients.forEach((c) => c.postMessage({ type: 'TRIGGER_AUTOSAVE' }))
)
);
}
});
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PERIODIC BACKGROUND SYNC β Refresh locale JSON while idle
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'worldscript-refresh') {
event.waitUntil(
caches.open(CACHE_DYNAMIC).then(async (cache) => {
const keys = await cache.keys();
const localeKeys = keys.filter((r) => r.url.includes('/locales/'));
return Promise.allSettled(
localeKeys.map(async (req) => {
const response = await fetch(req);
if (response.ok) cache.put(req, response);
})
);
})
);
}
});
swLogger.log(`WorldScript Studio Service Worker v${APP_VERSION} loaded`);