// Service worker : fonctionnement hors-ligne de l'app Boucle du Hainaut AR. // - « coquille » (HTML, JS, CSS, bibliothèques, tracé) : mise en cache à l'installation ; // - dalles de bâtiments : mises en cache à la première utilisation, ou toutes d'un coup via // Réglages › « Télécharger tout pour hors-ligne » (cache DATA, conservé entre les versions). // À chaque nouvelle version de l'app, changer VERSION (et les ?v= dans index.html). const VERSION = 'v50'; const SHELL = `bdh-shell-${VERSION}`; const DATA = 'bdh-data-v1'; const SHELL_FILES = [ './', 'index.html', `app.js?v=50`, `boot.js?v=50`, `pylon.js?v=50`, `buildings.js?v=50`, `offline.js?v=50`, `lidar.js?v=50`, `terrain.js?v=50`, `style.css?v=50`, 'lib/three.module.js', 'lib/three.core.js', 'lib/locar.es.js?v=lib2', 'lib/lines/LineSegments2.js?v=lib2', 'lib/lines/LineSegmentsGeometry.js?v=lib2', 'lib/lines/LineMaterial.js?v=lib2', 'data/trace.json', 'manifest.json', 'icon.svg', 'icon-192.png', 'icon-512.png', 'icon-maskable-192.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.ico', ]; self.addEventListener('install', (e) => { e.waitUntil(caches.open(SHELL).then((c) => c.addAll(SHELL_FILES)).then(() => self.skipWaiting())); }); self.addEventListener('activate', (e) => { e.waitUntil(caches.keys() .then((keys) => Promise.all(keys.filter((k) => k.startsWith('bdh-shell-') && k !== SHELL).map((k) => caches.delete(k)))) .then(() => self.clients.claim())); }); // Réseau d'abord (pour avoir la dernière version), cache si hors-ligne async function networkFirst(req, cacheName) { const cache = await caches.open(cacheName); try { // Réseau faible en balade : au-delà de 4 s, on se rabat sur la copie locale si elle existe const res = await Promise.race([ fetch(req), new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 4000)), ]); if (res.ok) cache.put(req, res.clone()); return res; } catch (e) { const hit = await cache.match(req, { ignoreSearch: req.mode === 'navigate' }); if (hit) return hit; throw e; } } // Cache d'abord (fichiers versionnés, dalles), réseau sinon (et on garde la copie) async function cacheFirst(req, cacheName) { const hit = await caches.match(req); if (hit) return hit; const res = await fetch(req); if (res.ok) (await caches.open(cacheName)).put(req, res.clone()); return res; } self.addEventListener('fetch', (e) => { const req = e.request; const url = new URL(req.url); if (req.method !== 'GET' || url.origin !== self.location.origin) return; const p = url.pathname; if (req.mode === 'navigate' || p.endsWith('/index.html') || p.endsWith('/data/trace.json') || (p.includes('/data/') && p.endsWith('/index.json'))) { e.respondWith(networkFirst(req, SHELL)); } else if (p.includes('/data/bat/') || p.includes('/data/lidar/') || p.includes('/data/terrain/')) { e.respondWith(cacheFirst(req, DATA)); } else { e.respondWith(cacheFirst(req, SHELL)); } });