informe-comercial-alfa/public/campo-sw.js

70 lines
3.3 KiB
JavaScript

/* Service worker mínimo y seguro de ALFA+ Campo. Alcance: SOLO /m/.
- Guarda la última respuesta de /m/hoy (cuando hay sesión) para leerla sin conexión: «Sin conexión · actualizado HH:MM».
- Guarda los archivos estáticos de Next (/_next/static, inmutables) para que la página abra sin red.
- NO guarda autenticación (/api/auth), ni acciones de servidor, ni ninguna otra ruta ni respuesta de datos.
- Sin avisos push (van en otro paquete). Las acciones requieren conexión: la app lo dice. */
const CACHE_HOY = "campo-hoy";
const CACHE_EST = "campo-estatico-v1";
let servidoDeCache = null; // { url, hora } cuando la última navegación salió de la copia
self.addEventListener("install", (e) => {
e.waitUntil(caches.open(CACHE_EST).then((c) => c.addAll(["/campo/icon-192.png", "/assets/css/campo.css"])).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
const hora = (d) => new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", hour: "2-digit", minute: "2-digit", hour12: false }).format(d);
self.addEventListener("message", (e) => {
if (e.data?.q === "estado") e.ports[0]?.postMessage(servidoDeCache && servidoDeCache.url === e.data.url ? { cache: true, hora: servidoDeCache.hora } : { cache: false });
});
self.addEventListener("fetch", (e) => {
const req = e.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== location.origin) return;
// Estáticos inmutables de Next: cache primero.
if (url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/campo/") || url.pathname === "/assets/css/campo.css") {
e.respondWith(
caches.open(CACHE_EST).then(async (c) => {
const hit = await c.match(req);
if (hit) return hit;
const r = await fetch(req);
if (r.ok) c.put(req, r.clone());
return r;
})
);
return;
}
// Navegación a /m/hoy: red primero; si hay sesión guarda copia; sin red usa la copia.
if (req.mode === "navigate" && url.pathname === "/m/hoy") {
e.respondWith(
(async () => {
try {
const r = await fetch(req);
servidoDeCache = null;
// Solo se guarda si la página trae la marca de sesión iniciada y no hubo redirección a inicio de sesión.
if (r.ok && !r.redirected) {
const copia = r.clone();
const texto = await copia.text();
if (texto.includes('data-campo-ok="1"')) {
const c = await caches.open(CACHE_HOY);
await c.put("/m/hoy", new Response(texto, { headers: { "Content-Type": "text/html; charset=utf-8", "x-campo-hora": hora(new Date()) } }));
}
}
return r;
} catch {
const c = await caches.open(CACHE_HOY);
const hit = await c.match("/m/hoy");
if (hit) {
servidoDeCache = { url: "/m/hoy", hora: hit.headers.get("x-campo-hora") || "" };
return hit;
}
return new Response("<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'><body style='font-family:sans-serif;padding:24px'><h2>Sin conexión</h2><p>Abre ALFA+ Campo con señal al menos una vez para ver tu día sin conexión.</p>", { headers: { "Content-Type": "text/html; charset=utf-8" } });
}
})()
);
}
});