Pwa

From j4flmao/agent-skills · View interactive version

Pwa is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks to make the site installable and work offline, PWA, web app manifest, service worker with Workbox or vite-plugin-pwa, update prompts, background sync or web push. Produces manifest, caching strategies and a safe update flow with real browser limits. Not for HTTP cache headers

How to use this skill

Skill file

Progressive Web Apps

Purpose

A PWA is a web app with a manifest (installability, app identity) and a service worker (network proxy enabling offline, caching and push). This skill produces a manifest that installs on all major platforms, a Workbox service worker with per-resource caching strategies, an update flow that never strands users on stale code, and offline/push features with honest support caveats.

Agent Protocol

Trigger

"pwa", "service worker", "offline", "manifest.json", "install prompt", "workbox", "vite-plugin-pwa", "web push", "background sync", "new version available".

Input Context

Output Artifact

manifest.webmanifest, service worker (Workbox or plugin config), registration/update UI code.

Response Format

Install: manifest fields + icons {sizes, purpose}
Precache: {app shell files}
Runtime routes: {pattern -> strategy, cache name, expiration}
Offline: {fallback page | IndexedDB queue}
Update flow: {prompt | auto} 
Push: {VAPID, permission trigger, platforms}

Do You Need It?

| Need | PWA fit |

|------|---------|

| Works on flaky networks, field/retail apps | Strong |

| Installable icon, standalone window without app stores | Strong |

| Re-engagement via notifications | Good (iOS/iPadOS 16.4+ only for home-screen-installed apps) |

| Bluetooth/NFC/background location, heavy background work | Weak — Web Bluetooth/NFC are Chromium-only; SW background execution is limited |

| Static content site | Optional; a simple offline page may be enough |

Manifest

{
  "id": "/",
  "name": "Acme Field Service",
  "short_name": "Acme",
  "start_url": "/?source=pwa",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#1d4ed8",
  "icons": [
    { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
    { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
    { "src": "/icons/maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
  ],
  "screenshots": [
    { "src": "/screenshots/wide.png", "sizes": "1280x800", "type": "image/png", "form_factor": "wide" },
    { "src": "/screenshots/narrow.png", "sizes": "720x1280", "type": "image/png", "form_factor": "narrow" }
  ]
}

Strategy per Resource

| Resource | Strategy | Notes |

|----------|----------|-------|

| Hashed JS/CSS from the build | Precache (installed with SW) | Revisioned automatically by Workbox |

| HTML navigations | NetworkFirst with short timeout, offline fallback | Avoid serving stale HTML that references deleted chunks |

| Images | StaleWhileRevalidate or CacheFirst + expiration | Cap entries; opaque cross-origin responses cost quota |

| Public API reads (non-personal) | NetworkFirst (timeout) or StaleWhileRevalidate | |

| Authenticated/personal API data | NetworkOnly, or cache per user and clear on logout | Shared devices leak data otherwise |

| Analytics, payments, auth endpoints | NetworkOnly | |

Workbox Service Worker (injectManifest)

// src/sw.ts
/// <reference lib="webworker" />
import { precacheAndRoute, cleanupOutdatedCaches, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute, NavigationRoute, setCatchHandler } from 'workbox-routing';
import { NetworkFirst, StaleWhileRevalidate, NetworkOnly } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { BackgroundSyncPlugin } from 'workbox-background-sync';

declare const self: ServiceWorkerGlobalScope & { __WB_MANIFEST: Array<{ url: string; revision: string | null }> };

precacheAndRoute(self.__WB_MANIFEST);   // includes /offline.html via globPatterns
cleanupOutdatedCaches();

registerRoute(
  new NavigationRoute(
    new NetworkFirst({ cacheName: 'pages', networkTimeoutSeconds: 3, plugins: [new CacheableResponsePlugin({ statuses: [200] })] }),
    { denylist: [/^\/api\//, /^\/auth\//] },
  ),
);

registerRoute(
  ({ request }) => request.destination === 'image',
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [new ExpirationPlugin({ maxEntries: 100, maxAgeSeconds: 30 * 24 * 3600, purgeOnQuotaError: true })],
  }),
);

registerRoute(
  ({ url }) => url.pathname.startsWith('/api/public/'),
  new NetworkFirst({ cacheName: 'api-public', networkTimeoutSeconds: 3, plugins: [new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 300 })] }),
);

// Offline writes: failed POSTs are queued and replayed (Background Sync API in Chromium; Workbox
// falls back to replaying on the next SW startup in other browsers)
registerRoute(
  ({ url, request }) => url.pathname === '/api/notes' && request.method === 'POST',
  new NetworkOnly({ plugins: [new BackgroundSyncPlugin('notes-queue', { maxRetentionTime: 24 * 60 })] }),
  'POST',
);

setCatchHandler(async ({ request }) => {
  if (request.destination === 'document') {
    const offline = await caches.match('/offline.html');
    if (offline) return offline;
  }
  return Response.error();
});

// Update flow: only activate when the page asks (user accepted the prompt)
self.addEventListener('message', (event) => {
  if (event.data?.type === 'SKIP_WAITING') void self.skipWaiting();
});

POST replays must be idempotent on the server (send an Idempotency-Key), because a request can be delivered more than once.

vite-plugin-pwa

// vite.config.ts
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
  plugins: [
    VitePWA({
      strategies: 'injectManifest',
      srcDir: 'src',
      filename: 'sw.ts',
      registerType: 'prompt',
      injectManifest: { globPatterns: ['**/*.{js,css,html,svg,png,woff2}'] },
      manifest: false, // using public/manifest.webmanifest
    }),
  ],
});
// UpdatePrompt.tsx (React; vue/svelte variants exist)
import { useRegisterSW } from 'virtual:pwa-register/react';

export function UpdatePrompt() {
  const { needRefresh: [needRefresh, setNeedRefresh], updateServiceWorker } = useRegisterSW({
    onRegisterError(error) { console.error('Service worker registration failed', error); },
  });
  if (!needRefresh) return null;
  return (
    <div role="status">
      A new version is available.
      <button onClick={() => updateServiceWorker(true)}>Reload</button>
      <button onClick={() => setNeedRefresh(false)}>Later</button>
    </div>
  );
}

Update Lifecycle Rules

Web Push

export async function subscribeToPush(vapidPublicKey: string): Promise<PushSubscription> {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    throw new Error('Push not supported in this browser (on iOS, install to Home Screen first)');
  }
  const permission = await Notification.requestPermission(); // call from a click handler
  if (permission !== 'granted') throw new Error(`Notification permission ${permission}`);
  const reg = await navigator.serviceWorker.ready;
  const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidPublicKey });
  const res = await fetch('/api/push/subscriptions', {
    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sub),
  });
  if (!res.ok) throw new Error(`Saving push subscription failed: ${res.status}`);
  return sub;
}
// in sw.ts
self.addEventListener('push', (event) => {
  const data = event.data?.json() as { title: string; body: string; url: string } | undefined;
  if (!data) return;
  event.waitUntil(self.registration.showNotification(data.title, { body: data.body, icon: '/icons/icon-192.png', data: { url: data.url } }));
});
self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(self.clients.openWindow(event.notification.data.url));
});

Storage

Testing

Anti-patterns

| Anti-pattern | Fix |

|--------------|-----|

| Unconditional skipWaiting() + lazy chunks | Prompt-based update |

| CacheFirst for HTML | NetworkFirst with offline fallback |

| Caching personal API responses in shared caches | NetworkOnly or per-user caches cleared on logout |

| Permission prompt on load | Ask in context after user intent |

| No cleanupOutdatedCaches() / cache versioning | Clean old caches on activate |

| Assuming Background Sync everywhere | Workbox fallback + visible "pending" UI |

Checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.