perf: arranque ultrarapido pwa con gzip compression stale-while-revalidate y renderizado optimista

This commit is contained in:
unknown
2026-10-08 22:09:49 -06:00
parent da5dbd24f8
commit 06beb22c1f
6 changed files with 192 additions and 61 deletions
+79
View File
@@ -10,6 +10,7 @@
"license": "ISC",
"dependencies": {
"better-sqlite3": "^13.0.3",
"compression": "^1.8.2",
"cors": "^2.8.6",
"express": "^5.2.1",
"imap-simple": "^5.1.0",
@@ -493,6 +494,65 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/compressible": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
"integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
"license": "MIT",
"dependencies": {
"mime-db": ">= 1.43.0 < 2"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/compression": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz",
"integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"compressible": "~2.0.18",
"debug": "2.6.9",
"destroy": "1.2.0",
"negotiator": "~0.6.4",
"on-headers": "~1.1.0",
"safe-buffer": "5.2.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.8.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/compression/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/compression/node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/compression/node_modules/negotiator": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
"integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-disposition": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -622,6 +682,16 @@
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/devtools-protocol": {
"version": "0.0.1687809",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",
@@ -1512,6 +1582,15 @@
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",
"integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+1
View File
@@ -22,6 +22,7 @@
"homepage": "https://github.com/pampo32-hub/recreopay#readme",
"dependencies": {
"better-sqlite3": "^13.0.3",
"compression": "^1.8.2",
"cors": "^2.8.6",
"express": "^5.2.1",
"imap-simple": "^5.1.0",
+6 -5
View File
@@ -11,7 +11,8 @@
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="SiboPay">
<meta name="mobile-web-app-capable" content="yes">
<link rel="preload" href="/css/styles.css?v=14.0" as="style">
<link rel="preload" href="/js/app.js?v=14.0" as="script">
<link rel="stylesheet" href="/css/styles.css?v=14.0">
<link rel="stylesheet" href="/css/desktop.css?v=2.2">
<style>
@@ -3896,9 +3897,9 @@
</nav>
<script src="/js/dialogs.js?v=13.8"></script>
<script src="/js/sounds.js?v=13.8"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/food-icons.js?v=1.1"></script>
<script src="/js/app.js?v=14.0"></script>
<script src="/js/sounds.js?v=13.8" defer></script>
<script src="/js/jsQR.js" defer></script>
<script src="/js/food-icons.js?v=1.1" defer></script>
<script src="/js/app.js?v=15.0"></script>
</body>
</html>
+49 -18
View File
@@ -68,7 +68,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// Registrar Service Worker para PWA
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js?v=15.0').then(reg => {
navigator.serviceWorker.register('/sw.js?v=16.0').then(reg => {
reg.update().catch(() => {});
if ('Notification' in window && Notification.permission === 'granted') {
subscribeDeviceToWebPush().catch(() => {});
@@ -546,12 +546,38 @@ async function applyUserRoleSession() {
const btnPadres = document.getElementById('btnModePadres');
if (btnPadres) btnPadres.style.display = 'none';
await loadInitialData();
// 🚀 RENDERIZADO OPTIMISTA INSTANTÁNEO (0 ms):
// El estudiante ve su carné, saldo y botón de QR de inmediato con sus datos guardados localmente
if (currentUser.estudiante) {
await selectStudent(currentUser.estudiante.id);
currentStudent = currentUser.estudiante;
currentAppMode = 'teens';
updateStudentUI();
}
// En segundo plano y en paralelo: sincronizar datos frescos sin congelar la pantalla
const studentTasks = [loadInitialData(true)];
if (currentUser.estudiante) {
studentTasks.push(
fetch(`/api/estudiantes/${currentUser.estudiante.id}`)
.then(r => r.json())
.then(freshStudent => {
if (freshStudent && freshStudent.id) {
currentStudent = freshStudent;
currentUser.estudiante = freshStudent;
try {
localStorage.setItem('sibopay_user', JSON.stringify(currentUser));
} catch (_) {}
updateStudentUI();
}
})
.catch(e => console.warn('Error sincronizando estudiante:', e))
);
} else if (students.length > 0) {
selectStudent(students[0].id);
}
await Promise.allSettled(studentTasks);
}
}
@@ -678,21 +704,24 @@ function pwaNavigateTo(target) {
}
}
async function loadInitialData() {
async function loadInitialData(isStudent = false) {
try {
// 1. Cargar estudiantes
const resEst = await fetch('/api/estudiantes');
students = await resEst.json();
populateStudentSelector();
// 2. Cargar productos y categorías de la escuela activa
const escId = (currentUser && currentUser.escuela_id) || (currentStudent && currentStudent.escuela_id) || 1;
const resProd = await fetch(`/api/productos?escuela_id=${escId}`);
const dataProd = await resProd.json();
categories = dataProd.categorias || [];
// Deduplicar productos para garantizar que nunca se repita ninguno
// 🚀 Ejecución paralela ultra rápida con Promise.all
const promises = [
fetch(`/api/productos?escuela_id=${escId}`).then(r => r.json()).catch(() => ({ categorias: [], productos: [] })),
loadCardDesigns()
];
if (!isStudent) {
promises.push(fetch('/api/estudiantes').then(r => r.json()).catch(() => []));
}
const [dataProd, _, resEst] = await Promise.all(promises);
if (dataProd) {
categories = dataProd.categorias || [];
const seenNames = new Set();
products = (dataProd.productos || []).filter(p => {
const key = String(p.nombre).trim().toLowerCase();
@@ -700,12 +729,14 @@ async function loadInitialData() {
seenNames.add(key);
return true;
});
renderCategories();
renderProducts();
}
// 3. Cargar catálogo de diseños de tarjetas
await loadCardDesigns();
if (!isStudent && Array.isArray(resEst)) {
students = resEst;
populateStudentSelector();
}
} catch (error) {
console.error('Error cargando datos iniciales:', error);
}
+22 -13
View File
@@ -1,5 +1,5 @@
// SiboPay PWA Service Worker v15.0 - Dashboard Ejecutivo de Padres & Persistencia Sesión F5
const CACHE_NAME = 'sibopay-v15.0';
// SiboPay PWA Service Worker v16.0 - Ultra Fast Startup & Stale-While-Revalidate
const CACHE_NAME = 'sibopay-v16.0';
const STATIC_ASSETS = [
'/',
'/index.html',
@@ -7,13 +7,13 @@ const STATIC_ASSETS = [
'/pistola.html',
'/carnet.html',
'/manifest.json',
'/css/styles.css',
'/css/desktop.css',
'/js/dialogs.js',
'/js/app.js',
'/css/styles.css?v=14.0',
'/css/desktop.css?v=2.2',
'/js/dialogs.js?v=13.8',
'/js/app.js?v=14.0',
'/js/pos.js',
'/js/sounds.js',
'/js/food-icons.js',
'/js/sounds.js?v=13.8',
'/js/food-icons.js?v=1.1',
'/icons/icon-192.png',
'/icons/icon-512.png',
'/img/sibopay-emblem.png',
@@ -46,11 +46,11 @@ self.addEventListener('activate', (event) => {
);
});
// Network-First con fallback a caché para navegación y recursos estáticos
// Estrategia Stale-While-Revalidate para apertura instantánea (0ms) en móviles
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
// APIs y Server-Sent Events (SSE): Directo a red sin caché
// APIs y Server-Sent Events (SSE): Directo a red en tiempo real sin caché
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/events')) {
return;
}
@@ -61,7 +61,9 @@ self.addEventListener('fetch', (event) => {
}
event.respondWith(
fetch(event.request)
caches.match(event.request).then((cachedResponse) => {
// Lanzar actualización en segundo plano (revalidate) sin bloquear la pantalla
const fetchPromise = fetch(event.request)
.then((networkResponse) => {
if (networkResponse && networkResponse.status === 200) {
const responseClone = networkResponse.clone();
@@ -72,12 +74,19 @@ self.addEventListener('fetch', (event) => {
return networkResponse;
})
.catch(() => {
return caches.match(event.request).then((cachedResponse) => {
if (cachedResponse) return cachedResponse;
// Si no hay red y era navegación, retornar index.html en caché
if (event.request.mode === 'navigate') {
return caches.match('/index.html');
}
});
// Si ya está en la memoria del teléfono, entregar INMEDIATAMENTE (<15ms)
if (cachedResponse) {
return cachedResponse;
}
// Si es la primera vez que se descarga, esperar la respuesta de red
return fetchPromise;
})
);
});
+14 -4
View File
@@ -89,9 +89,13 @@ async function sendWebPushNotification({ escuelaId = null, payload, roles = ['ad
}
}
const compression = require('compression');
const app = express();
const PORT = process.env.PORT || 3030;
// Compresión Gzip de alto rendimiento para HTML, JS, CSS y JSON
app.use(compression());
// Initialize DB schema & seed data
initDatabase();
@@ -114,12 +118,18 @@ app.get('/desktop-preview.html', (req, res) => {
res.redirect(301, '/');
});
// Servir archivos estáticos con compresión y caché optimizado para PWA
app.use(express.static(path.join(__dirname, '../public'), {
etag: false,
etag: true,
maxAge: '1d',
setHeaders: (res, filePath) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
// Para HTML y Service Worker: siempre revalidar para garantizar actualizaciones inmediatas
if (filePath.endsWith('.html') || filePath.endsWith('sw.js') || filePath.endsWith('manifest.json')) {
res.setHeader('Cache-Control', 'no-cache, must-revalidate');
} else {
// Para CSS, JS, imágenes y fuentes: permitir caché con stale-while-revalidate para arranque instantáneo
res.setHeader('Cache-Control', 'public, max-age=86400, stale-while-revalidate=604800');
}
}
}));