diff --git a/offline/offline.web.ts b/offline/offline.web.ts index a81941dd5b..ef0383b8ce 100644 --- a/offline/offline.web.ts +++ b/offline/offline.web.ts @@ -75,7 +75,7 @@ namespace $ { if (this._worker) return this._worker const worker = this._worker = self as unknown as ServiceWorkerGlobalScope // as unknown as NonNullable - worker.addEventListener( 'beforeinstallprompt' , this.beforeinstallprompt.bind(this) ) + worker.addEventListener( 'beforeinstallprompt' , this.before_install.bind(this) ) worker.addEventListener( 'install' , this.install.bind(this)) worker.addEventListener( 'activate' , this.activate.bind(this)) worker.addEventListener( 'message', this.message.bind(this)) @@ -88,7 +88,7 @@ namespace $ { if (event.data === 'mol_build_obsolete') this.ignore_cache = true } - beforeinstallprompt(event: Event & { prompt?(): void }) { + before_install(event: Event & { prompt?(): void }) { event.prompt?.() } @@ -134,22 +134,12 @@ namespace $ { async respond(event: FetchEvent) { const request = event.request - let cached - try { - cached = await caches.match( request ) - } catch (e) { - console.error(e) - } - - if ( ! cached) return this.fetch_and_cache(event) - - if (request.cache === 'force-cache') return cached - + let fallback_header if (this.ignore_cache || request.cache === 'no-cache' || request.cache === 'reload') { // fetch with fallback to cache if statuses not match try { const actual = await this.fetch_and_cache(event) - if (actual.status === cached.status) return actual + if (actual.status < 400) return actual throw new Error( `${actual.status}${actual.statusText ? ` ${actual.statusText}` : ''}`, @@ -157,14 +147,22 @@ namespace $ { ) } catch (err) { - const message = `${(err as Error).cause instanceof Response ? '' : '500 '}${ + fallback_header = `${(err as Error).cause instanceof Response ? '' : '500 '}${ (err as Error).message} $mol_offline fallback to cache` + } + } - const cloned = cached.clone() - cloned.headers.set( '$mol_offline_remote_status', message ) + let cached + try { + cached = await caches.match( request ) + } catch (e) { + console.error(e) + } - return cloned - } + if ( ! cached) return this.fetch_and_cache(event) + if (fallback_header) { + cached = cached.clone() + cached.headers.set( '$mol_offline_remote_status', fallback_header ) } return cached