-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
143 lines (129 loc) · 3.8 KB
/
sw.js
File metadata and controls
143 lines (129 loc) · 3.8 KB
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
/* eslint-disable no-console, no-restricted-globals, no-restricted-syntax */ /* eslint-env serviceworker */ /* global workbox */
importScripts(`${self.__workbox_prefix__}/workbox-sw.js`)
workbox.setConfig({
modulePathPrefix: self.__workbox_prefix__,
})
workbox.precaching.precacheAndRoute([])
workbox.skipWaiting()
// helpers start
// wrapHandler :: (Handler a) => a -> Function | any
const wrapHandler = handler => {
if (typeof handler === 'function') return handler
if (
handler &&
typeof handler === 'object' &&
typeof handler.handle === 'function'
) {
return input => handler.handle(input)
}
return handler
}
// createHandler :: (Handler a) => (..., a) -> a
const createHandlerFactory = createHandler =>
function handler(...args) {
args[args.length - 1] = wrapHandler(args[args.length - 1]) // eslint-disable-line
return createHandler.call(this, ...args)
}
// getMsg :: (Any info) => info -> String
// throwTest :: (Any x) => x -> Boolean
const check = (getMsg, throwTest) => info => x => {
const errMsg = getMsg(info)
if (throwTest(x)) {
console.error(errMsg)
throw Error(errMsg)
}
return x
}
const checkResponse = check(
({ tag, url }) => `[SW]${tag ? ' ' : ''}${tag || ''}: fail to fetch ${url}`,
response => response === undefined || (!response.ok && response.status === 0)
)
// withFallback :: (Handler a) => (String, a) -> a
const withFallback = createHandlerFactory((url, handler) => input =>
handler(input)
.then(checkResponse({ url: input.event.request.url }))
.catch(() => caches.match(url))
.then(checkResponse({ url, tag: 'fallback' }))
)
const removeCaches = filter =>
caches.keys().then(keys =>
Promise.all(
keys.map(key => {
if (filter(key)) return null
return caches.delete(key)
})
)
)
const runTimeCacheNames = self.__runTimeCacheNames__
const expecteds = [].concat(
Object.values(runTimeCacheNames),
Object.values(workbox.core.cacheNames)
)
// remove old store
self.addEventListener('activate', event => {
event.waitUntil(removeCaches(key => expecteds.includes(key)))
})
const responsesAreSame = (a, b, names) =>
names.every(x => a.headers.get(x) === b.headers.get(x))
const checkPageUpdatePlugin = ({ headersToCheck }) => ({
cacheDidUpdate: ({ cacheName, oldResponse, newResponse, request }) => {
if (
!oldResponse ||
responsesAreSame(oldResponse, newResponse, headersToCheck)
) {
return null
}
return self.clients
.matchAll({
type: 'window',
})
.then(clientList => {
const updatedUrl = request.url
clientList.forEach(client => {
setTimeout(() => {
client.postMessage({
type: 'update',
payload: { cacheName, updatedUrl },
})
}, 500)
})
})
},
})
// helpers end
const pageBaseHandler = workbox.strategies.staleWhileRevalidate({
cacheName: runTimeCacheNames.sitePages,
plugins: [
checkPageUpdatePlugin({
headersToCheck: ['content-length', 'etag', 'last-modified'],
}),
new workbox.expiration.Plugin({
maxEntries: 40,
maxAgeSeconds: 7 * 24 * 60 * 60,
}),
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
],
})
const rootRegex = /^\/[^/]*$/
workbox.routing.registerRoute(
({ event, url }) =>
event.request.mode === 'navigate' && !rootRegex.test(url.pathname),
withFallback(`${self.location.origin}/offline.html`, pageBaseHandler)
)
workbox.routing.registerRoute(
/.*\.(png|jpg|jpeg|gif)/,
workbox.strategies.cacheFirst({
cacheName: runTimeCacheNames.images,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 20,
maxAgeSeconds: 7 * 24 * 60 * 60,
}),
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
],
})
)