MEGAINFRA-WEBAPP/src/lib/pwa-registration.ts

21 lines
1 KiB
TypeScript

type PwaEnvironment={
production:boolean;
serviceWorker:Pick<ServiceWorkerContainer,'register'|'getRegistrations'|'controller'>;
origin:string;
reload:()=>void;
};
/** Development assets must not be controlled by a worker generated by a production build. */
export async function configurePwa({production,serviceWorker,origin,reload}:PwaEnvironment){
if(production){await serviceWorker.register('/sw.js',{scope:'/'});return;}
const workerUrl=new URL('/sw.js',origin).href;
const registrations=await serviceWorker.getRegistrations();
let removed=false;
for(const registration of registrations){
const worker=registration.active??registration.waiting??registration.installing;
if(registration.scope!==new URL('/',origin).href||worker?.scriptURL!==workerUrl)continue;
removed=await registration.unregister()||removed;
}
// Unregistering takes effect on the next navigation. Reload only when our
// worker actually controlled this page, so clean dev browsers never loop.
if(removed&&serviceWorker.controller?.scriptURL===workerUrl)reload();
}