@serwist/precaching 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/PrecacheController.d.ts +138 -0
  4. package/dist/PrecacheController.d.ts.map +1 -0
  5. package/dist/PrecacheFallbackPlugin.d.ts +44 -0
  6. package/dist/PrecacheFallbackPlugin.d.ts.map +1 -0
  7. package/dist/PrecacheRoute.d.ts +20 -0
  8. package/dist/PrecacheRoute.d.ts.map +1 -0
  9. package/dist/PrecacheStrategy.d.ts +67 -0
  10. package/dist/PrecacheStrategy.d.ts.map +1 -0
  11. package/dist/_types.d.ts +37 -0
  12. package/dist/_types.d.ts.map +1 -0
  13. package/dist/addPlugins.d.ts +9 -0
  14. package/dist/addPlugins.d.ts.map +1 -0
  15. package/dist/addRoute.d.ts +16 -0
  16. package/dist/addRoute.d.ts.map +1 -0
  17. package/dist/cleanupOutdatedCaches.d.ts +7 -0
  18. package/dist/cleanupOutdatedCaches.d.ts.map +1 -0
  19. package/dist/createHandlerBoundToURL.d.ts +18 -0
  20. package/dist/createHandlerBoundToURL.d.ts.map +1 -0
  21. package/dist/getCacheKeyForURL.d.ts +20 -0
  22. package/dist/getCacheKeyForURL.d.ts.map +1 -0
  23. package/dist/index.d.ts +25 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +917 -0
  26. package/dist/index.old.cjs +930 -0
  27. package/dist/matchPrecache.d.ts +15 -0
  28. package/dist/matchPrecache.d.ts.map +1 -0
  29. package/dist/precache.d.ts +20 -0
  30. package/dist/precache.d.ts.map +1 -0
  31. package/dist/precacheAndRoute.d.ts +15 -0
  32. package/dist/precacheAndRoute.d.ts.map +1 -0
  33. package/dist/utils/PrecacheCacheKeyPlugin.d.ts +17 -0
  34. package/dist/utils/PrecacheCacheKeyPlugin.d.ts.map +1 -0
  35. package/dist/utils/PrecacheInstallReportPlugin.d.ts +15 -0
  36. package/dist/utils/PrecacheInstallReportPlugin.d.ts.map +1 -0
  37. package/dist/utils/createCacheKey.d.ts +16 -0
  38. package/dist/utils/createCacheKey.d.ts.map +1 -0
  39. package/dist/utils/deleteOutdatedCaches.d.ts +19 -0
  40. package/dist/utils/deleteOutdatedCaches.d.ts.map +1 -0
  41. package/dist/utils/generateURLVariations.d.ts +12 -0
  42. package/dist/utils/generateURLVariations.d.ts.map +1 -0
  43. package/dist/utils/getCacheKeyForURL.d.ts +14 -0
  44. package/dist/utils/getCacheKeyForURL.d.ts.map +1 -0
  45. package/dist/utils/getOrCreatePrecacheController.d.ts +7 -0
  46. package/dist/utils/getOrCreatePrecacheController.d.ts.map +1 -0
  47. package/dist/utils/printCleanupDetails.d.ts +6 -0
  48. package/dist/utils/printCleanupDetails.d.ts.map +1 -0
  49. package/dist/utils/printInstallDetails.d.ts +7 -0
  50. package/dist/utils/printInstallDetails.d.ts.map +1 -0
  51. package/dist/utils/removeIgnoredSearchParams.d.ts +12 -0
  52. package/dist/utils/removeIgnoredSearchParams.d.ts.map +1 -0
  53. package/package.json +46 -0
package/dist/index.js ADDED
@@ -0,0 +1,917 @@
1
+ import { privateCacheNames, logger, getFriendlyURL, SerwistError, assert, waitUntil } from '@serwist/core/internal';
2
+ import { copyResponse } from '@serwist/core';
3
+ import { Strategy } from '@serwist/strategies';
4
+ import { Route, registerRoute } from '@serwist/routing';
5
+
6
+ /**
7
+ * A `@serwist/strategies.Strategy` implementation
8
+ * specifically designed to work with
9
+ * `@serwist/precaching.PrecacheController`
10
+ * to both cache and fetch precached assets.
11
+ *
12
+ * Note: an instance of this class is created automatically when creating a
13
+ * `PrecacheController`; it's generally not necessary to create this yourself.
14
+ */ class PrecacheStrategy extends Strategy {
15
+ _fallbackToNetwork;
16
+ static defaultPrecacheCacheabilityPlugin = {
17
+ async cacheWillUpdate ({ response }) {
18
+ if (!response || response.status >= 400) {
19
+ return null;
20
+ }
21
+ return response;
22
+ }
23
+ };
24
+ static copyRedirectedCacheableResponsesPlugin = {
25
+ async cacheWillUpdate ({ response }) {
26
+ return response.redirected ? await copyResponse(response) : response;
27
+ }
28
+ };
29
+ /**
30
+ * @param options
31
+ */ constructor(options = {}){
32
+ options.cacheName = privateCacheNames.getPrecacheName(options.cacheName);
33
+ super(options);
34
+ this._fallbackToNetwork = options.fallbackToNetwork === false ? false : true;
35
+ // Redirected responses cannot be used to satisfy a navigation request, so
36
+ // any redirected response must be "copied" rather than cloned, so the new
37
+ // response doesn't contain the `redirected` flag. See:
38
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
39
+ this.plugins.push(PrecacheStrategy.copyRedirectedCacheableResponsesPlugin);
40
+ }
41
+ /**
42
+ * @private
43
+ * @param request A request to run this strategy for.
44
+ * @param handler The event that triggered the request.
45
+ * @returns
46
+ */ async _handle(request, handler) {
47
+ const response = await handler.cacheMatch(request);
48
+ if (response) {
49
+ return response;
50
+ }
51
+ // If this is an `install` event for an entry that isn't already cached,
52
+ // then populate the cache.
53
+ if (handler.event && handler.event.type === "install") {
54
+ return await this._handleInstall(request, handler);
55
+ }
56
+ // Getting here means something went wrong. An entry that should have been
57
+ // precached wasn't found in the cache.
58
+ return await this._handleFetch(request, handler);
59
+ }
60
+ async _handleFetch(request, handler) {
61
+ let response;
62
+ const params = handler.params || {};
63
+ // Fallback to the network if we're configured to do so.
64
+ if (this._fallbackToNetwork) {
65
+ if (process.env.NODE_ENV !== "production") {
66
+ logger.warn(`The precached response for ` + `${getFriendlyURL(request.url)} in ${this.cacheName} was not ` + `found. Falling back to the network.`);
67
+ }
68
+ const integrityInManifest = params.integrity;
69
+ const integrityInRequest = request.integrity;
70
+ const noIntegrityConflict = !integrityInRequest || integrityInRequest === integrityInManifest;
71
+ // Do not add integrity if the original request is no-cors
72
+ // See https://github.com/GoogleChrome/workbox/issues/3096
73
+ response = await handler.fetch(new Request(request, {
74
+ integrity: request.mode !== "no-cors" ? integrityInRequest || integrityInManifest : undefined
75
+ }));
76
+ // It's only "safe" to repair the cache if we're using SRI to guarantee
77
+ // that the response matches the precache manifest's expectations,
78
+ // and there's either a) no integrity property in the incoming request
79
+ // or b) there is an integrity, and it matches the precache manifest.
80
+ // See https://github.com/GoogleChrome/workbox/issues/2858
81
+ // Also if the original request users no-cors we don't use integrity.
82
+ // See https://github.com/GoogleChrome/workbox/issues/3096
83
+ if (integrityInManifest && noIntegrityConflict && request.mode !== "no-cors") {
84
+ this._useDefaultCacheabilityPluginIfNeeded();
85
+ const wasCached = await handler.cachePut(request, response.clone());
86
+ if (process.env.NODE_ENV !== "production") {
87
+ if (wasCached) {
88
+ logger.log(`A response for ${getFriendlyURL(request.url)} ` + `was used to "repair" the precache.`);
89
+ }
90
+ }
91
+ }
92
+ } else {
93
+ // This shouldn't normally happen, but there are edge cases:
94
+ // https://github.com/GoogleChrome/workbox/issues/1441
95
+ throw new SerwistError("missing-precache-entry", {
96
+ cacheName: this.cacheName,
97
+ url: request.url
98
+ });
99
+ }
100
+ if (process.env.NODE_ENV !== "production") {
101
+ const cacheKey = params.cacheKey || await handler.getCacheKey(request, "read");
102
+ // Serwist is going to handle the route.
103
+ // print the routing details to the console.
104
+ logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL(request.url));
105
+ logger.log(`Serving the precached url: ${getFriendlyURL(cacheKey instanceof Request ? cacheKey.url : cacheKey)}`);
106
+ logger.groupCollapsed(`View request details here.`);
107
+ logger.log(request);
108
+ logger.groupEnd();
109
+ logger.groupCollapsed(`View response details here.`);
110
+ logger.log(response);
111
+ logger.groupEnd();
112
+ logger.groupEnd();
113
+ }
114
+ return response;
115
+ }
116
+ async _handleInstall(request, handler) {
117
+ this._useDefaultCacheabilityPluginIfNeeded();
118
+ const response = await handler.fetch(request);
119
+ // Make sure we defer cachePut() until after we know the response
120
+ // should be cached; see https://github.com/GoogleChrome/workbox/issues/2737
121
+ const wasCached = await handler.cachePut(request, response.clone());
122
+ if (!wasCached) {
123
+ // Throwing here will lead to the `install` handler failing, which
124
+ // we want to do if *any* of the responses aren't safe to cache.
125
+ throw new SerwistError("bad-precaching-response", {
126
+ url: request.url,
127
+ status: response.status
128
+ });
129
+ }
130
+ return response;
131
+ }
132
+ /**
133
+ * This method is complex, as there a number of things to account for:
134
+ *
135
+ * The `plugins` array can be set at construction, and/or it might be added to
136
+ * to at any time before the strategy is used.
137
+ *
138
+ * At the time the strategy is used (i.e. during an `install` event), there
139
+ * needs to be at least one plugin that implements `cacheWillUpdate` in the
140
+ * array, other than `copyRedirectedCacheableResponsesPlugin`.
141
+ *
142
+ * - If this method is called and there are no suitable `cacheWillUpdate`
143
+ * plugins, we need to add `defaultPrecacheCacheabilityPlugin`.
144
+ *
145
+ * - If this method is called and there is exactly one `cacheWillUpdate`, then
146
+ * we don't have to do anything (this might be a previously added
147
+ * `defaultPrecacheCacheabilityPlugin`, or it might be a custom plugin).
148
+ *
149
+ * - If this method is called and there is more than one `cacheWillUpdate`,
150
+ * then we need to check if one is `defaultPrecacheCacheabilityPlugin`. If so,
151
+ * we need to remove it. (This situation is unlikely, but it could happen if
152
+ * the strategy is used multiple times, the first without a `cacheWillUpdate`,
153
+ * and then later on after manually adding a custom `cacheWillUpdate`.)
154
+ *
155
+ * See https://github.com/GoogleChrome/workbox/issues/2737 for more context.
156
+ *
157
+ * @private
158
+ */ _useDefaultCacheabilityPluginIfNeeded() {
159
+ let defaultPluginIndex = null;
160
+ let cacheWillUpdatePluginCount = 0;
161
+ for (const [index, plugin] of this.plugins.entries()){
162
+ // Ignore the copy redirected plugin when determining what to do.
163
+ if (plugin === PrecacheStrategy.copyRedirectedCacheableResponsesPlugin) {
164
+ continue;
165
+ }
166
+ // Save the default plugin's index, in case it needs to be removed.
167
+ if (plugin === PrecacheStrategy.defaultPrecacheCacheabilityPlugin) {
168
+ defaultPluginIndex = index;
169
+ }
170
+ if (plugin.cacheWillUpdate) {
171
+ cacheWillUpdatePluginCount++;
172
+ }
173
+ }
174
+ if (cacheWillUpdatePluginCount === 0) {
175
+ this.plugins.push(PrecacheStrategy.defaultPrecacheCacheabilityPlugin);
176
+ } else if (cacheWillUpdatePluginCount > 1 && defaultPluginIndex !== null) {
177
+ // Only remove the default plugin; multiple custom plugins are allowed.
178
+ this.plugins.splice(defaultPluginIndex, 1);
179
+ }
180
+ // Nothing needs to be done if cacheWillUpdatePluginCount is 1
181
+ }
182
+ }
183
+
184
+ // Name of the search parameter used to store revision info.
185
+ const REVISION_SEARCH_PARAM = "__WB_REVISION__";
186
+ /**
187
+ * Converts a manifest entry into a versioned URL suitable for precaching.
188
+ *
189
+ * @param entry
190
+ * @returns A URL with versioning info.
191
+ *
192
+ * @private
193
+ */ function createCacheKey(entry) {
194
+ if (!entry) {
195
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
196
+ entry
197
+ });
198
+ }
199
+ // If a precache manifest entry is a string, it's assumed to be a versioned
200
+ // URL, like '/app.abcd1234.js'. Return as-is.
201
+ if (typeof entry === "string") {
202
+ const urlObject = new URL(entry, location.href);
203
+ return {
204
+ cacheKey: urlObject.href,
205
+ url: urlObject.href
206
+ };
207
+ }
208
+ const { revision, url } = entry;
209
+ if (!url) {
210
+ throw new SerwistError("add-to-cache-list-unexpected-type", {
211
+ entry
212
+ });
213
+ }
214
+ // If there's just a URL and no revision, then it's also assumed to be a
215
+ // versioned URL.
216
+ if (!revision) {
217
+ const urlObject = new URL(url, location.href);
218
+ return {
219
+ cacheKey: urlObject.href,
220
+ url: urlObject.href
221
+ };
222
+ }
223
+ // Otherwise, construct a properly versioned URL using the custom Serwist
224
+ // search parameter along with the revision info.
225
+ const cacheKeyURL = new URL(url, location.href);
226
+ const originalURL = new URL(url, location.href);
227
+ cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
228
+ return {
229
+ cacheKey: cacheKeyURL.href,
230
+ url: originalURL.href
231
+ };
232
+ }
233
+
234
+ /*
235
+ Copyright 2020 Google LLC
236
+
237
+ Use of this source code is governed by an MIT-style
238
+ license that can be found in the LICENSE file or at
239
+ https://opensource.org/licenses/MIT.
240
+ */ /**
241
+ * A plugin, designed to be used with PrecacheController, to translate URLs into
242
+ * the corresponding cache key, based on the current revision info.
243
+ *
244
+ * @private
245
+ */ class PrecacheCacheKeyPlugin {
246
+ _precacheController;
247
+ constructor({ precacheController }){
248
+ this._precacheController = precacheController;
249
+ }
250
+ cacheKeyWillBeUsed = async ({ request, params })=>{
251
+ // Params is type any, can't change right now.
252
+ /* eslint-disable */ const cacheKey = params?.cacheKey || this._precacheController.getCacheKeyForURL(request.url);
253
+ /* eslint-enable */ return cacheKey ? new Request(cacheKey, {
254
+ headers: request.headers
255
+ }) : request;
256
+ };
257
+ }
258
+
259
+ /*
260
+ Copyright 2020 Google LLC
261
+
262
+ Use of this source code is governed by an MIT-style
263
+ license that can be found in the LICENSE file or at
264
+ https://opensource.org/licenses/MIT.
265
+ */ /**
266
+ * A plugin, designed to be used with PrecacheController, to determine the
267
+ * of assets that were updated (or not updated) during the install event.
268
+ *
269
+ * @private
270
+ */ class PrecacheInstallReportPlugin {
271
+ updatedURLs = [];
272
+ notUpdatedURLs = [];
273
+ handlerWillStart = async ({ request, state })=>{
274
+ // TODO: `state` should never be undefined...
275
+ if (state) {
276
+ state.originalRequest = request;
277
+ }
278
+ };
279
+ cachedResponseWillBeUsed = async ({ event, state, cachedResponse })=>{
280
+ if (event.type === "install") {
281
+ if (state && state.originalRequest && state.originalRequest instanceof Request) {
282
+ // TODO: `state` should never be undefined...
283
+ const url = state.originalRequest.url;
284
+ if (cachedResponse) {
285
+ this.notUpdatedURLs.push(url);
286
+ } else {
287
+ this.updatedURLs.push(url);
288
+ }
289
+ }
290
+ }
291
+ return cachedResponse;
292
+ };
293
+ }
294
+
295
+ /**
296
+ * @param groupTitle
297
+ * @param deletedURLs
298
+ *
299
+ * @private
300
+ */ const logGroup = (groupTitle, deletedURLs)=>{
301
+ logger.groupCollapsed(groupTitle);
302
+ for (const url of deletedURLs){
303
+ logger.log(url);
304
+ }
305
+ logger.groupEnd();
306
+ };
307
+ /**
308
+ * @param deletedURLs
309
+ * @private
310
+ */ function printCleanupDetails(deletedURLs) {
311
+ const deletionCount = deletedURLs.length;
312
+ if (deletionCount > 0) {
313
+ logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? " was" : "s were"} deleted.`);
314
+ logGroup("Deleted Cache Requests", deletedURLs);
315
+ logger.groupEnd();
316
+ }
317
+ }
318
+
319
+ /**
320
+ * @param groupTitle
321
+ * @param urls
322
+ *
323
+ * @private
324
+ */ function _nestedGroup(groupTitle, urls) {
325
+ if (urls.length === 0) {
326
+ return;
327
+ }
328
+ logger.groupCollapsed(groupTitle);
329
+ for (const url of urls){
330
+ logger.log(url);
331
+ }
332
+ logger.groupEnd();
333
+ }
334
+ /**
335
+ * @param urlsToPrecache
336
+ * @param urlsAlreadyPrecached
337
+ * @private
338
+ */ function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
339
+ const precachedCount = urlsToPrecache.length;
340
+ const alreadyPrecachedCount = urlsAlreadyPrecached.length;
341
+ if (precachedCount || alreadyPrecachedCount) {
342
+ let message = `Precaching ${precachedCount} file${precachedCount === 1 ? "" : "s"}.`;
343
+ if (alreadyPrecachedCount > 0) {
344
+ message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? " is" : "s are"} already cached.`;
345
+ }
346
+ logger.groupCollapsed(message);
347
+ _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
348
+ _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
349
+ logger.groupEnd();
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Performs efficient precaching of assets.
355
+ */ class PrecacheController {
356
+ _installAndActiveListenersAdded;
357
+ _strategy;
358
+ _urlsToCacheKeys = new Map();
359
+ _urlsToCacheModes = new Map();
360
+ _cacheKeysToIntegrities = new Map();
361
+ /**
362
+ * Create a new PrecacheController.
363
+ *
364
+ * @param options
365
+ */ constructor({ cacheName, plugins = [], fallbackToNetwork = true } = {}){
366
+ this._strategy = new PrecacheStrategy({
367
+ cacheName: privateCacheNames.getPrecacheName(cacheName),
368
+ plugins: [
369
+ ...plugins,
370
+ new PrecacheCacheKeyPlugin({
371
+ precacheController: this
372
+ })
373
+ ],
374
+ fallbackToNetwork
375
+ });
376
+ // Bind the install and activate methods to the instance.
377
+ this.install = this.install.bind(this);
378
+ this.activate = this.activate.bind(this);
379
+ }
380
+ /**
381
+ * The strategy created by this controller and
382
+ * used to cache assets and respond to fetch events.
383
+ */ get strategy() {
384
+ return this._strategy;
385
+ }
386
+ /**
387
+ * Adds items to the precache list, removing any duplicates and
388
+ * stores the files in the precache cache when the service
389
+ * worker installs.
390
+ *
391
+ * This method can be called multiple times.
392
+ *
393
+ * @param entries Array of entries to precache.
394
+ */ precache(entries) {
395
+ this.addToCacheList(entries);
396
+ if (!this._installAndActiveListenersAdded) {
397
+ self.addEventListener("install", this.install);
398
+ self.addEventListener("activate", this.activate);
399
+ this._installAndActiveListenersAdded = true;
400
+ }
401
+ }
402
+ /**
403
+ * This method will add items to the precache list, removing duplicates
404
+ * and ensuring the information is valid.
405
+ *
406
+ * @param entries Array of entries to precache.
407
+ */ addToCacheList(entries) {
408
+ if (process.env.NODE_ENV !== "production") {
409
+ assert.isArray(entries, {
410
+ moduleName: "@serwist/precaching",
411
+ className: "PrecacheController",
412
+ funcName: "addToCacheList",
413
+ paramName: "entries"
414
+ });
415
+ }
416
+ const urlsToWarnAbout = [];
417
+ for (const entry of entries){
418
+ // See https://github.com/GoogleChrome/workbox/issues/2259
419
+ if (typeof entry === "string") {
420
+ urlsToWarnAbout.push(entry);
421
+ } else if (entry && entry.revision === undefined) {
422
+ urlsToWarnAbout.push(entry.url);
423
+ }
424
+ const { cacheKey, url } = createCacheKey(entry);
425
+ const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
426
+ if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
427
+ throw new SerwistError("add-to-cache-list-conflicting-entries", {
428
+ firstEntry: this._urlsToCacheKeys.get(url),
429
+ secondEntry: cacheKey
430
+ });
431
+ }
432
+ if (typeof entry !== "string" && entry.integrity) {
433
+ if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
434
+ throw new SerwistError("add-to-cache-list-conflicting-integrities", {
435
+ url
436
+ });
437
+ }
438
+ this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
439
+ }
440
+ this._urlsToCacheKeys.set(url, cacheKey);
441
+ this._urlsToCacheModes.set(url, cacheMode);
442
+ if (urlsToWarnAbout.length > 0) {
443
+ const warningMessage = `Serwist is precaching URLs without revision ` + `info: ${urlsToWarnAbout.join(", ")}\nThis is generally NOT safe. ` + `Learn more at https://bit.ly/wb-precache`;
444
+ if (process.env.NODE_ENV === "production") {
445
+ // Use console directly to display this warning without bloating
446
+ // bundle sizes by pulling in all of the logger codebase in prod.
447
+ console.warn(warningMessage);
448
+ } else {
449
+ logger.warn(warningMessage);
450
+ }
451
+ }
452
+ }
453
+ }
454
+ /**
455
+ * Precaches new and updated assets. Call this method from the service worker
456
+ * install event.
457
+ *
458
+ * Note: this method calls `event.waitUntil()` for you, so you do not need
459
+ * to call it yourself in your event handlers.
460
+ *
461
+ * @param event
462
+ * @returns
463
+ */ install(event) {
464
+ // waitUntil returns Promise<any>
465
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
466
+ return waitUntil(event, async ()=>{
467
+ const installReportPlugin = new PrecacheInstallReportPlugin();
468
+ this.strategy.plugins.push(installReportPlugin);
469
+ // Cache entries one at a time.
470
+ // See https://github.com/GoogleChrome/workbox/issues/2528
471
+ for (const [url, cacheKey] of this._urlsToCacheKeys){
472
+ const integrity = this._cacheKeysToIntegrities.get(cacheKey);
473
+ const cacheMode = this._urlsToCacheModes.get(url);
474
+ const request = new Request(url, {
475
+ integrity,
476
+ cache: cacheMode,
477
+ credentials: "same-origin"
478
+ });
479
+ await Promise.all(this.strategy.handleAll({
480
+ params: {
481
+ cacheKey
482
+ },
483
+ request,
484
+ event
485
+ }));
486
+ }
487
+ const { updatedURLs, notUpdatedURLs } = installReportPlugin;
488
+ if (process.env.NODE_ENV !== "production") {
489
+ printInstallDetails(updatedURLs, notUpdatedURLs);
490
+ }
491
+ return {
492
+ updatedURLs,
493
+ notUpdatedURLs
494
+ };
495
+ });
496
+ }
497
+ /**
498
+ * Deletes assets that are no longer present in the current precache manifest.
499
+ * Call this method from the service worker activate event.
500
+ *
501
+ * Note: this method calls `event.waitUntil()` for you, so you do not need
502
+ * to call it yourself in your event handlers.
503
+ *
504
+ * @param event
505
+ * @returns
506
+ */ activate(event) {
507
+ // waitUntil returns Promise<any>
508
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
509
+ return waitUntil(event, async ()=>{
510
+ const cache = await self.caches.open(this.strategy.cacheName);
511
+ const currentlyCachedRequests = await cache.keys();
512
+ const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
513
+ const deletedURLs = [];
514
+ for (const request of currentlyCachedRequests){
515
+ if (!expectedCacheKeys.has(request.url)) {
516
+ await cache.delete(request);
517
+ deletedURLs.push(request.url);
518
+ }
519
+ }
520
+ if (process.env.NODE_ENV !== "production") {
521
+ printCleanupDetails(deletedURLs);
522
+ }
523
+ return {
524
+ deletedURLs
525
+ };
526
+ });
527
+ }
528
+ /**
529
+ * Returns a mapping of a precached URL to the corresponding cache key, taking
530
+ * into account the revision information for the URL.
531
+ *
532
+ * @returns A URL to cache key mapping.
533
+ */ getURLsToCacheKeys() {
534
+ return this._urlsToCacheKeys;
535
+ }
536
+ /**
537
+ * Returns a list of all the URLs that have been precached by the current
538
+ * service worker.
539
+ *
540
+ * @returns The precached URLs.
541
+ */ getCachedURLs() {
542
+ return [
543
+ ...this._urlsToCacheKeys.keys()
544
+ ];
545
+ }
546
+ /**
547
+ * Returns the cache key used for storing a given URL. If that URL is
548
+ * unversioned, like `/index.html', then the cache key will be the original
549
+ * URL with a search parameter appended to it.
550
+ *
551
+ * @param url A URL whose cache key you want to look up.
552
+ * @returns The versioned URL that corresponds to a cache key
553
+ * for the original URL, or undefined if that URL isn't precached.
554
+ */ getCacheKeyForURL(url) {
555
+ const urlObject = new URL(url, location.href);
556
+ return this._urlsToCacheKeys.get(urlObject.href);
557
+ }
558
+ /**
559
+ * @param url A cache key whose SRI you want to look up.
560
+ * @returns The subresource integrity associated with the cache key,
561
+ * or undefined if it's not set.
562
+ */ getIntegrityForCacheKey(cacheKey) {
563
+ return this._cacheKeysToIntegrities.get(cacheKey);
564
+ }
565
+ /**
566
+ * This acts as a drop-in replacement for
567
+ * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
568
+ * with the following differences:
569
+ *
570
+ * - It knows what the name of the precache is, and only checks in that cache.
571
+ * - It allows you to pass in an "original" URL without versioning parameters,
572
+ * and it will automatically look up the correct cache key for the currently
573
+ * active revision of that URL.
574
+ *
575
+ * E.g., `matchPrecache('index.html')` will find the correct precached
576
+ * response for the currently active service worker, even if the actual cache
577
+ * key is `'/index.html?__WB_REVISION__=1234abcd'`.
578
+ *
579
+ * @param request The key (without revisioning parameters)
580
+ * to look up in the precache.
581
+ * @returns
582
+ */ async matchPrecache(request) {
583
+ const url = request instanceof Request ? request.url : request;
584
+ const cacheKey = this.getCacheKeyForURL(url);
585
+ if (cacheKey) {
586
+ const cache = await self.caches.open(this.strategy.cacheName);
587
+ return cache.match(cacheKey);
588
+ }
589
+ return undefined;
590
+ }
591
+ /**
592
+ * Returns a function that looks up `url` in the precache (taking into
593
+ * account revision information), and returns the corresponding `Response`.
594
+ *
595
+ * @param url The precached URL which will be used to lookup the response.
596
+ * @return
597
+ */ createHandlerBoundToURL(url) {
598
+ const cacheKey = this.getCacheKeyForURL(url);
599
+ if (!cacheKey) {
600
+ throw new SerwistError("non-precached-url", {
601
+ url
602
+ });
603
+ }
604
+ return (options)=>{
605
+ options.request = new Request(url);
606
+ options.params = {
607
+ cacheKey,
608
+ ...options.params
609
+ };
610
+ return this.strategy.handle(options);
611
+ };
612
+ }
613
+ }
614
+
615
+ let precacheController;
616
+ /**
617
+ * @returns
618
+ * @private
619
+ */ const getOrCreatePrecacheController = ()=>{
620
+ if (!precacheController) {
621
+ precacheController = new PrecacheController();
622
+ }
623
+ return precacheController;
624
+ };
625
+
626
+ /**
627
+ * Adds plugins to the precaching strategy.
628
+ *
629
+ * @param plugins
630
+ */ function addPlugins(plugins) {
631
+ const precacheController = getOrCreatePrecacheController();
632
+ precacheController.strategy.plugins.push(...plugins);
633
+ }
634
+
635
+ /*
636
+ Copyright 2018 Google LLC
637
+
638
+ Use of this source code is governed by an MIT-style
639
+ license that can be found in the LICENSE file or at
640
+ https://opensource.org/licenses/MIT.
641
+ */ /**
642
+ * Removes any URL search parameters that should be ignored.
643
+ *
644
+ * @param urlObject The original URL.
645
+ * @param ignoreURLParametersMatching RegExps to test against
646
+ * each search parameter name. Matches mean that the search parameter should be
647
+ * ignored.
648
+ * @returns The URL with any ignored search parameters removed.
649
+ * @private
650
+ */ function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching = []) {
651
+ // Convert the iterable into an array at the start of the loop to make sure
652
+ // deletion doesn't mess up iteration.
653
+ for (const paramName of [
654
+ ...urlObject.searchParams.keys()
655
+ ]){
656
+ if (ignoreURLParametersMatching.some((regExp)=>regExp.test(paramName))) {
657
+ urlObject.searchParams.delete(paramName);
658
+ }
659
+ }
660
+ return urlObject;
661
+ }
662
+
663
+ /**
664
+ * Generator function that yields possible variations on the original URL to
665
+ * check, one at a time.
666
+ *
667
+ * @param url
668
+ * @param options
669
+ *
670
+ * @private
671
+ */ function* generateURLVariations(url, { ignoreURLParametersMatching = [
672
+ /^utm_/,
673
+ /^fbclid$/
674
+ ], directoryIndex = "index.html", cleanURLs = true, urlManipulation } = {}) {
675
+ const urlObject = new URL(url, location.href);
676
+ urlObject.hash = "";
677
+ yield urlObject.href;
678
+ const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
679
+ yield urlWithoutIgnoredParams.href;
680
+ if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith("/")) {
681
+ const directoryURL = new URL(urlWithoutIgnoredParams.href);
682
+ directoryURL.pathname += directoryIndex;
683
+ yield directoryURL.href;
684
+ }
685
+ if (cleanURLs) {
686
+ const cleanURL = new URL(urlWithoutIgnoredParams.href);
687
+ cleanURL.pathname += ".html";
688
+ yield cleanURL.href;
689
+ }
690
+ if (urlManipulation) {
691
+ const additionalURLs = urlManipulation({
692
+ url: urlObject
693
+ });
694
+ for (const urlToAttempt of additionalURLs){
695
+ yield urlToAttempt.href;
696
+ }
697
+ }
698
+ }
699
+
700
+ /**
701
+ * A subclass of `@serwist/routing.Route` that takes a
702
+ * `@serwist/precaching.PrecacheController`
703
+ * instance and uses it to match incoming requests and handle fetching
704
+ * responses from the precache.
705
+ */ class PrecacheRoute extends Route {
706
+ /**
707
+ * @param precacheController A `PrecacheController`
708
+ * instance used to both match requests and respond to fetch events.
709
+ * @param options Options to control how requests are matched
710
+ * against the list of precached URLs.
711
+ */ constructor(precacheController, options){
712
+ const match = ({ request })=>{
713
+ const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
714
+ for (const possibleURL of generateURLVariations(request.url, options)){
715
+ const cacheKey = urlsToCacheKeys.get(possibleURL);
716
+ if (cacheKey) {
717
+ const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
718
+ return {
719
+ cacheKey,
720
+ integrity
721
+ };
722
+ }
723
+ }
724
+ if (process.env.NODE_ENV !== "production") {
725
+ logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
726
+ }
727
+ return;
728
+ };
729
+ super(match, precacheController.strategy);
730
+ }
731
+ }
732
+
733
+ /**
734
+ * Add a `fetch` listener to the service worker that will
735
+ * respond to
736
+ * [network requests](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests)
737
+ * with precached assets.
738
+ *
739
+ * Requests for assets that aren't precached, the `FetchEvent` will not be
740
+ * responded to, allowing the event to fall through to other `fetch` event
741
+ * listeners.
742
+ *
743
+ * @param options See the `@serwist/precaching.PrecacheRoute` options.
744
+ */ function addRoute(options) {
745
+ const precacheController = getOrCreatePrecacheController();
746
+ const precacheRoute = new PrecacheRoute(precacheController, options);
747
+ registerRoute(precacheRoute);
748
+ }
749
+
750
+ /*
751
+ Copyright 2018 Google LLC
752
+
753
+ Use of this source code is governed by an MIT-style
754
+ license that can be found in the LICENSE file or at
755
+ https://opensource.org/licenses/MIT.
756
+ */ // Give TypeScript the correct global.
757
+ const SUBSTRING_TO_FIND = "-precache-";
758
+ /**
759
+ * Cleans up incompatible precaches that were created by older versions of
760
+ * Serwist, by a service worker registered under the current scope.
761
+ *
762
+ * This is meant to be called as part of the `activate` event.
763
+ *
764
+ * This should be safe to use as long as you don't include `substringToFind`
765
+ * (defaulting to `-precache-`) in your non-precache cache names.
766
+ *
767
+ * @param currentPrecacheName The cache name currently in use for
768
+ * precaching. This cache won't be deleted.
769
+ * @param substringToFind Cache names which include this
770
+ * substring will be deleted (excluding `currentPrecacheName`).
771
+ * @returns A list of all the cache names that were deleted.
772
+ * @private
773
+ */ const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND)=>{
774
+ const cacheNames = await self.caches.keys();
775
+ const cacheNamesToDelete = cacheNames.filter((cacheName)=>{
776
+ return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
777
+ });
778
+ await Promise.all(cacheNamesToDelete.map((cacheName)=>self.caches.delete(cacheName)));
779
+ return cacheNamesToDelete;
780
+ };
781
+
782
+ /**
783
+ * Adds an `activate` event listener which will clean up incompatible
784
+ * precaches that were created by older versions of Serwist.
785
+ */ function cleanupOutdatedCaches() {
786
+ // See https://github.com/Microsoft/TypeScript/issues/28357#issuecomment-436484705
787
+ self.addEventListener("activate", (event)=>{
788
+ const cacheName = privateCacheNames.getPrecacheName();
789
+ event.waitUntil(deleteOutdatedCaches(cacheName).then((cachesDeleted)=>{
790
+ if (process.env.NODE_ENV !== "production") {
791
+ if (cachesDeleted.length > 0) {
792
+ logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
793
+ }
794
+ }
795
+ }));
796
+ });
797
+ }
798
+
799
+ /**
800
+ * Helper function that calls `PrecacheController#createHandlerBoundToURL`
801
+ * on the default `PrecacheController` instance.
802
+ *
803
+ * If you are creating your own `PrecacheController`, then call the
804
+ * `PrecacheController#createHandlerBoundToURL` on that instance,
805
+ * instead of using this function.
806
+ *
807
+ * @param url The precached URL which will be used to lookup the
808
+ * `Response`.
809
+ * @param fallbackToNetwork Whether to attempt to get the
810
+ * response from the network if there's a precache miss.
811
+ * @return
812
+ */ function createHandlerBoundToURL(url) {
813
+ const precacheController = getOrCreatePrecacheController();
814
+ return precacheController.createHandlerBoundToURL(url);
815
+ }
816
+
817
+ /**
818
+ * Takes in a URL, and returns the corresponding URL that could be used to
819
+ * lookup the entry in the precache.
820
+ *
821
+ * If a relative URL is provided, the location of the service worker file will
822
+ * be used as the base.
823
+ *
824
+ * For precached entries without revision information, the cache key will be the
825
+ * same as the original URL.
826
+ *
827
+ * For precached entries with revision information, the cache key will be the
828
+ * original URL with the addition of a query parameter used for keeping track of
829
+ * the revision info.
830
+ *
831
+ * @param url The URL whose cache key to look up.
832
+ * @returns The cache key that corresponds to that URL.
833
+ */ function getCacheKeyForURL(url) {
834
+ const precacheController = getOrCreatePrecacheController();
835
+ return precacheController.getCacheKeyForURL(url);
836
+ }
837
+
838
+ /**
839
+ * Helper function that calls `PrecacheController#matchPrecache`
840
+ * on the default `PrecacheController` instance.
841
+ *
842
+ * If you are creating your own `PrecacheController`, then call
843
+ * `PrecacheController#matchPrecache` on that instance,
844
+ * instead of using this function.
845
+ *
846
+ * @param request The key (without revisioning parameters)
847
+ * to look up in the precache.
848
+ * @returns
849
+ */ function matchPrecache(request) {
850
+ const precacheController = getOrCreatePrecacheController();
851
+ return precacheController.matchPrecache(request);
852
+ }
853
+
854
+ /**
855
+ * Adds items to the precache list, removing any duplicates and
856
+ * stores the files in the precache cache when the service
857
+ * worker installs.
858
+ *
859
+ * This method can be called multiple times.
860
+ *
861
+ * Please note: This method **will not** serve any of the cached files for you.
862
+ * It only precaches files. To respond to a network request you call
863
+ * `@serwist/precaching.addRoute`.
864
+ *
865
+ * If you have a single array of files to precache, you can just call
866
+ * `@serwist/precaching.precacheAndRoute`.
867
+ *
868
+ * @param entries Array of entries to precache.
869
+ */ function precache(entries) {
870
+ const precacheController = getOrCreatePrecacheController();
871
+ precacheController.precache(entries);
872
+ }
873
+
874
+ /**
875
+ * This method will add entries to the precache list and add a route to
876
+ * respond to fetch events.
877
+ *
878
+ * This is a convenience method that will call
879
+ * `@serwist/precaching.precache` and
880
+ * `@serwist/precaching.addRoute` in a single call.
881
+ *
882
+ * @param entries Array of entries to precache.
883
+ * @param options See the `@serwist/precaching.PrecacheRoute` options.
884
+ */ function precacheAndRoute(entries, options) {
885
+ precache(entries);
886
+ addRoute(options);
887
+ }
888
+
889
+ /**
890
+ * `PrecacheFallbackPlugin` allows you to specify an "offline fallback"
891
+ * response to be used when a given strategy is unable to generate a response.
892
+ *
893
+ * It does this by intercepting the `handlerDidError` plugin callback
894
+ * and returning a precached response, taking the expected revision parameter
895
+ * into account automatically.
896
+ *
897
+ * Unless you explicitly pass in a `PrecacheController` instance to the
898
+ * constructor, the default instance will be used. Generally speaking, most
899
+ * developers will end up using the default.
900
+ */ class PrecacheFallbackPlugin {
901
+ _fallbackURL;
902
+ _precacheController;
903
+ /**
904
+ * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.
905
+ *
906
+ * @param config
907
+ */ constructor({ fallbackURL, precacheController }){
908
+ this._fallbackURL = fallbackURL;
909
+ this._precacheController = precacheController || getOrCreatePrecacheController();
910
+ }
911
+ /**
912
+ * @returns The precache response for the fallback URL.
913
+ * @private
914
+ */ handlerDidError = ()=>this._precacheController.matchPrecache(this._fallbackURL);
915
+ }
916
+
917
+ export { PrecacheController, PrecacheFallbackPlugin, PrecacheRoute, PrecacheStrategy, addPlugins, addRoute, cleanupOutdatedCaches, createHandlerBoundToURL, getCacheKeyForURL, matchPrecache, precache, precacheAndRoute };