versione 1.2.14 :

- aggiornati i file di configurazione, ENV e script non funzionanti., package.
- corretto custom-service-worker.js con CORS
- ottimizzato il server, la chiamata Load iniziale (senza promise, con async/await).
This commit is contained in:
Surya Paolo
2025-03-12 21:02:51 +01:00
parent cc541b1e6f
commit 834203ffbb
135 changed files with 572 additions and 1965 deletions

View File

@@ -3,23 +3,19 @@
/* global workbox */
/* global cfgenv */
importScripts('/workbox/workbox-sw.js'); // 7.3.0
const CACHE_NAME = 'pwa-cache-v2'; // Nome della cache
if (workbox) {
console.log('Workbox ESISTE ✅ ');
const ORA = "12.57"
// Imposta configurazione prima di tutto
const debug = process.env.NODE_ENV !== 'production';
workbox.setConfig({ debug });
console.log('***** INIZIO CUSTOM-SERVICE-WORKER.JS ' + ORA);
workbox.precaching.precacheAndRoute([]);
} else {
console.error('Workbox NON CARICATO ! ❌');
}
//importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');
importScripts('workbox/workbox-sw.js')
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { clientsClaim } from 'workbox-core'
import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute, NavigationRoute } from 'workbox-routing';
import { setCacheNameDetails } from 'workbox-core';
import {
NetworkOnly,
@@ -30,10 +26,25 @@ import {
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { ExpirationPlugin } from 'workbox-expiration';
const debug = process.env.NODE_ENV !== 'production';
if (workbox) {
// Imposta configurazione prima di tutto
workbox.setConfig({ debug });
workbox.loadModule('workbox-strategies');
console.log('Workbox ESISTE ✅ ' + ORA);
} else {
console.error('Workbox NON CARICATO ! ❌');
}
setCacheNameDetails({
prefix: self.location.hostname,
suffix: 'v1',
suffix: 'v2',
precache: 'precache',
runtime: 'runtime',
});
@@ -49,40 +60,33 @@ const precacheList = (self.__WB_MANIFEST || []).filter(entry => {
// Precache solo i file filtrati
precacheAndRoute(precacheList);
// importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');
cleanupOutdatedCaches()
// Installazione del Service Worker
self.addEventListener('install', () => {
console.log('Service Worker: Skip...');
console.log('[Service Worker] Installing ...');
self.skipWaiting()
clientsClaim();
});
// Attivazione del Service Worker
self.addEventListener('activate', (event) => {
console.log('Service Worker: Activated');
// Pulizia delle cache obsolete durante l'attivazione
console.log('[Service Worker] Activating...');
event.waitUntil(
(async () => {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.map((cacheName) => {
if (!cacheName.startsWith(`${self.location.hostname}-v1`)) {
return caches.delete(cacheName);
}
})
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
);
// Reclama immediatamente il controllo delle pagine
self.clients.claim();
})()
})
);
});
const VITE_APP_VERSION = "1.2.13";
const VITE_APP_VERSION = "1.2.2";
console.log(' [ VER-' + VITE_APP_VERSION + ' ] _---------________------ PAO: this is my custom service worker');
console.log(' [ VER-' + VITE_APP_VERSION + ' ] _---------________------ PAO: this is my custom service worker: ' + ORA);
try {
importScripts('/js/idb.js', '/js/storage.js');
@@ -118,6 +122,14 @@ async function deleteItemFromData(table, id) {
if (workbox) {
if (process.env.MODE !== 'ssr' || process.env.PROD) {
registerRoute(
new NavigationRoute(
createHandlerBoundToURL(process.env.PWA_FALLBACK_HTML),
{ denylist: [new RegExp(process.env.PWA_SERVICE_WORKER_REGEX), /workbox\workbox-(.)*\.js$/] }
)
)
}
// Cache strategy registrations
registerRoute(
@@ -236,7 +248,7 @@ if (workbox) {
}
// Costanti di configurazione
const DYNAMIC_CACHE = 'dynamic-cache-v1';
const DYNAMIC_CACHE = 'dynamic-cache-v2';
const ENABLE_DYNAMIC_CACHING = true;
const baseUrl = self.location.origin;
console.log('baseUrl', baseUrl);
@@ -260,123 +272,92 @@ if (workbox) {
'Accept': 'application/json',
},
mode: 'cors',
// credentials: 'include'
credentials: 'include', // Abilita le credenziali (cookie, token)
});
try {
const response = await fetch(modifiedRequest);
// Se la risposta è ok, restituiscila
// Se la risposta è valida, restituiscila
if (response.ok) {
return response;
}
// Se riceviamo un errore CORS, prova con una richiesta no-cors
if (response.status === 0 || response.type === 'opaque' || response.headers.get('Access-Control-Allow-Origin') !== `https://${APP_DOMAIN}`) {
console.log('[Service Worker] Fallback to no-cors mode for:', request.url);
return fetch(new Request(request.url, {
method: 'GET',
mode: 'no-cors',
// credentials: 'include'
}));
}
// Logga eventuali errori
console.warn('[Service Worker] API response not OK:', response.status, response.statusText);
return response;
} catch (error) {
console.error('[Service Worker] API request error ❌:', error);
// Restituisci una risposta di errore personalizzata
return new Response(JSON.stringify({
error: 'Network error',
message: 'Unable to fetch from API'
message: 'Unable to fetch from API: ' + error.message,
}), {
status: 503,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': `https://${APP_DOMAIN}`,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
}
},
});
}
}
// Funzione principale per gestire il fetch
async function handleFetch(request) {
// Strategia di caching: stale-while-revalidate
async function cacheWithStaleWhileRevalidate(request) {
const cache = await caches.open(CACHE_NAME);
// Prova a recuperare la risorsa dalla cache
const cachedResponse = await cache.match(request);
if (cachedResponse) {
// Restituisci la risposta in cache mentre aggiorni in background
fetchAndCache(request);
return cachedResponse;
}
// Se non è in cache, fai la richiesta di rete
return fetchAndCache(request);
}
// Funzione per fare la richiesta di rete e aggiornare la cache
async function fetchAndCache(request) {
const cache = await caches.open(CACHE_NAME);
try {
// Verifica se è una richiesta all'API
const url = new URL(request.url);
const isApiRequest = url.hostname === API_DOMAIN;
// Se è una richiesta API, gestiscila separatamente
if (isApiRequest) {
return handleApiRequest(request);
}
// Per le altre richieste, prova prima la cache
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
// Se non è in cache, fai la richiesta di rete
const response = await fetch(request);
// Verifica la validità della risposta
if (!response || (!response.ok && response.type !== 'opaque')) {
console.warn('[Service Worker] Invalid response for:', request.url);
return response;
if (response.ok) {
cache.put(request, response.clone());
}
// Cache solo le risorse dello stesso origine
if (ENABLE_DYNAMIC_CACHING && !isCrossOrigin(request.url)) {
try {
const cache = await caches.open(DYNAMIC_CACHE);
cache.put(request, response.clone());
} catch (cacheError) {
console.error('[Service Worker] Cache error ❌:', cacheError);
}
}
return response;
} catch (error) {
console.error('[Service Worker] Fetch error: ❌', error, request);
// Personalizza la risposta di errore in base al tipo di richiesta
if (request.headers.get('Accept')?.includes('application/json')) {
return new Response(JSON.stringify({
error: 'Network error',
message: 'Servizio non disponibile, riprovare !'
}), {
status: 503,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': `https://${APP_DOMAIN}`
}
});
}
return new Response('Network error', {
status: 503,
statusText: 'Internet non disponibile (503)'
});
console.error('[Service Worker] Fetch and cache error ❌:', error);
return new Response('Network error', { status: 503 });
}
}
// Listener per gestire tutte le richieste
self.addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
// Ignora richieste non gestibili
if (event.request.method !== 'GET' ||
event.request.url.startsWith('chrome-extension://')) {
if (request.method !== 'GET' || url.protocol !== 'https:') {
return;
}
// Gestione richieste API
const url = new URL(event.request.url);
if (url.origin === API_DOMAIN) {
event.respondWith(handleApiRequest(event.request));
if (url.hostname === API_DOMAIN) {
if (debug) {
console.log('E\' una RICHIESTA API ! ')
}
event.respondWith(handleApiRequest(request));
return;
}
// Default handler per altre richieste
event.respondWith(handleFetch(event.request));
if (debug) {
console.log('E\' una RICHIESTA statica...')
}
// Gestione risorse statiche e altre richieste
event.respondWith(cacheWithStaleWhileRevalidate(request));
});
@@ -506,3 +487,5 @@ if (workbox) {
} else {
console.warn('Workbox could not be loaded.');
}
console.log('***** FINE CUSTOM-SERVICE-WORKER.JS ***** ');