PrecacheStrategy.ts
10.4 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
Copyright 2020 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {copyResponse} from 'workbox-core/copyResponse.js';
import {cacheNames} from 'workbox-core/_private/cacheNames.js';
import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {logger} from 'workbox-core/_private/logger.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import {WorkboxPlugin} from 'workbox-core/types.js';
import {Strategy, StrategyOptions} from 'workbox-strategies/Strategy.js';
import {StrategyHandler} from 'workbox-strategies/StrategyHandler.js';
import './_version.js';
interface PrecacheStrategyOptions extends StrategyOptions {
fallbackToNetwork?: boolean;
}
/**
* A {@link workbox-strategies.Strategy} implementation
* specifically designed to work with
* {@link workbox-precaching.PrecacheController}
* to both cache and fetch precached assets.
*
* Note: an instance of this class is created automatically when creating a
* `PrecacheController`; it's generally not necessary to create this yourself.
*
* @extends workbox-strategies.Strategy
* @memberof workbox-precaching
*/
class PrecacheStrategy extends Strategy {
private readonly _fallbackToNetwork: boolean;
static readonly defaultPrecacheCacheabilityPlugin: WorkboxPlugin = {
async cacheWillUpdate({response}) {
if (!response || response.status >= 400) {
return null;
}
return response;
},
};
static readonly copyRedirectedCacheableResponsesPlugin: WorkboxPlugin = {
async cacheWillUpdate({response}) {
return response.redirected ? await copyResponse(response) : response;
},
};
/**
*
* @param {Object} [options]
* @param {string} [options.cacheName] Cache name to store and retrieve
* requests. Defaults to the cache names provided by
* {@link workbox-core.cacheNames}.
* @param {Array<Object>} [options.plugins] {@link https://developers.google.com/web/tools/workbox/guides/using-plugins|Plugins}
* to use in conjunction with this caching strategy.
* @param {Object} [options.fetchOptions] Values passed along to the
* {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters|init}
* of all fetch() requests made by this strategy.
* @param {Object} [options.matchOptions] The
* {@link https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions|CacheQueryOptions}
* for any `cache.match()` or `cache.put()` calls made by this strategy.
* @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
* get the response from the network if there's a precache miss.
*/
constructor(options: PrecacheStrategyOptions = {}) {
options.cacheName = cacheNames.getPrecacheName(options.cacheName);
super(options);
this._fallbackToNetwork =
options.fallbackToNetwork === false ? false : true;
// Redirected responses cannot be used to satisfy a navigation request, so
// any redirected response must be "copied" rather than cloned, so the new
// response doesn't contain the `redirected` flag. See:
// https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
}
/**
* @private
* @param {Request|string} request A request to run this strategy for.
* @param {workbox-strategies.StrategyHandler} handler The event that
* triggered the request.
* @return {Promise<Response>}
*/
async _handle(request: Request, handler: StrategyHandler): Promise<Response> {
const response = await handler.cacheMatch(request);
if (response) {
return response;
}
// If this is an `install` event for an entry that isn't already cached,
// then populate the cache.
if (handler.event && handler.event.type === 'install') {
return await this._handleInstall(request, handler);
}
// Getting here means something went wrong. An entry that should have been
// precached wasn't found in the cache.
return await this._handleFetch(request, handler);
}
async _handleFetch(
request: Request,
handler: StrategyHandler,
): Promise<Response> {
let response;
const params = (handler.params || {}) as {
cacheKey?: string;
integrity?: string;
};
// Fall back to the network if we're configured to do so.
if (this._fallbackToNetwork) {
if (process.env.NODE_ENV !== 'production') {
logger.warn(
`The precached response for ` +
`${getFriendlyURL(request.url)} in ${this.cacheName} was not ` +
`found. Falling back to the network.`,
);
}
const integrityInManifest = params.integrity;
const integrityInRequest = request.integrity;
const noIntegrityConflict =
!integrityInRequest || integrityInRequest === integrityInManifest;
// Do not add integrity if the original request is no-cors
// See https://github.com/GoogleChrome/workbox/issues/3096
response = await handler.fetch(
new Request(request, {
integrity:
request.mode !== 'no-cors'
? integrityInRequest || integrityInManifest
: undefined,
}),
);
// It's only "safe" to repair the cache if we're using SRI to guarantee
// that the response matches the precache manifest's expectations,
// and there's either a) no integrity property in the incoming request
// or b) there is an integrity, and it matches the precache manifest.
// See https://github.com/GoogleChrome/workbox/issues/2858
// Also if the original request users no-cors we don't use integrity.
// See https://github.com/GoogleChrome/workbox/issues/3096
if (
integrityInManifest &&
noIntegrityConflict &&
request.mode !== 'no-cors'
) {
this._useDefaultCacheabilityPluginIfNeeded();
const wasCached = await handler.cachePut(request, response.clone());
if (process.env.NODE_ENV !== 'production') {
if (wasCached) {
logger.log(
`A response for ${getFriendlyURL(request.url)} ` +
`was used to "repair" the precache.`,
);
}
}
}
} else {
// This shouldn't normally happen, but there are edge cases:
// https://github.com/GoogleChrome/workbox/issues/1441
throw new WorkboxError('missing-precache-entry', {
cacheName: this.cacheName,
url: request.url,
});
}
if (process.env.NODE_ENV !== 'production') {
const cacheKey =
params.cacheKey || (await handler.getCacheKey(request, 'read'));
// Workbox is going to handle the route.
// print the routing details to the console.
logger.groupCollapsed(
`Precaching is responding to: ` + getFriendlyURL(request.url),
);
logger.log(
`Serving the precached url: ${getFriendlyURL(
cacheKey instanceof Request ? cacheKey.url : cacheKey,
)}`,
);
logger.groupCollapsed(`View request details here.`);
logger.log(request);
logger.groupEnd();
logger.groupCollapsed(`View response details here.`);
logger.log(response);
logger.groupEnd();
logger.groupEnd();
}
return response;
}
async _handleInstall(
request: Request,
handler: StrategyHandler,
): Promise<Response> {
this._useDefaultCacheabilityPluginIfNeeded();
const response = await handler.fetch(request);
// Make sure we defer cachePut() until after we know the response
// should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
const wasCached = await handler.cachePut(request, response.clone());
if (!wasCached) {
// Throwing here will lead to the `install` handler failing, which
// we want to do if *any* of the responses aren't safe to cache.
throw new WorkboxError('bad-precaching-response', {
url: request.url,
status: response.status,
});
}
return response;
}
/**
* This method is complex, as there a number of things to account for:
*
* The `plugins` array can be set at construction, and/or it might be added to
* to at any time before the strategy is used.
*
* At the time the strategy is used (i.e. during an `install` event), there
* needs to be at least one plugin that implements `cacheWillUpdate` in the
* array, other than `copyRedirectedCacheableResponsesPlugin`.
*
* - If this method is called and there are no suitable `cacheWillUpdate`
* plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
*
* - If this method is called and there is exactly one `cacheWillUpdate`, then
* we don't have to do anything (this might be a previously added
* `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
*
* - If this method is called and there is more than one `cacheWillUpdate`,
* then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
* we need to remove it. (This situation is unlikely, but it could happen if
* the strategy is used multiple times, the first without a `cacheWillUpdate`,
* and then later on after manually adding a custom `cacheWillUpdate`.)
*
* See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
*
* @private
*/
_useDefaultCacheabilityPluginIfNeeded(): void {
let defaultPluginIndex: number | null = null;
let cacheWillUpdatePluginCount = 0;
for (const [index, plugin] of this.plugins.entries()) {
// Ignore the copy redirected plugin when determining what to do.
if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
continue;
}
// Save the default plugin's index, in case it needs to be removed.
if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
defaultPluginIndex = index;
}
if (plugin.cacheWillUpdate) {
cacheWillUpdatePluginCount++;
}
}
if (cacheWillUpdatePluginCount === 0) {
this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
} else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
// Only remove the default plugin; multiple custom plugins are allowed.
this.plugins.splice(defaultPluginIndex, 1);
}
// Nothing needs to be done if cacheWillUpdatePluginCount is 1
}
}
export {PrecacheStrategy};