-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsw.js
More file actions
314 lines (293 loc) · 12.1 KB
/
sw.js
File metadata and controls
314 lines (293 loc) · 12.1 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
const CORE_CACHE_VERSION = 'Bismuth 17.2';
const CORE_CACHE_NAME = `polygol-core-${CORE_CACHE_VERSION}`;
const APPS_CACHE_NAME = 'polygol-apps';
// --- IndexedDB Vault Configuration ---
const VAULT_DB = 'PolygolSystemVaultDB';
const VAULT_STORE = 'core_assets';
const ASSETS_TO_CACHE = [
'/',
'/assets/img/icon.svg',
'/recovery/index.html',
'/index.html',
'/css/styles.css',
'/js/core/storage.js',
'/js/core/audio.js',
'/js/core/a11y.js',
'/js/core/performance.js',
'/js/core/system.js',
'/js/core/dialogs.js',
'/js/core/files.js',
'/js/core/power.js',
'/js/core/first-setup.js',
'/js/core/sys-connect-waves.js',
'/js/ui/theme.js',
'/js/ui/modes.js',
'/js/ui/notifications.js',
'/js/ui/clock-weather.js',
'/js/ui/environment.js',
'/js/ui/wallpaper.js',
'/js/ui/widgets.js',
'/js/ui/dock-drawer.js',
'/js/ui/settings.js',
'/js/ui/physical-keyboard.js',
'/js/ui/osk.js',
'/js/ui/browser-chrome.js',
'/js/ui/donburi.js',
'/js/ui/main-ui.js',
'/js/apps/app-switcher.js',
'/js/apps/window-manager.js',
'/js/apps/media-session.js',
'/js/apps/live-activities.js',
'/js/apps/api.js',
'/js/core/boot.js',
'/js/index.js',
'/js/lang.js',
'/js/kirbservices.js',
'/js/waves.js',
'/assets/gurapp/api/gurasuraisu-api.js',
'https://polygol.github.io/assets/gurapp/api/gurasuraisu-api.js',
'https://raw.githubusercontent.com/Polygol/polygol.github.io/refs/heads/main/assets/gurapp/api/gurasuraisu-api.js',
'/assets/ui/svg/load.svg',
'/manifest.json',
'/about/external.md',
'/assets/text/greet/home.json',
'/assets/img/favi/regular.png',
'/assets/img/pwaicon/coloricon.png',
'/assets/img/pwaicon/regular.png',
'https://github.com/kirbIndustries/assets/blob/main/brand/img/colorlogotxt/text-owner-transparent.png?raw=true',
'/assets/img/ver/16.png',
'/transfer/index.html',
'/appstore/index.html',
'/assets/gurapp/intl/settings/index.html',
'/assets/gurapp/intl/settings/settings.css',
'/assets/gurapp/intl/settings/settings.js',
'/assets/gurapp/intl/forudaraisu/index.html',
'/assets/gurapp/intl/donburi/index.html',
'/assets/gurapp/intl/overlay/osk/osk.html',
'/assets/gurapp/intl/liveactivity/weather-alert.html',
'/assets/gurapp/intl/liveactivity/slideshow-control.html',
'/assets/gurapp/intl/system-widgets/media-widget.html',
'/assets/gurapp/intl/waves/announce.html',
'/assets/gurapp/intl/waves/cast.html',
'/waves/index.html',
'/waves/manifest.json',
'/waves/favicon.png',
'/waves/home.png',
'/assets/appicon/appstore.png',
'/assets/appicon/assistant.png',
'/assets/appicon/default.png',
'/assets/appicon/feedback.png',
'/assets/appicon/files.png',
'/assets/appicon/home.png',
'/assets/appicon/settings.png',
'/assets/appicon/system.png',
'/assets/appicon/tips.png',
'/assets/appicon/transfer.png',
'/assets/sound/ui/check.mp3',
'/assets/sound/ui/in.mp3',
'/assets/sound/ui/mecha.mp3',
'/assets/sound/ui/out.mp3',
'/assets/sound/ui/popup.mp3',
'/assets/sound/ui/seldelay.mp3',
'/assets/sound/ui/select.mp3',
'/assets/sound/ui/seltoggle.mp3',
'/assets/sound/ui/tone1.mp3',
'/assets/sound/ui/tone2.mp3',
'/assets/sound/ui/tridown.mp3',
'/assets/sound/ui/tripuck.mp3',
'https://cdn.jsdelivr.net/npm/modern-screenshot@4.6.8/dist/index.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js',
'https://cdn.jsdelivr.net/npm/suncalc@1.9.0/suncalc.min.js',
'https://esm.sh/trystero@0.15.1/torrent',
'https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js',
'https://cdn.jsdelivr.net/npm/three@0.158.0/build/three.module.js',
'https://cdn.jsdelivr.net/npm/three@0.158.0/examples/jsm/',
'https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap',
'https://cdn.jsdelivr.net/gh/lauridskern/open-runde@main/src/web/OpenRunde-Regular.woff2',
'https://cdn.jsdelivr.net/gh/lauridskern/open-runde@main/src/web/OpenRunde-Medium.woff2',
'https://cdn.jsdelivr.net/gh/lauridskern/open-runde@main/src/web/OpenRunde-Semibold.woff2',
'https://cdn.jsdelivr.net/gh/lauridskern/open-runde@main/src/web/OpenRunde-Bold.woff2',
'/assets/fonts/InterNumeric.ttf',
'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js',
'https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,0',
'https://fonts.googleapis.com/css2?family=Roboto:wght@100..900&display=swap',
'https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap',
'https://fonts.googleapis.com/css2?family=DynaPuff:wght@400..700&display=swap',
'https://fonts.googleapis.com/css2?family=Domine:wght@400..700&display=swap',
'https://fonts.googleapis.com/css2?family=Climate+Crisis&display=swap',
'https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@100..800&display=swap',
'https://fonts.googleapis.com/css2?family=DotGothic16&display=swap',
'https://fonts.googleapis.com/css2?family=Playpen+Sans:wght@100..800&display=swap',
'https://fonts.googleapis.com/css2?family=Jaro:opsz@6..72&display=swap',
'https://fonts.googleapis.com/css2?family=Doto:wght@400;700&display=swap',
'https://fonts.googleapis.com/css2?family=Nunito:wght@200..900&display=swap',
'https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt'
];
// --- IndexedDB Helper Functions ---
function openVault() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(VAULT_DB, 1);
req.onupgradeneeded = e => e.target.result.createObjectStore(VAULT_STORE);
req.onsuccess = e => resolve(e.target.result);
req.onerror = e => reject(e);
});
}
async function stashInVault(requestUrl, response) {
try {
const db = await openVault();
const blob = await response.clone().blob();
const headers = {};
response.headers.forEach((val, key) => headers[key] = val);
return new Promise((resolve) => {
const tx = db.transaction(VAULT_STORE, 'readwrite');
tx.objectStore(VAULT_STORE).put({
blob: blob,
headers: headers,
status: response.status,
statusText: response.statusText
}, requestUrl);
tx.oncomplete = resolve;
});
} catch (e) { console.warn('[SW] Failed to stash in Vault:', e); }
}
async function getFromVault(requestUrl) {
try {
const db = await openVault();
return new Promise((resolve) => {
const tx = db.transaction(VAULT_STORE, 'readonly');
const req = tx.objectStore(VAULT_STORE).get(requestUrl);
req.onsuccess = () => {
const data = req.result;
if (data) {
resolve(new Response(data.blob, {
status: data.status,
statusText: data.statusText,
headers: data.headers
}));
} else {
resolve(null);
}
};
req.onerror = () => resolve(null);
});
} catch (e) { return null; }
}
// INSTALL: Cache system assets into both Cache API AND IndexedDB Vault
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CORE_CACHE_NAME).then(async cache => {
console.log(`[SW] Caching core assets for ${CORE_CACHE_VERSION}`);
for (const url of ASSETS_TO_CACHE) {
try {
const req = new Request(url, {cache: 'reload'});
const res = await fetch(req);
// 1. Store in Cache API (For Speed)
// FIX: Create isolated clones immediately to prevent locking conflicts
const resForCache = res.clone();
const resForVault = res.clone();
await cache.put(req, resForCache);
// 2. Store in IndexedDB Vault (For Permanence)
const absoluteUrl = new URL(url, self.location.origin).href;
await stashInVault(absoluteUrl, resForVault);
} catch(e) {
console.error('[SW] Asset caching failed for:', url, e);
}
}
})
);
});
// ACTIVATE: Clean up OLD core caches, but KEEP the apps cache
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
// Delete old core caches (e.g. polygol-core-v1.0)
if (cacheName.startsWith('polygol-core-') && cacheName !== CORE_CACHE_NAME) {
console.log(`[SW] Deleting old system cache: ${cacheName}`);
return caches.delete(cacheName);
}
// Do NOT delete 'polygol-apps' or other unrelated caches
})
);
}).then(() => self.clients.claim())
);
});
// MESSAGE: Handle App Caching and Updates
self.addEventListener('message', event => {
if (!event.data) return;
if (event.data.action === 'skipWaiting') {
console.log('[SW] Activating new version...');
self.skipWaiting();
}
// Cache user-installed apps into the persistent APPS_CACHE
if (event.data.action === 'cache-app') {
const filesToCache = event.data.files;
if (filesToCache && filesToCache.length > 0) {
console.log(`[SW] Caching app files into ${APPS_CACHE_NAME}`);
event.waitUntil(
caches.open(APPS_CACHE_NAME).then(cache => {
return cache.addAll(filesToCache)
.then(() => console.log('[SW] App caching complete.'))
.catch(err => console.warn(`[SW] App caching failed`, err));
})
);
}
}
if (event.data.action === 'uncache-app') {
const filesToDelete = event.data.filesToDelete;
if (filesToDelete && filesToDelete.length > 0) {
event.waitUntil(
caches.open(APPS_CACHE_NAME).then(cache => {
const deletePromises = filesToDelete.map(url => cache.delete(url));
return Promise.allSettled(deletePromises);
})
);
}
}
});
// FETCH: Check Core -> Apps -> Network
self.addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
// Ensure API requests for live data never serve stale cached versions
const apiHosts = [
'polygol.github.io/kirbstore/inventories',
'/kirbstore/inventories',
'raw.githubusercontent.com/kirbIndustries/assets/refs/heads/main/kirbindustries-ads-service/octagon/small.json',
'kirbindust.goatcounter.com',
'api.open-meteo.com',
'dummyjson.com',
'api.rss2json.com'
];
if (apiHosts.includes(url.hostname)) {
event.respondWith(fetch(request));
return;
}
event.respondWith(
// 1. Try Cache API (Fastest)
caches.match(request).then(async cacheRes => {
if (cacheRes) return cacheRes;
// 2. Cache API Miss/Eviction! Try IndexedDB Vault (Safety Net)
const vaultRes = await getFromVault(request.url);
if (vaultRes) {
console.warn(`[SW] Cache API evicted ${request.url}. Recovered from IDB Vault.`);
// Heal the Cache API for next time
const resToCache = vaultRes.clone();
caches.open(CORE_CACHE_NAME).then(c => c.put(request, resToCache));
return vaultRes;
}
// 3. Fallback to Network
return fetch(request).then(netRes => {
return netRes;
}).catch(async () => {
// Offline Fallback for Navigation
if (request.mode === 'navigate') {
// Try to rescue the root index from Cache, then Vault
const indexUrl = new URL('/index.html', self.location.origin).href;
return (await caches.match('/index.html')) || (await getFromVault(indexUrl));
}
});
})
);
});