-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathoffline.web.ts
192 lines (147 loc) · 4.74 KB
/
offline.web.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/// <reference lib="webworker" />
namespace $ {
export class $mol_offline_web extends $mol_offline {
web_js() { return 'web.js' }
blacklist = new Set([
'//cse.google.com/adsense/search/async-ads.js'
])
in_worker() { return typeof window === 'undefined' }
is_supported() {
if( location.protocol !== 'https:' && location.hostname !== 'localhost' ) {
console.warn( 'HTTPS or localhost is required for service workers.' )
return false
}
if( ! navigator.serviceWorker ) {
console.warn( 'Service Worker is not supported.' )
return false
}
return true
}
protected _registration = null as null | Promise<ServiceWorkerRegistration>
registration() {
if (this._registration) return this._registration
if ( this.in_worker() ) return null
if ( ! this.is_supported() ) return null
window.addEventListener('message', this.window_message.bind(this))
navigator.serviceWorker.register(this.web_js())
return this._registration = navigator.serviceWorker.ready
}
window_message(e: MessageEvent) {
if (e.data === 'mol_build_obsolete') return this.send(e.data)
}
async send(data: unknown) {
try {
const reg = await this.registration()
reg?.active?.postMessage(data)
} catch (e) {
console.error(e)
}
}
override run() {
if (! this.registration()) {
this.worker()
return false
}
// const reg = await this.registration()
// reg?.addEventListener( 'updatefound', ()=> {
// const worker = reg.installing!
// worker.addEventListener( 'statechange', ()=> {
// if( worker.state !== 'activated' ) return
// window.location.reload()
// } )
// } )
return true
}
_worker = null as null | ServiceWorkerGlobalScope
worker() {
if (this._worker) return this._worker
const worker = this._worker = self as unknown as ServiceWorkerGlobalScope
// as unknown as NonNullable<typeof this['_worker']>
worker.addEventListener( 'beforeinstallprompt' , this.beforeinstallprompt.bind(this) )
worker.addEventListener( 'install' , this.install.bind(this))
worker.addEventListener( 'activate' , this.activate.bind(this))
worker.addEventListener( 'message', this.message.bind(this))
worker.addEventListener( 'fetch', this.fetch_event.bind(this))
return worker
}
message(event: ExtendableMessageEvent) {
if (event.data === 'mol_build_obsolete') this.ignore_cache = true
}
beforeinstallprompt(event: Event & { prompt?(): void }) {
event.prompt?.()
}
install(event: ExtendableEvent) { this.worker().skipWaiting() }
activate(event: ExtendableEvent) {
// caches.delete( '$mol_offline' )
this.worker().clients.claim()
$$.$mol_log3_done({
place: '$mol_offline',
message: 'Activated',
})
}
protected ignore_cache = false
fetch_event(event: FetchEvent) {
const request = event.request
if( this.blacklist.has( request.url.replace( /^https?:/, '' ) ) ) {
return event.respondWith(
new Response(
null,
{
status: 418,
statusText: 'Blocked'
},
)
)
}
if( request.method !== 'GET' ) return
if( !/^https?:/.test( request.url ) ) return
if( /\?/.test( request.url ) ) return
if( request.cache === 'no-store' ) return
const response = this.respond(event)
event.waitUntil( response )
event.respondWith( response )
}
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
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
throw new Error(
`${actual.status}${actual.statusText ? ` ${actual.statusText}` : ''}`,
{ cause: actual }
)
} catch (err) {
const message = `${(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 )
return cloned
}
}
return cached
}
async put_cache(request: Request, response: Response) {
const cache = await caches.open( '$mol_offline' )
return cache.put( request , response )
}
async fetch_and_cache(event: FetchEvent) {
const request = event.request
const response = await fetch( request )
if (response.status === 200) {
event.waitUntil(this.put_cache(request, response.clone()))
}
return response
}
}
$.$mol_offline = $mol_offline_web
}