-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
277 lines (246 loc) · 9.84 KB
/
Copy pathservice-worker.js
File metadata and controls
277 lines (246 loc) · 9.84 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
/**
* Snake Game Service Worker - Full Offline Support
* Caches all game assets for offline gameplay
*/
const CACHE_NAME = 'snake-game-v1.0.0';
const CACHE_VERSION = '1.0.0';
// Define all assets to cache for offline support
const CORE_ASSETS = [
'/',
'/index.html',
'/style.css',
'/game.js',
'/audio.js',
'/asset-loader.js',
'/dev-toggle.js'
];
const FONT_ASSETS = [
'/assets/fonts/driftwood.ttf',
'/assets/fonts/display_dots_two_sans.ttf'
];
const IMAGE_ASSETS = [
'/assets/snake/snake_icon.webp',
'/assets/backgrounds/log.webp',
'/assets/buttons/play_wooden.webp',
'/assets/buttons/play_default.webp',
'/assets/buttons/settings.webp',
'/assets/backgrounds/title_screen_bg.webp',
'/assets/backgrounds/jungle.webp',
'/assets/backgrounds/grass_01.webp',
'/assets/backgrounds/grass_02.webp',
'/assets/backgrounds/grass_03.webp',
'/assets/backgrounds/game_over_board.webp',
'/assets/obstacles/rock_1_block.webp',
'/assets/obstacles/rock_2_blocks.webp',
'/assets/obstacles/rock_4_blocks.webp',
'/assets/obstacles/rock_1_block_alt.webp',
'/assets/snake/skins/greeny/head.webp',
'/assets/snake/skins/greeny/body_straight.webp',
'/assets/snake/skins/greeny/body_turn.webp',
'/assets/snake/skins/greeny/tail.webp',
'/assets/snake/skins/greeny/food.webp',
'/assets/snake/skins/greeny/dead_head.webp',
'/assets/snake/sprites/greeny/greeny_spritesheet.webp',
'/assets/buttons/home_food_icon.webp',
'/assets/buttons/home_stone.webp',
'/assets/buttons/retry_stone.webp'
];
const AUDIO_ASSETS = [
'/assets/audio/jungle_snake_background_music.mp3',
'/assets/audio/jungle_snake_button_click.mp3',
'/assets/audio/jungle_snake_game_start.mp3',
'/assets/audio/jungle_snake_snake_move.mp3',
'/assets/audio/jungle_snake_eat_food.mp3',
'/assets/audio/jungle_snake_tongue_flick.mp3',
'/assets/audio/jungle_snake_collision.mp3',
'/assets/audio/jungle_snake_hit_impact.mp3',
'/assets/audio/jungle_snake_game_over.mp3',
'/assets/audio/jungle_snake_hover.mp3'
];
// Combine all assets for caching
const ASSETS_TO_CACHE = [
...CORE_ASSETS,
...FONT_ASSETS,
...IMAGE_ASSETS,
...AUDIO_ASSETS
];
// Install event - cache all assets
self.addEventListener('install', event => {
console.log('[ServiceWorker] Installing...');
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('[ServiceWorker] Caching app shell and assets');
console.log(`[ServiceWorker] Caching ${ASSETS_TO_CACHE.length} total assets`);
// Cache assets in batches to avoid overwhelming the browser
return cacheAssetsInBatches(cache, ASSETS_TO_CACHE, 10);
})
.then(() => {
console.log('[ServiceWorker] All assets cached successfully');
// Force the waiting service worker to become the active service worker
return self.skipWaiting();
})
.catch(error => {
console.error('[ServiceWorker] Failed to cache assets:', error);
})
);
});
// Activate event - clean up old caches
self.addEventListener('activate', event => {
console.log('[ServiceWorker] Activating...');
event.waitUntil(
caches.keys()
.then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName => {
// Delete old caches that don't match current version
return cacheName.startsWith('snake-game-') && cacheName !== CACHE_NAME;
})
.map(cacheName => {
console.log('[ServiceWorker] Deleting old cache:', cacheName);
return caches.delete(cacheName);
})
);
})
.then(() => {
console.log('[ServiceWorker] Cache cleanup complete');
// Ensure the service worker takes control immediately
return self.clients.claim();
})
);
});
// Fetch event - serve from cache when offline, network when online
self.addEventListener('fetch', event => {
// Skip non-GET requests
if (event.request.method !== 'GET') {
return;
}
// Skip cross-origin requests that aren't assets
if (!event.request.url.startsWith(self.location.origin)) {
return;
}
event.respondWith(
caches.match(event.request)
.then(cachedResponse => {
// Return cached response if available
if (cachedResponse) {
return cachedResponse;
}
// Otherwise, fetch from network
return fetch(event.request)
.then(networkResponse => {
// Don't cache non-successful responses
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
// Clone the response for caching
const responseToCache = networkResponse.clone();
// Cache the new response for future use
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseToCache);
});
return networkResponse;
})
.catch(() => {
// Network failed and no cache available
// For HTML requests, return a fallback page
if (event.request.destination === 'document') {
return caches.match('/index.html');
}
// For other requests, just fail
return new Response('Offline - Asset not available', {
status: 404,
statusText: 'Offline'
});
});
})
);
});
// Helper function to cache assets in batches
async function cacheAssetsInBatches(cache, assets, batchSize) {
const batches = [];
// Split assets into batches
for (let i = 0; i < assets.length; i += batchSize) {
batches.push(assets.slice(i, i + batchSize));
}
// Cache each batch sequentially
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
console.log(`[ServiceWorker] Caching batch ${i + 1}/${batches.length} (${batch.length} assets)`);
try {
await cache.addAll(batch);
console.log(`[ServiceWorker] Batch ${i + 1} cached successfully`);
} catch (error) {
console.warn(`[ServiceWorker] Some assets in batch ${i + 1} failed to cache:`, error);
// Try to cache assets individually in this batch
for (const asset of batch) {
try {
await cache.add(asset);
} catch (assetError) {
console.warn(`[ServiceWorker] Failed to cache individual asset: ${asset}`, assetError);
}
}
}
}
}
// Message handler for cache updates and cleanup
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (event.data && event.data.type === 'GET_CACHE_STATUS') {
// Send cache status back to client
caches.open(CACHE_NAME)
.then(cache => cache.keys())
.then(keys => {
event.ports[0].postMessage({
type: 'CACHE_STATUS',
cached: keys.length,
total: ASSETS_TO_CACHE.length,
version: CACHE_VERSION
});
});
}
// Handle force stop message from cleanup utility
if (event.data && event.data.type === 'FORCE_STOP') {
console.log('[ServiceWorker] Received FORCE_STOP message, unregistering...');
// Unregister this service worker
self.registration.unregister()
.then(() => {
console.log('[ServiceWorker] Successfully unregistered via FORCE_STOP');
// Take control of clients to ensure clean transition
return self.clients.claim();
})
.then(() => {
console.log('[ServiceWorker] Claimed clients after unregistration');
// Notify all clients that SW has been unregistered
return self.clients.matchAll();
})
.then(clients => {
clients.forEach(client => {
client.postMessage({
type: 'SW_UNREGISTERED',
message: 'Service Worker has been unregistered',
timestamp: event.data.timestamp || Date.now()
});
});
})
.catch(error => {
console.error('[ServiceWorker] Error during FORCE_STOP cleanup:', error);
});
}
});
// Handle updates - notify clients when new version is available
self.addEventListener('controllerchange', () => {
// Send message to all clients that SW has been updated
self.clients.matchAll().then(clients => {
clients.forEach(client => {
client.postMessage({
type: 'SW_UPDATED',
message: 'New version available! Refresh to update.'
});
});
});
});