@ordojs/mobile
Version:
Mobile and PWA support for OrdoJS applications
145 lines (135 loc) • 5.86 kB
JavaScript
var r=class{config;swConfig;constructor(e,t){this.config=e,this.swConfig=t;}generateManifest(){let e={name:this.config.name,short_name:this.config.shortName,description:this.config.description,start_url:this.config.startUrl,display:this.config.display,theme_color:this.config.themeColor,background_color:this.config.backgroundColor,icons:this.config.icons,categories:this.config.categories,lang:this.config.lang,dir:this.config.dir,orientation:this.config.orientation,scope:this.config.scope,prefer_related_applications:this.config.preferRelatedApplications,related_applications:this.config.relatedApplications};return JSON.stringify(e,null,2)}generateServiceWorker(){return `
// OrdoJS Service Worker
const CACHE_NAME = 'ordojs-cache-v1';
const STATIC_CACHE = 'static-cache-v1';
const DYNAMIC_CACHE = 'dynamic-cache-v1';
// Install event
self.addEventListener('install', (event) => {
console.log('Service Worker installing...');
event.waitUntil(
caches.open(STATIC_CACHE).then((cache) => {
return cache.addAll([
'/',
'/offline.html',
'/static/css/main.css',
'/static/js/main.js'
]);
})
);
self.skipWaiting();
});
// Activate event
self.addEventListener('activate', (event) => {
console.log('Service Worker activating...');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== STATIC_CACHE && cacheName !== DYNAMIC_CACHE) {
return caches.delete(cacheName);
}
})
);
})
);
self.clients.claim();
});
// Fetch event
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Handle different cache strategies
${this.generateCacheStrategies()}
// Background sync
${this.generateBackgroundSync()}
// Push notifications
${this.generatePushNotifications()}
});
${this.generateCacheStrategies()}
${this.generateBackgroundSync()}
${this.generatePushNotifications()}
`.trim()}generateCacheStrategies(){let e="";return this.swConfig.cacheStrategies.forEach(t=>{e+=`
// ${t.name} strategy
if (${this.generatePatternMatcher(t.pattern)}) {
event.respondWith(
${this.generateStrategyHandler(t)}
);
return;
}
`;}),e}generatePatternMatcher(e){return e.includes("*")?`url.pathname.match(/^${e.replace(/\*/g,".*")}$/)`:`url.pathname === '${e}'`}generateStrategyHandler(e){switch(e.strategy){case "cache-first":return `
caches.match(request).then((response) => {
return response || fetch(request).then((fetchResponse) => {
return caches.open(DYNAMIC_CACHE).then((cache) => {
cache.put(request, fetchResponse.clone());
return fetchResponse;
});
});
})
`;case "network-first":return `
fetch(request).then((response) => {
return caches.open(DYNAMIC_CACHE).then((cache) => {
cache.put(request, response.clone());
return response;
});
}).catch(() => {
return caches.match(request);
})
`;case "stale-while-revalidate":return `
caches.match(request).then((cachedResponse) => {
const fetchPromise = fetch(request).then((networkResponse) => {
return caches.open(DYNAMIC_CACHE).then((cache) => {
cache.put(request, networkResponse.clone());
return networkResponse;
});
});
return cachedResponse || fetchPromise;
})
`;case "network-only":return "fetch(request)";case "cache-only":return "caches.match(request)";default:return "fetch(request)"}}generateBackgroundSync(){return this.swConfig.backgroundSync.enabled?`
// Background sync
self.addEventListener('sync', (event) => {
if (event.tag === '${this.swConfig.backgroundSync.syncName}') {
event.waitUntil(
// Perform background sync operations
console.log('Background sync triggered');
);
}
});
`:""}generatePushNotifications(){return this.swConfig.pushNotifications.enabled?`
// Push notifications
self.addEventListener('push', (event) => {
const options = {
body: event.data ? event.data.text() : 'New notification',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{
action: 'explore',
title: 'View',
icon: '/icon-192x192.png'
},
{
action: 'close',
title: 'Close',
icon: '/icon-192x192.png'
}
]
};
event.waitUntil(
self.registration.showNotification('${this.config.name}', options)
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
if (event.action === 'explore') {
event.waitUntil(
clients.openWindow('/')
);
}
});
`:""}registerServiceWorker(){return "serviceWorker"in navigator?navigator.serviceWorker.register("/sw.js",{scope:this.swConfig.scope,updateViaCache:this.swConfig.updateViaCache}):Promise.resolve(null)}isInstalled(){return window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone===true}showInstallPrompt(){return new Promise((e,t)=>{if("BeforeInstallPromptEvent"in window){let i=new Event("beforeinstallprompt");window.dispatchEvent(i),window.addEventListener("beforeinstallprompt",n=>{n.preventDefault(),n.prompt(),e();});}else t(new Error("Install prompt not supported"));})}updateConfig(e){this.config={...this.config,...e};}updateServiceWorkerConfig(e){this.swConfig={...this.swConfig,...e};}getConfig(){return {...this.config}}getServiceWorkerConfig(){return {...this.swConfig}}};export{r as PWAManager};//# sourceMappingURL=pwa.mjs.map
//# sourceMappingURL=pwa.mjs.map