diff --git a/packages/libs/package.json b/packages/libs/package.json index b4c86e1..b1f2049 100644 --- a/packages/libs/package.json +++ b/packages/libs/package.json @@ -8,6 +8,7 @@ ".": "./src/index.ts", "./server": "./src/server.ts", "./*/server": "./src/*/server.ts", + "./pwa/plugin": "./src/pwa/plugin.ts", "./*": "./src/*/index.ts", "./package.json": "./package.json" }, diff --git a/packages/libs/src/index.ts b/packages/libs/src/index.ts index 4297d99..fb9eb22 100644 --- a/packages/libs/src/index.ts +++ b/packages/libs/src/index.ts @@ -75,3 +75,20 @@ export { storage, } from './local-storage'; export type { LocalStorageOptions } from './local-storage'; +export { + SERVICE_WORKER_CONFIG, + SERVICE_WORKER_URL, + captureInstallPrompt, + configureServiceWorker, + getInstallState, + getServerInstallState, + promptInstall, + registerServiceWorker, + subscribeInstallState, +} from './pwa'; +export type { + InstallOutcome, + InstallState, + ServiceWorkerConfig, + ServiceWorkerOptions, +} from './pwa'; diff --git a/packages/libs/src/pwa/constants.ts b/packages/libs/src/pwa/constants.ts new file mode 100644 index 0000000..d61efc2 --- /dev/null +++ b/packages/libs/src/pwa/constants.ts @@ -0,0 +1,37 @@ +import type { InstallState, ServiceWorkerConfig } from './types'; + +export const SERVICE_WORKER_URL = '/sw.js'; +export const SERVICE_WORKER_SCOPE = '/'; +export const CACHE_NAME_PREFIX = 'pwa-'; + +export const SERVICE_WORKER_CONFIG: ServiceWorkerConfig = { + // The default; only the developer switches an app to 'cache-first'. + strategy: 'stale-while-revalidate', + // Raise v1 when the worker changes what it stores or how it keys it. + cacheName: `${CACHE_NAME_PREFIX}assets-v1`, + cachePrefix: CACHE_NAME_PREFIX, + maxEntries: 200, + cacheLoadedMessage: 'pwa.cache-loaded', + paths: { + static: '/_next/static/', + fonts: '/fonts/', + sprite: '/icons/symbol-defs.svg', + }, +}; + +/** For `/sw.js` only: revalidated on every update check, and it can't reach another origin. */ +export const SERVICE_WORKER_HEADERS: Readonly> = { + 'Cache-Control': 'no-cache', + 'Content-Security-Policy': "default-src 'self'; script-src 'self'", +}; + +export const STANDALONE_QUERY = '(display-mode: standalone)'; + +/** The server and the first browser render know nothing about the device. */ +export const SERVER_INSTALL_STATE: InstallState = { + ready: false, + canInstall: false, + installed: false, + isIOS: false, + isStandalone: false, +}; diff --git a/packages/libs/src/pwa/index.ts b/packages/libs/src/pwa/index.ts new file mode 100644 index 0000000..d78eec3 --- /dev/null +++ b/packages/libs/src/pwa/index.ts @@ -0,0 +1,17 @@ +// The page side. Runs nothing at import, so the client bootstrap can import it during SSR. +// The build side (writeServiceWorker) is on the `/pwa/plugin` subpath; nothing goes in server.ts. +export { SERVICE_WORKER_CONFIG, SERVICE_WORKER_URL } from './constants'; +export { + captureInstallPrompt, + getInstallState, + getServerInstallState, + promptInstall, + subscribeInstallState, +} from './install'; +export { configureServiceWorker, registerServiceWorker } from './pwa'; +export type { + InstallOutcome, + InstallState, + ServiceWorkerConfig, + ServiceWorkerOptions, +} from './types'; diff --git a/packages/libs/src/pwa/install.ts b/packages/libs/src/pwa/install.ts new file mode 100644 index 0000000..6d19478 --- /dev/null +++ b/packages/libs/src/pwa/install.ts @@ -0,0 +1,103 @@ +import { SERVER_INSTALL_STATE, STANDALONE_QUERY } from './constants'; +import type { InstallOutcome, InstallState } from './types'; + +/** Chromium's deferred install prompt; not in TypeScript's DOM lib. */ +type BeforeInstallPromptEvent = Event & { + prompt: () => Promise; + userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>; +}; + +let state: InstallState = SERVER_INSTALL_STATE; +let deferred: BeforeInstallPromptEvent | null = null; +let capturing = false; +const listeners = new Set<() => void>(); + +function update(next: Partial): void { + state = { ...state, ...next }; + for (const listener of listeners) listener(); +} + +/** iPadOS asks for desktop pages, so an iPad says Macintosh, with touch. */ +function isIOSDevice(): boolean { + const { userAgent, maxTouchPoints } = navigator; + return ( + /iPad|iPhone|iPod/.test(userAgent) || + (/Macintosh/.test(userAgent) && maxTouchPoints > 1) + ); +} + +function isStandaloneNow(query: MediaQueryList): boolean { + return ( + query.matches || (navigator as { standalone?: boolean }).standalone === true + ); +} + +/** + * Starts listening for the browser's install offer (`beforeinstallprompt`, kept for + * `promptInstall`) and for `appinstalled`. Call it as early as the page's code runs, in the client + * bootstrap: the offer can come before React hydrates. Idempotent, and a no-op on the server. + */ +export function captureInstallPrompt(): void { + if (typeof window === 'undefined' || capturing) return; + capturing = true; + const standalone = window.matchMedia(STANDALONE_QUERY); + update({ + ready: true, + isIOS: isIOSDevice(), + isStandalone: isStandaloneNow(standalone), + }); + window.addEventListener('beforeinstallprompt', (event) => { + // The app offers the install itself (حساب کاربری › نصب اپلیکیشن, the خانه prompt), not the + // browser's mini-infobar. + event.preventDefault(); + deferred = event as BeforeInstallPromptEvent; + update({ canInstall: true }); + }); + window.addEventListener('appinstalled', () => { + deferred = null; + update({ canInstall: false, installed: true }); + }); + standalone.addEventListener('change', () => + update({ isStandalone: isStandaloneNow(standalone) }), + ); +} + +/** For `useSyncExternalStore`: starts the capture if the bootstrap hasn't. */ +export function subscribeInstallState(listener: () => void): () => void { + listeners.add(listener); + captureInstallPrompt(); + return () => listeners.delete(listener); +} + +/** The current state; the same object until something changes. */ +export function getInstallState(): InstallState { + return state; +} + +/** What the server and the first browser render use, so both match. */ +export function getServerInstallState(): InstallState { + return SERVER_INSTALL_STATE; +} + +/** + * Opens the browser's install dialog with the kept offer. An offer works once, so `canInstall` + * turns off when the dialog closes; the browser may offer again later. Call it from a press: + * browsers need the gesture. + */ +export async function promptInstall(): Promise { + const event = deferred; + if (!event) return 'unavailable'; + deferred = null; + try { + await event.prompt(); + const { outcome } = await event.userChoice; + update({ + canInstall: false, + installed: state.installed || outcome === 'accepted', + }); + return outcome; + } catch { + update({ canInstall: false }); + return 'unavailable'; + } +} diff --git a/packages/libs/src/pwa/plugin.ts b/packages/libs/src/pwa/plugin.ts new file mode 100644 index 0000000..89b7705 --- /dev/null +++ b/packages/libs/src/pwa/plugin.ts @@ -0,0 +1,5 @@ +// The build side, on the `@lumina/libs/pwa/plugin` subpath. Node only (it reads and writes files): +// only build configs import it, and no root entry re-exports it. +export { SERVICE_WORKER_HEADERS, SERVICE_WORKER_URL } from './constants'; +export { writeServiceWorker } from './service-worker-plugin'; +export type { CacheStrategy, ServiceWorkerPluginOptions } from './types'; diff --git a/packages/libs/src/pwa/pwa.ts b/packages/libs/src/pwa/pwa.ts new file mode 100644 index 0000000..41731a2 --- /dev/null +++ b/packages/libs/src/pwa/pwa.ts @@ -0,0 +1,69 @@ +import { + CACHE_NAME_PREFIX, + SERVICE_WORKER_CONFIG, + SERVICE_WORKER_SCOPE, + SERVICE_WORKER_URL, +} from './constants'; +import type { CacheLoadedMessage, ServiceWorkerOptions } from './types'; + +let options: ServiceWorkerOptions = { enabled: false }; + +/** Runs once, in the client bootstrap, with `enabled` from the app's env. Only stores the options. */ +export function configureServiceWorker(next: ServiceWorkerOptions): void { + options = next; +} + +/** + * Runs once per page load, in an effect of the platform's AppShell. Registers `/sw.js` after the + * window's `load` when enabled, or unregisters every worker and deletes every `pwa-` cache when + * not (the kill switch). Returns at once; the work happens in the background. + */ +export function registerServiceWorker(): void { + if (typeof window === 'undefined') { + throw new Error( + 'registerServiceWorker is browser-only; call it in an effect', + ); + } + if (!('serviceWorker' in navigator)) return; + // Best effort: the site works the same without the worker. + void (options.enabled ? register() : unregister()).catch(() => undefined); +} + +async function register(): Promise { + const wasControlled = navigator.serviceWorker.controller !== null; + await loaded(); + await navigator.serviceWorker.register(SERVICE_WORKER_URL, { + scope: SERVICE_WORKER_SCOPE, + updateViaCache: 'none', + }); + if (wasControlled) return; + + // The page loaded before the worker controlled it, so the worker stores what the page already has. + const { active } = await navigator.serviceWorker.ready; + const message: CacheLoadedMessage = { + type: SERVICE_WORKER_CONFIG.cacheLoadedMessage, + urls: performance.getEntriesByType('resource').map((entry) => entry.name), + }; + active?.postMessage(message); +} + +async function unregister(): Promise { + const registrations = await navigator.serviceWorker.getRegistrations(); + await Promise.all( + registrations.map((registration) => registration.unregister()), + ); + const names = await caches.keys(); + await Promise.all( + names + .filter((name) => name.startsWith(CACHE_NAME_PREFIX)) + .map((name) => caches.delete(name)), + ); +} + +/** The worker never competes with the page for the network. */ +function loaded(): Promise { + if (document.readyState === 'complete') return Promise.resolve(); + return new Promise((resolve) => + window.addEventListener('load', () => resolve(), { once: true }), + ); +} diff --git a/packages/libs/src/pwa/service-worker-plugin.ts b/packages/libs/src/pwa/service-worker-plugin.ts new file mode 100644 index 0000000..37374f9 --- /dev/null +++ b/packages/libs/src/pwa/service-worker-plugin.ts @@ -0,0 +1,47 @@ +import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import ts from 'typescript'; + +import { SERVICE_WORKER_CONFIG, SERVICE_WORKER_URL } from './constants'; +import type { ServiceWorkerPluginOptions } from './types'; + +/** The worker's source, resolved from this file, so the plugin works from every app. */ +const WORKER_SOURCE = fileURLToPath( + new URL('./service-worker.ts', import.meta.url), +); + +/** + * Compiles the worker with the workspace's own TypeScript, writes `SERVICE_WORKER_CONFIG` above it + * (with the developer's `strategy` when one is passed), and saves it as `/sw.js`. + * Build-time only: import it from `next.config.ts`, never from app code. + */ +export function writeServiceWorker({ + publicDir, + strategy, +}: ServiceWorkerPluginOptions): void { + const { outputText } = ts.transpileModule( + readFileSync(WORKER_SOURCE, 'utf8'), + { + compilerOptions: { + target: ts.ScriptTarget.ES2022, + removeComments: true, + }, + }, + ); + const config = { + ...SERVICE_WORKER_CONFIG, + strategy: strategy ?? SERVICE_WORKER_CONFIG.strategy, + }; + // The config goes under TypeScript's "use strict", which only counts as the script's first line. + const body = outputText.replace(/^"use strict";\n/, ''); + const script = `"use strict";\nconst SERVICE_WORKER_CONFIG = ${JSON.stringify(config)};\n${body}`; + const file = path.join(publicDir, SERVICE_WORKER_URL); + // The same bytes again would restart the dev server's file watchers for nothing. + if (existsSync(file) && readFileSync(file, 'utf8') === script) return; + // Next can run this in more than one process: no request ever sees half a worker. + const temp = `${file}.${process.pid}.tmp`; + writeFileSync(temp, script); + renameSync(temp, file); +} diff --git a/packages/libs/src/pwa/service-worker.ts b/packages/libs/src/pwa/service-worker.ts new file mode 100644 index 0000000..50af960 --- /dev/null +++ b/packages/libs/src/pwa/service-worker.ts @@ -0,0 +1,191 @@ +// A classic script: no import or export, so writeServiceWorker can emit it as one file. +// writeServiceWorker writes SERVICE_WORKER_CONFIG above it. Type-checked by tsconfig.worker.json +// (the WebWorker lib); the lib's main tsconfig leaves it out. + +declare const SERVICE_WORKER_CONFIG: import('./types').ServiceWorkerConfig; + +type InstallEventWithRoutes = ExtendableEvent & { + addRoutes?: ( + rules: { condition: { requestMode: RequestMode }; source: 'network' }[], + ) => Promise; +}; + +const worker = self as unknown as ServiceWorkerGlobalScope; +const { + strategy, + cacheName, + cachePrefix, + maxEntries, + cacheLoadedMessage, + paths, +} = SERVICE_WORKER_CONFIG; + +/** JS and CSS from /_next/static/, fonts from /fonts/, and the icon sprite: nothing else. */ +function isStoredKind(url: URL): boolean { + if (url.origin !== worker.location.origin) return false; + const { pathname } = url; + if (pathname.startsWith(paths.static)) { + return pathname.endsWith('.js') || pathname.endsWith('.css'); + } + if (pathname.startsWith(paths.fonts)) return pathname.endsWith('.woff2'); + return pathname === paths.sprite; +} + +function isStorable(response: Response): boolean { + return ( + response.status === 200 && response.type === 'basic' && !response.redirected + ); +} + +async function store(request: Request, response: Response): Promise { + try { + const cache = await caches.open(cacheName); + if (new URL(request.url).pathname === paths.sprite) { + // One sprite: a new ?v= replaces the older ones. + const versions = await cache.keys(request, { ignoreSearch: true }); + await Promise.all(versions.map((version) => cache.delete(version))); + } + await cache.put(request, response); + const keys = await cache.keys(); + await Promise.all( + keys + .slice(0, Math.max(0, keys.length - maxEntries)) + .map((key) => cache.delete(key)), + ); + } catch { + // A full or blocked cache costs one network request next time, nothing more. + } +} + +// Matching validators mean the same file. A response without one counts as changed. +function isSameFile(stored: Response, fresh: Response): boolean { + const validator = (response: Response) => + response.headers.get('etag') ?? response.headers.get('last-modified'); + const freshValidator = validator(fresh); + return freshValidator !== null && freshValidator === validator(stored); +} + +async function fromNetwork( + event: FetchEvent, + stored?: Response, +): Promise { + const response = await fetch(event.request); + if (isStorable(response) && !(stored && isSameFile(stored, response))) { + event.waitUntil(store(event.request, response.clone())); + } + return response; +} + +async function staleWhileRevalidate(event: FetchEvent): Promise { + const stored = await caches.match(event.request, { + cacheName, + ignoreVary: true, + }); + const fresh = fromNetwork(event, stored); + if (!stored) return fresh; + // The check finishes after the response; when it fails, the stored copy stays. + event.waitUntil( + fresh.then( + () => undefined, + () => undefined, + ), + ); + return stored; +} + +async function cacheFirst(event: FetchEvent): Promise { + const stored = await caches.match(event.request, { + cacheName, + ignoreVary: true, + }); + return stored ?? fromNetwork(event); +} + +const respond = strategy === 'cache-first' ? cacheFirst : staleWhileRevalidate; + +function toStoredKindUrl(value: unknown): URL | null { + if (typeof value !== 'string') return null; + try { + const url = new URL(value); + return isStoredKind(url) ? url : null; + } catch { + return null; + } +} + +async function storeLoaded(urls: unknown[]): Promise { + const wanted = urls + .map(toStoredKindUrl) + .filter((url): url is URL => url !== null); + await Promise.all( + wanted.slice(0, maxEntries).map(async (url) => { + if (await caches.match(url.href, { cacheName, ignoreVary: true })) return; + // The page loaded it a moment ago, so the HTTP cache answers. + const response = await fetch(url.href).catch(() => null); + if (response && isStorable(response)) { + await store(new Request(url.href), response); + } + }), + ); +} + +worker.addEventListener('install', (event) => { + void worker.skipWaiting(); + // Chromium sends navigations straight to the network, so the worker never starts only to let a + // page through. Other browsers use navigation preload (activate). + const routable = event as InstallEventWithRoutes; + if (!routable.addRoutes) return; + event.waitUntil( + routable + .addRoutes([ + { condition: { requestMode: 'navigate' }, source: 'network' }, + ]) + .catch(() => undefined), + ); +}); + +worker.addEventListener('activate', (event) => { + event.waitUntil( + (async () => { + await worker.registration.navigationPreload + ?.enable() + .catch(() => undefined); + const names = await caches.keys(); + await Promise.all( + names + .filter((name) => name.startsWith(cachePrefix) && name !== cacheName) + .map((name) => caches.delete(name)), + ); + await worker.clients.claim(); + })(), + ); +}); + +worker.addEventListener('fetch', (event) => { + const { request } = event; + if (request.method !== 'GET') return; + if (request.mode === 'navigate') { + // Passed through, never stored. + event.respondWith( + Promise.resolve(event.preloadResponse).then( + (preloaded?: Response) => preloaded ?? fetch(request), + ), + ); + return; + } + // DevTools sends these; fetch rejects them. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + return; + } + if (isStoredKind(new URL(request.url))) event.respondWith(respond(event)); +}); + +worker.addEventListener('message', (event) => { + // The worker trusts no message: storeLoaded checks every URL again. + const message = event.data as Partial< + import('./types').CacheLoadedMessage + > | null; + if (message?.type === cacheLoadedMessage && Array.isArray(message.urls)) { + event.waitUntil(storeLoaded(message.urls)); + } +}); diff --git a/packages/libs/src/pwa/types.ts b/packages/libs/src/pwa/types.ts new file mode 100644 index 0000000..cc7e7b2 --- /dev/null +++ b/packages/libs/src/pwa/types.ts @@ -0,0 +1,59 @@ +/** The page side's settings, from the app's env. */ +export type ServiceWorkerOptions = { + /** From the app's env; false unregisters the worker and deletes its caches (the kill switch). */ + enabled: boolean; +}; + +export type CacheStrategy = 'stale-while-revalidate' | 'cache-first'; + +/** The worker's settings. writeServiceWorker writes them into public/sw.js; the worker reads nothing else. */ +export type ServiceWorkerConfig = { + /** 'stale-while-revalidate' unless the developer explicitly chose 'cache-first'. */ + strategy: CacheStrategy; + /** The one cache, such as 'pwa-assets-v1'. */ + cacheName: string; + /** Every cache this lib owns starts with it. */ + cachePrefix: string; + /** Above it, the oldest entries go first. */ + maxEntries: number; + /** The type of the message that lists what the page already loaded. */ + cacheLoadedMessage: string; + paths: { + /** '/_next/static/': .js and .css only. */ + static: string; + /** '/fonts/': .woff2 only. */ + fonts: string; + /** '/icons/symbol-defs.svg', stored with its ?v=. */ + sprite: string; + }; +}; + +/** The page lists what it loaded before the worker controlled it. */ +export type CacheLoadedMessage = { + type: string; + urls: string[]; +}; + +export type ServiceWorkerPluginOptions = { + /** Absolute path of the app's public/. */ + publicDir: string; + /** Only when the developer explicitly changes it; 'stale-while-revalidate' by default. */ + strategy?: CacheStrategy; +}; + +/** What the browser says about installing the app, from `beforeinstallprompt` and `appinstalled`. */ +export type InstallState = { + /** false on the server and in the first browser render, so both match: nothing is known yet. */ + ready: boolean; + /** The browser offered the install (`beforeinstallprompt`), so `promptInstall` opens its dialog. */ + canInstall: boolean; + /** Installed during this page load (`appinstalled`, or the person accepted the dialog). */ + installed: boolean; + /** iPhone or iPad, where only the share menu's «Add to Home Screen» installs. */ + isIOS: boolean; + /** Running as the installed app (display mode standalone, or iOS's `navigator.standalone`). */ + isStandalone: boolean; +}; + +/** How the browser's install dialog ended; `unavailable` when it couldn't be opened. */ +export type InstallOutcome = 'accepted' | 'dismissed' | 'unavailable'; diff --git a/packages/libs/tsconfig.json b/packages/libs/tsconfig.json index c23e61c..92bf9d8 100644 --- a/packages/libs/tsconfig.json +++ b/packages/libs/tsconfig.json @@ -5,6 +5,9 @@ "references": [ { "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.worker.json" } ] } diff --git a/packages/libs/tsconfig.lib.json b/packages/libs/tsconfig.lib.json index 2d842f2..a34d29e 100644 --- a/packages/libs/tsconfig.lib.json +++ b/packages/libs/tsconfig.lib.json @@ -6,21 +6,14 @@ "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", "emitDeclarationOnly": true, "forceConsistentCasingInFileNames": true, - "types": [ - "node" - ], - "lib": [ - "es2022", - "dom", - "dom.iterable" - ] + "types": ["node"], + "lib": ["es2022", "dom", "dom.iterable"] }, - "include": [ - "src/**/*.ts" - ], + "include": ["src/**/*.ts"], "references": [ { "path": "../tools/tsconfig.lib.json" } - ] + ], + "exclude": ["src/pwa/service-worker.ts"] } diff --git a/packages/libs/tsconfig.worker.json b/packages/libs/tsconfig.worker.json new file mode 100644 index 0000000..a6e3d99 --- /dev/null +++ b/packages/libs/tsconfig.worker.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist/worker", + "tsBuildInfoFile": "dist/tsconfig.worker.tsbuildinfo", + "emitDeclarationOnly": true, + "forceConsistentCasingInFileNames": true, + "types": [], + "lib": ["es2022", "webworker"] + }, + "include": ["src/pwa/service-worker.ts", "src/pwa/types.ts"] +}