-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
378 lines (318 loc) · 10.6 KB
/
service-worker.js
File metadata and controls
378 lines (318 loc) · 10.6 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
// ========================================
// CHESSARCADE SERVICE WORKER v2.0.0
// Soporte offline para máxima jugabilidad retro
// ========================================
const CACHE_NAME = 'chessarcade-v2.0.0';
const CACHE_STATIC_NAME = 'chessarcade-static-v2.0.0';
const CACHE_DYNAMIC_NAME = 'chessarcade-dynamic-v2.0.0';
// ===== RECURSOS CRÍTICOS PARA CACHE =====
const STATIC_ASSETS = [
// Páginas principales
'/',
'/index.html',
// Juegos
'/games/knight-quest/',
'/games/knight-quest/index.html',
// Recursos compartidos
'/shared/arcade-shared.css',
'/shared/shared-utils.js',
'/shared/hub-main.js',
// PWA
'/manifest.json',
// Fuentes externas (críticas)
'https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap',
// Offline fallback
'/offline.html'
];
// ===== RECURSOS DINÁMICOS =====
const DYNAMIC_ASSETS = [
// Imágenes de iconos
'/assets/icons/',
// Screenshots
'/assets/screenshots/',
// Archivos de configuración
'/assets/config/',
// Audio (futuro)
'/assets/audio/'
];
// ===== INSTALACIÓN DEL SERVICE WORKER =====
self.addEventListener('install', event => {
console.log('🚀 [SW] Instalando ChessArcade Service Worker v2.0.0...');
event.waitUntil(
Promise.all([
// Cache recursos estáticos críticos
caches.open(CACHE_STATIC_NAME).then(cache => {
console.log('📦 [SW] Cacheando recursos estáticos...');
return cache.addAll(STATIC_ASSETS.map(url => new Request(url, {
cache: 'reload' // Forzar recarga para última versión
})));
}),
// Crear cache dinámico vacío
caches.open(CACHE_DYNAMIC_NAME).then(cache => {
console.log('📁 [SW] Cache dinámico creado');
return cache;
})
]).then(() => {
console.log('✅ [SW] Instalación completada - ChessArcade listo offline!');
// Forzar activación inmediata
return self.skipWaiting();
}).catch(error => {
console.error('❌ [SW] Error durante instalación:', error);
})
);
});
// ===== ACTIVACIÓN DEL SERVICE WORKER =====
self.addEventListener('activate', event => {
console.log('⚡ [SW] Activando ChessArcade Service Worker...');
event.waitUntil(
Promise.all([
// Limpiar caches antiguos
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_STATIC_NAME &&
cacheName !== CACHE_DYNAMIC_NAME &&
cacheName.startsWith('chessarcade-')) {
console.log('🗑️ [SW] Eliminando cache antiguo:', cacheName);
return caches.delete(cacheName);
}
})
);
}),
// Tomar control de todas las páginas
self.clients.claim()
]).then(() => {
console.log('✅ [SW] Activación completada - Modo retro offline activo!');
}).catch(error => {
console.error('❌ [SW] Error durante activación:', error);
})
);
});
// ===== INTERCEPTAR REQUESTS (ESTRATEGIA CACHE-FIRST) =====
self.addEventListener('fetch', event => {
const request = event.request;
const url = new URL(request.url);
// Solo manejar requests HTTP/HTTPS
if (!request.url.startsWith('http')) {
return;
}
// Estrategia basada en tipo de recurso
if (isStaticAsset(request.url)) {
// Recursos estáticos: Cache First
event.respondWith(cacheFirst(request));
} else if (isGameAsset(request.url)) {
// Recursos del juego: Cache First con fallback
event.respondWith(cacheFirstWithFallback(request));
} else if (isExternalResource(request.url)) {
// Recursos externos (fuentes, CDN): Cache First
event.respondWith(cacheFirstExternal(request));
} else {
// Otros recursos: Network First con fallback a cache
event.respondWith(networkFirstWithCache(request));
}
});
// ===== ESTRATEGIAS DE CACHE =====
// Cache First - Para recursos estáticos
async function cacheFirst(request) {
try {
const cacheResponse = await caches.match(request);
if (cacheResponse) {
console.log('💾 [SW] Sirviendo desde cache:', request.url);
return cacheResponse;
}
console.log('🌐 [SW] Descargando y cacheando:', request.url);
const networkResponse = await fetch(request);
// Cachear solo respuestas exitosas
if (networkResponse.status === 200) {
const cache = await caches.open(CACHE_STATIC_NAME);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.error('❌ [SW] Error en cacheFirst:', error);
return getOfflineFallback(request);
}
}
// Cache First con Fallback - Para recursos del juego
async function cacheFirstWithFallback(request) {
try {
const cacheResponse = await caches.match(request);
if (cacheResponse) {
return cacheResponse;
}
const networkResponse = await fetch(request);
if (networkResponse.status === 200) {
const cache = await caches.open(CACHE_DYNAMIC_NAME);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.log('🎮 [SW] Sirviendo fallback para juego');
return getGameFallback(request);
}
}
// Cache First para recursos externos
async function cacheFirstExternal(request) {
try {
const cacheResponse = await caches.match(request);
if (cacheResponse) {
return cacheResponse;
}
const networkResponse = await fetch(request, {
mode: 'cors',
cache: 'default'
});
if (networkResponse.status === 200) {
const cache = await caches.open(CACHE_STATIC_NAME);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.log('🌐 [SW] Recurso externo no disponible offline');
return new Response('', { status: 204 }); // No Content
}
}
// Network First con Cache - Para recursos dinámicos
async function networkFirstWithCache(request) {
try {
const networkResponse = await fetch(request);
if (networkResponse.status === 200) {
const cache = await caches.open(CACHE_DYNAMIC_NAME);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.log('📱 [SW] Red no disponible, buscando en cache...');
const cacheResponse = await caches.match(request);
if (cacheResponse) {
return cacheResponse;
}
return getOfflineFallback(request);
}
}
// ===== FUNCIONES DE UTILIDAD =====
function isStaticAsset(url) {
return STATIC_ASSETS.some(asset => url.includes(asset)) ||
url.includes('.css') ||
url.includes('.js') ||
url.includes('manifest.json');
}
function isGameAsset(url) {
return url.includes('/games/') ||
url.includes('/assets/') ||
url.includes('.png') ||
url.includes('.jpg') ||
url.includes('.svg');
}
function isExternalResource(url) {
return url.includes('fonts.googleapis.com') ||
url.includes('fonts.gstatic.com') ||
!url.includes(self.location.origin);
}
// Fallback offline genérico
async function getOfflineFallback(request) {
const url = new URL(request.url);
// Para páginas HTML
if (request.destination === 'document') {
const offlinePage = await caches.match('/offline.html');
if (offlinePage) {
return offlinePage;
}
}
// Para imágenes
if (request.destination === 'image') {
return new Response(
'<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">' +
'<rect width="200" height="200" fill="#1a1a2e"/>' +
'<text x="100" y="100" text-anchor="middle" fill="#00ffff" font-family="monospace" font-size="12">' +
'Imagen no disponible offline' +
'</text></svg>',
{ headers: { 'Content-Type': 'image/svg+xml' } }
);
}
// Respuesta genérica
return new Response('Recurso no disponible offline', {
status: 503,
statusText: 'Service Unavailable',
headers: { 'Content-Type': 'text/plain' }
});
}
// Fallback específico para juegos
async function getGameFallback(request) {
// Intentar servir la página principal del juego desde cache
const mainGamePage = await caches.match('/games/knight-quest/index.html');
if (mainGamePage) {
return mainGamePage;
}
return getOfflineFallback(request);
}
// ===== EVENTOS DE MENSAJE =====
self.addEventListener('message', event => {
const { type, data } = event.data;
switch (type) {
case 'SKIP_WAITING':
console.log('⚡ [SW] Forzando activación...');
self.skipWaiting();
break;
case 'GET_VERSION':
event.ports[0].postMessage({
version: CACHE_NAME,
status: 'active'
});
break;
case 'CACHE_GAME_DATA':
// Cachear datos específicos del juego
cacheGameData(data).then(() => {
event.ports[0].postMessage({ success: true });
}).catch(error => {
event.ports[0].postMessage({ success: false, error: error.message });
});
break;
case 'CLEAR_CACHE':
clearAllCaches().then(() => {
event.ports[0].postMessage({ success: true });
});
break;
default:
console.log('📨 [SW] Mensaje desconocido:', type);
}
});
// Cachear datos específicos del juego
async function cacheGameData(gameData) {
const cache = await caches.open(CACHE_DYNAMIC_NAME);
const response = new Response(JSON.stringify(gameData), {
headers: { 'Content-Type': 'application/json' }
});
await cache.put('/api/game-data', response);
console.log('💾 [SW] Datos del juego cacheados');
}
// Limpiar todos los caches
async function clearAllCaches() {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.map(cacheName => {
if (cacheName.startsWith('chessarcade-')) {
console.log('🗑️ [SW] Limpiando cache:', cacheName);
return caches.delete(cacheName);
}
})
);
}
// ===== EVENTOS DE SINCRONIZACIÓN (FUTURO) =====
self.addEventListener('sync', event => {
if (event.tag === 'sync-scores') {
console.log('🔄 [SW] Sincronizando puntuaciones...');
event.waitUntil(syncScores());
}
});
async function syncScores() {
// Implementación futura para sincronizar puntuaciones
console.log('🏆 [SW] Sync de puntuaciones completado');
}
// ===== LOGGING DE EVENTOS =====
self.addEventListener('fetch', event => {
if (event.request.destination === 'document') {
console.log('📄 [SW] Navegando a:', event.request.url);
}
});
console.log('🎮 ChessArcade Service Worker v2.0.0 inicializado - ¡Modo retro offline activo!');