UNPKG

30.3 kBJavaScriptView Raw
1this.workbox = this.workbox || {};
2this.workbox.precaching = (function (exports, assert_mjs, cacheNames_mjs, getFriendlyURL_mjs, logger_mjs, cacheWrapper_mjs, fetchWrapper_mjs, WorkboxError_mjs) {
3 'use strict';
4
5 try {
6 self['workbox:precaching:4.3.0'] && _();
7 } catch (e) {} // eslint-disable-line
8
9 /*
10 Copyright 2019 Google LLC
11
12 Use of this source code is governed by an MIT-style
13 license that can be found in the LICENSE file or at
14 https://opensource.org/licenses/MIT.
15 */
16 const plugins = [];
17 const precachePlugins = {
18 /*
19 * @return {Array}
20 * @private
21 */
22 get() {
23 return plugins;
24 },
25
26 /*
27 * @param {Array} newPlugins
28 * @private
29 */
30 add(newPlugins) {
31 plugins.push(...newPlugins);
32 }
33
34 };
35
36 /*
37 Copyright 2019 Google LLC
38
39 Use of this source code is governed by an MIT-style
40 license that can be found in the LICENSE file or at
41 https://opensource.org/licenses/MIT.
42 */
43 /**
44 * Adds plugins to precaching.
45 *
46 * @param {Array<Object>} newPlugins
47 *
48 * @alias workbox.precaching.addPlugins
49 */
50
51 const addPlugins = newPlugins => {
52 precachePlugins.add(newPlugins);
53 };
54
55 /*
56 Copyright 2018 Google LLC
57
58 Use of this source code is governed by an MIT-style
59 license that can be found in the LICENSE file or at
60 https://opensource.org/licenses/MIT.
61 */
62 /**
63 * @param {Response} response
64 * @return {Response}
65 *
66 * @private
67 * @memberof module:workbox-precaching
68 */
69
70 async function cleanRedirect(response) {
71 const clonedResponse = response.clone(); // Not all browsers support the Response.body stream, so fall back
72 // to reading the entire body into memory as a blob.
73
74 const bodyPromise = 'body' in clonedResponse ? Promise.resolve(clonedResponse.body) : clonedResponse.blob();
75 const body = await bodyPromise; // new Response() is happy when passed either a stream or a Blob.
76
77 return new Response(body, {
78 headers: clonedResponse.headers,
79 status: clonedResponse.status,
80 statusText: clonedResponse.statusText
81 });
82 }
83
84 /*
85 Copyright 2018 Google LLC
86
87 Use of this source code is governed by an MIT-style
88 license that can be found in the LICENSE file or at
89 https://opensource.org/licenses/MIT.
90 */
91
92 const REVISION_SEARCH_PARAM = '__WB_REVISION__';
93 /**
94 * Converts a manifest entry into a versioned URL suitable for precaching.
95 *
96 * @param {Object} entry
97 * @return {string} A URL with versioning info.
98 *
99 * @private
100 * @memberof module:workbox-precaching
101 */
102
103 function createCacheKey(entry) {
104 if (!entry) {
105 throw new WorkboxError_mjs.WorkboxError('add-to-cache-list-unexpected-type', {
106 entry
107 });
108 } // If a precache manifest entry is a string, it's assumed to be a versioned
109 // URL, like '/app.abcd1234.js'. Return as-is.
110
111
112 if (typeof entry === 'string') {
113 const urlObject = new URL(entry, location);
114 return {
115 cacheKey: urlObject.href,
116 url: urlObject.href
117 };
118 }
119
120 const {
121 revision,
122 url
123 } = entry;
124
125 if (!url) {
126 throw new WorkboxError_mjs.WorkboxError('add-to-cache-list-unexpected-type', {
127 entry
128 });
129 } // If there's just a URL and no revision, then it's also assumed to be a
130 // versioned URL.
131
132
133 if (!revision) {
134 const urlObject = new URL(url, location);
135 return {
136 cacheKey: urlObject.href,
137 url: urlObject.href
138 };
139 } // Otherwise, construct a properly versioned URL using the custom Workbox
140 // search parameter along with the revision info.
141
142
143 const originalURL = new URL(url, location);
144 const cacheKeyURL = new URL(url, location);
145 cacheKeyURL.searchParams.set(REVISION_SEARCH_PARAM, revision);
146 return {
147 cacheKey: cacheKeyURL.href,
148 url: originalURL.href
149 };
150 }
151
152 /*
153 Copyright 2018 Google LLC
154
155 Use of this source code is governed by an MIT-style
156 license that can be found in the LICENSE file or at
157 https://opensource.org/licenses/MIT.
158 */
159
160 const logGroup = (groupTitle, deletedURLs) => {
161 logger_mjs.logger.groupCollapsed(groupTitle);
162
163 for (const url of deletedURLs) {
164 logger_mjs.logger.log(url);
165 }
166
167 logger_mjs.logger.groupEnd();
168 };
169 /**
170 * @param {Array<string>} deletedURLs
171 *
172 * @private
173 * @memberof module:workbox-precaching
174 */
175
176
177 function printCleanupDetails(deletedURLs) {
178 const deletionCount = deletedURLs.length;
179
180 if (deletionCount > 0) {
181 logger_mjs.logger.groupCollapsed(`During precaching cleanup, ` + `${deletionCount} cached ` + `request${deletionCount === 1 ? ' was' : 's were'} deleted.`);
182 logGroup('Deleted Cache Requests', deletedURLs);
183 logger_mjs.logger.groupEnd();
184 }
185 }
186
187 /*
188 Copyright 2018 Google LLC
189
190 Use of this source code is governed by an MIT-style
191 license that can be found in the LICENSE file or at
192 https://opensource.org/licenses/MIT.
193 */
194 /**
195 * @param {string} groupTitle
196 * @param {Array<string>} urls
197 *
198 * @private
199 */
200
201 function _nestedGroup(groupTitle, urls) {
202 if (urls.length === 0) {
203 return;
204 }
205
206 logger_mjs.logger.groupCollapsed(groupTitle);
207
208 for (const url of urls) {
209 logger_mjs.logger.log(url);
210 }
211
212 logger_mjs.logger.groupEnd();
213 }
214 /**
215 * @param {Array<string>} urlsToPrecache
216 * @param {Array<string>} urlsAlreadyPrecached
217 *
218 * @private
219 * @memberof module:workbox-precaching
220 */
221
222
223 function printInstallDetails(urlsToPrecache, urlsAlreadyPrecached) {
224 const precachedCount = urlsToPrecache.length;
225 const alreadyPrecachedCount = urlsAlreadyPrecached.length;
226
227 if (precachedCount || alreadyPrecachedCount) {
228 let message = `Precaching ${precachedCount} file${precachedCount === 1 ? '' : 's'}.`;
229
230 if (alreadyPrecachedCount > 0) {
231 message += ` ${alreadyPrecachedCount} ` + `file${alreadyPrecachedCount === 1 ? ' is' : 's are'} already cached.`;
232 }
233
234 logger_mjs.logger.groupCollapsed(message);
235
236 _nestedGroup(`View newly precached URLs.`, urlsToPrecache);
237
238 _nestedGroup(`View previously precached URLs.`, urlsAlreadyPrecached);
239
240 logger_mjs.logger.groupEnd();
241 }
242 }
243
244 /*
245 Copyright 2018 Google LLC
246
247 Use of this source code is governed by an MIT-style
248 license that can be found in the LICENSE file or at
249 https://opensource.org/licenses/MIT.
250 */
251 /**
252 * Performs efficient precaching of assets.
253 *
254 * @memberof module:workbox-precaching
255 */
256
257 class PrecacheController {
258 /**
259 * Create a new PrecacheController.
260 *
261 * @param {string} [cacheName] An optional name for the cache, to override
262 * the default precache name.
263 */
264 constructor(cacheName) {
265 this._cacheName = cacheNames_mjs.cacheNames.getPrecacheName(cacheName);
266 this._urlsToCacheKeys = new Map();
267 }
268 /**
269 * This method will add items to the precache list, removing duplicates
270 * and ensuring the information is valid.
271 *
272 * @param {
273 * Array<module:workbox-precaching.PrecacheController.PrecacheEntry|string>
274 * } entries Array of entries to precache.
275 */
276
277
278 addToCacheList(entries) {
279 {
280 assert_mjs.assert.isArray(entries, {
281 moduleName: 'workbox-precaching',
282 className: 'PrecacheController',
283 funcName: 'addToCacheList',
284 paramName: 'entries'
285 });
286 }
287
288 for (const entry of entries) {
289 const {
290 cacheKey,
291 url
292 } = createCacheKey(entry);
293
294 if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
295 throw new WorkboxError_mjs.WorkboxError('add-to-cache-list-conflicting-entries', {
296 firstEntry: this._urlsToCacheKeys.get(url),
297 secondEntry: cacheKey
298 });
299 }
300
301 this._urlsToCacheKeys.set(url, cacheKey);
302 }
303 }
304 /**
305 * Precaches new and updated assets. Call this method from the service worker
306 * install event.
307 *
308 * @param {Object} options
309 * @param {Event} [options.event] The install event (if needed).
310 * @param {Array<Object>} [options.plugins] Plugins to be used for fetching
311 * and caching during install.
312 * @return {Promise<workbox.precaching.InstallResult>}
313 */
314
315
316 async install({
317 event,
318 plugins
319 } = {}) {
320 {
321 if (plugins) {
322 assert_mjs.assert.isArray(plugins, {
323 moduleName: 'workbox-precaching',
324 className: 'PrecacheController',
325 funcName: 'install',
326 paramName: 'plugins'
327 });
328 }
329 }
330
331 const urlsToPrecache = [];
332 const urlsAlreadyPrecached = [];
333 const cache = await caches.open(this._cacheName);
334 const alreadyCachedRequests = await cache.keys();
335 const alreadyCachedURLs = new Set(alreadyCachedRequests.map(request => request.url));
336
337 for (const cacheKey of this._urlsToCacheKeys.values()) {
338 if (alreadyCachedURLs.has(cacheKey)) {
339 urlsAlreadyPrecached.push(cacheKey);
340 } else {
341 urlsToPrecache.push(cacheKey);
342 }
343 }
344
345 const precacheRequests = urlsToPrecache.map(url => {
346 return this._addURLToCache({
347 event,
348 plugins,
349 url
350 });
351 });
352 await Promise.all(precacheRequests);
353
354 {
355 printInstallDetails(urlsToPrecache, urlsAlreadyPrecached);
356 }
357
358 return {
359 updatedURLs: urlsToPrecache,
360 notUpdatedURLs: urlsAlreadyPrecached
361 };
362 }
363 /**
364 * Deletes assets that are no longer present in the current precache manifest.
365 * Call this method from the service worker activate event.
366 *
367 * @return {Promise<workbox.precaching.CleanupResult>}
368 */
369
370
371 async activate() {
372 const cache = await caches.open(this._cacheName);
373 const currentlyCachedRequests = await cache.keys();
374 const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
375 const deletedURLs = [];
376
377 for (const request of currentlyCachedRequests) {
378 if (!expectedCacheKeys.has(request.url)) {
379 await cache.delete(request);
380 deletedURLs.push(request.url);
381 }
382 }
383
384 {
385 printCleanupDetails(deletedURLs);
386 }
387
388 return {
389 deletedURLs
390 };
391 }
392 /**
393 * Requests the entry and saves it to the cache if the response is valid.
394 * By default, any response with a status code of less than 400 (including
395 * opaque responses) is considered valid.
396 *
397 * If you need to use custom criteria to determine what's valid and what
398 * isn't, then pass in an item in `options.plugins` that implements the
399 * `cacheWillUpdate()` lifecycle event.
400 *
401 * @private
402 * @param {Object} options
403 * @param {string} options.url The URL to fetch and cache.
404 * @param {Event} [options.event] The install event (if passed).
405 * @param {Array<Object>} [options.plugins] An array of plugins to apply to
406 * fetch and caching.
407 */
408
409
410 async _addURLToCache({
411 url,
412 event,
413 plugins
414 }) {
415 const request = new Request(url, {
416 credentials: 'same-origin'
417 });
418 let response = await fetchWrapper_mjs.fetchWrapper.fetch({
419 event,
420 plugins,
421 request
422 }); // Allow developers to override the default logic about what is and isn't
423 // valid by passing in a plugin implementing cacheWillUpdate(), e.g.
424 // a workbox.cacheableResponse.Plugin instance.
425
426 let cacheWillUpdateCallback;
427
428 for (const plugin of plugins || []) {
429 if ('cacheWillUpdate' in plugin) {
430 cacheWillUpdateCallback = plugin.cacheWillUpdate.bind(plugin);
431 }
432 }
433
434 const isValidResponse = cacheWillUpdateCallback ? // Use a callback if provided. It returns a truthy value if valid.
435 cacheWillUpdateCallback({
436 event,
437 request,
438 response
439 }) : // Otherwise, default to considering any response status under 400 valid.
440 // This includes, by default, considering opaque responses valid.
441 response.status < 400; // Consider this a failure, leading to the `install` handler failing, if
442 // we get back an invalid response.
443
444 if (!isValidResponse) {
445 throw new WorkboxError_mjs.WorkboxError('bad-precaching-response', {
446 url,
447 status: response.status
448 });
449 }
450
451 if (response.redirected) {
452 response = await cleanRedirect(response);
453 }
454
455 await cacheWrapper_mjs.cacheWrapper.put({
456 event,
457 plugins,
458 request,
459 response,
460 cacheName: this._cacheName,
461 matchOptions: {
462 ignoreSearch: true
463 }
464 });
465 }
466 /**
467 * Returns a mapping of a precached URL to the corresponding cache key, taking
468 * into account the revision information for the URL.
469 *
470 * @return {Map<string, string>} A URL to cache key mapping.
471 */
472
473
474 getURLsToCacheKeys() {
475 return this._urlsToCacheKeys;
476 }
477 /**
478 * Returns a list of all the URLs that have been precached by the current
479 * service worker.
480 *
481 * @return {Array<string>} The precached URLs.
482 */
483
484
485 getCachedURLs() {
486 return [...this._urlsToCacheKeys.keys()];
487 }
488 /**
489 * Returns the cache key used for storing a given URL. If that URL is
490 * unversioned, like `/index.html', then the cache key will be the original
491 * URL with a search parameter appended to it.
492 *
493 * @param {string} url A URL whose cache key you want to look up.
494 * @return {string} The versioned URL that corresponds to a cache key
495 * for the original URL, or undefined if that URL isn't precached.
496 */
497
498
499 getCacheKeyForURL(url) {
500 const urlObject = new URL(url, location);
501 return this._urlsToCacheKeys.get(urlObject.href);
502 }
503
504 }
505
506 /*
507 Copyright 2019 Google LLC
508
509 Use of this source code is governed by an MIT-style
510 license that can be found in the LICENSE file or at
511 https://opensource.org/licenses/MIT.
512 */
513 let precacheController;
514 /**
515 * @return {PrecacheController}
516 * @private
517 */
518
519 const getOrCreatePrecacheController = () => {
520 if (!precacheController) {
521 precacheController = new PrecacheController();
522 }
523
524 return precacheController;
525 };
526
527 /*
528 Copyright 2018 Google LLC
529
530 Use of this source code is governed by an MIT-style
531 license that can be found in the LICENSE file or at
532 https://opensource.org/licenses/MIT.
533 */
534 /**
535 * Removes any URL search parameters that should be ignored.
536 *
537 * @param {URL} urlObject The original URL.
538 * @param {Array<RegExp>} ignoreURLParametersMatching RegExps to test against
539 * each search parameter name. Matches mean that the search parameter should be
540 * ignored.
541 * @return {URL} The URL with any ignored search parameters removed.
542 *
543 * @private
544 * @memberof module:workbox-precaching
545 */
546
547 function removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching) {
548 // Convert the iterable into an array at the start of the loop to make sure
549 // deletion doesn't mess up iteration.
550 for (const paramName of [...urlObject.searchParams.keys()]) {
551 if (ignoreURLParametersMatching.some(regExp => regExp.test(paramName))) {
552 urlObject.searchParams.delete(paramName);
553 }
554 }
555
556 return urlObject;
557 }
558
559 /*
560 Copyright 2019 Google LLC
561
562 Use of this source code is governed by an MIT-style
563 license that can be found in the LICENSE file or at
564 https://opensource.org/licenses/MIT.
565 */
566 /**
567 * Generator function that yields possible variations on the original URL to
568 * check, one at a time.
569 *
570 * @param {string} url
571 * @param {Object} options
572 *
573 * @private
574 * @memberof module:workbox-precaching
575 */
576
577 function* generateURLVariations(url, {
578 ignoreURLParametersMatching,
579 directoryIndex,
580 cleanURLs,
581 urlManipulation
582 } = {}) {
583 const urlObject = new URL(url, location);
584 urlObject.hash = '';
585 yield urlObject.href;
586 const urlWithoutIgnoredParams = removeIgnoredSearchParams(urlObject, ignoreURLParametersMatching);
587 yield urlWithoutIgnoredParams.href;
588
589 if (directoryIndex && urlWithoutIgnoredParams.pathname.endsWith('/')) {
590 const directoryURL = new URL(urlWithoutIgnoredParams);
591 directoryURL.pathname += directoryIndex;
592 yield directoryURL.href;
593 }
594
595 if (cleanURLs) {
596 const cleanURL = new URL(urlWithoutIgnoredParams);
597 cleanURL.pathname += '.html';
598 yield cleanURL.href;
599 }
600
601 if (urlManipulation) {
602 const additionalURLs = urlManipulation({
603 url: urlObject
604 });
605
606 for (const urlToAttempt of additionalURLs) {
607 yield urlToAttempt.href;
608 }
609 }
610 }
611
612 /*
613 Copyright 2019 Google LLC
614
615 Use of this source code is governed by an MIT-style
616 license that can be found in the LICENSE file or at
617 https://opensource.org/licenses/MIT.
618 */
619 /**
620 * This function will take the request URL and manipulate it based on the
621 * configuration options.
622 *
623 * @param {string} url
624 * @param {Object} options
625 * @return {string} Returns the URL in the cache that matches the request,
626 * if possible.
627 *
628 * @private
629 */
630
631 const getCacheKeyForURL = (url, options) => {
632 const precacheController = getOrCreatePrecacheController();
633 const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
634
635 for (const possibleURL of generateURLVariations(url, options)) {
636 const possibleCacheKey = urlsToCacheKeys.get(possibleURL);
637
638 if (possibleCacheKey) {
639 return possibleCacheKey;
640 }
641 }
642 };
643
644 /*
645 Copyright 2019 Google LLC
646
647 Use of this source code is governed by an MIT-style
648 license that can be found in the LICENSE file or at
649 https://opensource.org/licenses/MIT.
650 */
651 /**
652 * Adds a `fetch` listener to the service worker that will
653 * respond to
654 * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
655 * with precached assets.
656 *
657 * Requests for assets that aren't precached, the `FetchEvent` will not be
658 * responded to, allowing the event to fall through to other `fetch` event
659 * listeners.
660 *
661 * NOTE: when called more than once this method will replace the previously set
662 * configuration options. Calling it more than once is not recommended outside
663 * of tests.
664 *
665 * @private
666 * @param {Object} options
667 * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
668 * check cache entries for a URLs ending with '/' to see if there is a hit when
669 * appending the `directoryIndex` value.
670 * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/]] An
671 * array of regex's to remove search params when looking for a cache match.
672 * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
673 * check the cache for the URL with a `.html` added to the end of the end.
674 * @param {workbox.precaching~urlManipulation} [options.urlManipulation]
675 * This is a function that should take a URL and return an array of
676 * alternative URL's that should be checked for precache matches.
677 */
678
679 const addFetchListener = ({
680 ignoreURLParametersMatching = [/^utm_/],
681 directoryIndex = 'index.html',
682 cleanURLs = true,
683 urlManipulation = null
684 } = {}) => {
685 const cacheName = cacheNames_mjs.cacheNames.getPrecacheName();
686 addEventListener('fetch', event => {
687 const precachedURL = getCacheKeyForURL(event.request.url, {
688 cleanURLs,
689 directoryIndex,
690 ignoreURLParametersMatching,
691 urlManipulation
692 });
693
694 if (!precachedURL) {
695 {
696 logger_mjs.logger.debug(`Precaching did not find a match for ` + getFriendlyURL_mjs.getFriendlyURL(event.request.url));
697 }
698
699 return;
700 }
701
702 let responsePromise = caches.open(cacheName).then(cache => {
703 return cache.match(precachedURL);
704 }).then(cachedResponse => {
705 if (cachedResponse) {
706 return cachedResponse;
707 } // Fall back to the network if we don't have a cached response
708 // (perhaps due to manual cache cleanup).
709
710
711 {
712 logger_mjs.logger.warn(`The precached response for ` + `${getFriendlyURL_mjs.getFriendlyURL(precachedURL)} in ${cacheName} was not found. ` + `Falling back to the network instead.`);
713 }
714
715 return fetch(precachedURL);
716 });
717
718 {
719 responsePromise = responsePromise.then(response => {
720 // Workbox is going to handle the route.
721 // print the routing details to the console.
722 logger_mjs.logger.groupCollapsed(`Precaching is responding to: ` + getFriendlyURL_mjs.getFriendlyURL(event.request.url));
723 logger_mjs.logger.log(`Serving the precached url: ${precachedURL}`);
724 logger_mjs.logger.groupCollapsed(`View request details here.`);
725 logger_mjs.logger.log(event.request);
726 logger_mjs.logger.groupEnd();
727 logger_mjs.logger.groupCollapsed(`View response details here.`);
728 logger_mjs.logger.log(response);
729 logger_mjs.logger.groupEnd();
730 logger_mjs.logger.groupEnd();
731 return response;
732 });
733 }
734
735 event.respondWith(responsePromise);
736 });
737 };
738
739 /*
740 Copyright 2019 Google LLC
741 Use of this source code is governed by an MIT-style
742 license that can be found in the LICENSE file or at
743 https://opensource.org/licenses/MIT.
744 */
745 let listenerAdded = false;
746 /**
747 * Add a `fetch` listener to the service worker that will
748 * respond to
749 * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
750 * with precached assets.
751 *
752 * Requests for assets that aren't precached, the `FetchEvent` will not be
753 * responded to, allowing the event to fall through to other `fetch` event
754 * listeners.
755 *
756 * @param {Object} options
757 * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
758 * check cache entries for a URLs ending with '/' to see if there is a hit when
759 * appending the `directoryIndex` value.
760 * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/]] An
761 * array of regex's to remove search params when looking for a cache match.
762 * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
763 * check the cache for the URL with a `.html` added to the end of the end.
764 * @param {workbox.precaching~urlManipulation} [options.urlManipulation]
765 * This is a function that should take a URL and return an array of
766 * alternative URL's that should be checked for precache matches.
767 *
768 * @alias workbox.precaching.addRoute
769 */
770
771 const addRoute = options => {
772 if (!listenerAdded) {
773 addFetchListener(options);
774 listenerAdded = true;
775 }
776 };
777
778 /*
779 Copyright 2018 Google LLC
780
781 Use of this source code is governed by an MIT-style
782 license that can be found in the LICENSE file or at
783 https://opensource.org/licenses/MIT.
784 */
785 const SUBSTRING_TO_FIND = '-precache-';
786 /**
787 * Cleans up incompatible precaches that were created by older versions of
788 * Workbox, by a service worker registered under the current scope.
789 *
790 * This is meant to be called as part of the `activate` event.
791 *
792 * This should be safe to use as long as you don't include `substringToFind`
793 * (defaulting to `-precache-`) in your non-precache cache names.
794 *
795 * @param {string} currentPrecacheName The cache name currently in use for
796 * precaching. This cache won't be deleted.
797 * @param {string} [substringToFind='-precache-'] Cache names which include this
798 * substring will be deleted (excluding `currentPrecacheName`).
799 * @return {Array<string>} A list of all the cache names that were deleted.
800 *
801 * @private
802 * @memberof module:workbox-precaching
803 */
804
805 const deleteOutdatedCaches = async (currentPrecacheName, substringToFind = SUBSTRING_TO_FIND) => {
806 const cacheNames = await caches.keys();
807 const cacheNamesToDelete = cacheNames.filter(cacheName => {
808 return cacheName.includes(substringToFind) && cacheName.includes(self.registration.scope) && cacheName !== currentPrecacheName;
809 });
810 await Promise.all(cacheNamesToDelete.map(cacheName => caches.delete(cacheName)));
811 return cacheNamesToDelete;
812 };
813
814 /*
815 Copyright 2019 Google LLC
816
817 Use of this source code is governed by an MIT-style
818 license that can be found in the LICENSE file or at
819 https://opensource.org/licenses/MIT.
820 */
821 /**
822 * Adds an `activate` event listener which will clean up incompatible
823 * precaches that were created by older versions of Workbox.
824 *
825 * @alias workbox.precaching.cleanupOutdatedCaches
826 */
827
828 const cleanupOutdatedCaches = () => {
829 addEventListener('activate', event => {
830 const cacheName = cacheNames_mjs.cacheNames.getPrecacheName();
831 event.waitUntil(deleteOutdatedCaches(cacheName).then(cachesDeleted => {
832 {
833 if (cachesDeleted.length > 0) {
834 logger_mjs.logger.log(`The following out-of-date precaches were cleaned up ` + `automatically:`, cachesDeleted);
835 }
836 }
837 }));
838 });
839 };
840
841 /*
842 Copyright 2019 Google LLC
843
844 Use of this source code is governed by an MIT-style
845 license that can be found in the LICENSE file or at
846 https://opensource.org/licenses/MIT.
847 */
848 /**
849 * Takes in a URL, and returns the corresponding URL that could be used to
850 * lookup the entry in the precache.
851 *
852 * If a relative URL is provided, the location of the service worker file will
853 * be used as the base.
854 *
855 * For precached entries without revision information, the cache key will be the
856 * same as the original URL.
857 *
858 * For precached entries with revision information, the cache key will be the
859 * original URL with the addition of a query parameter used for keeping track of
860 * the revision info.
861 *
862 * @param {string} url The URL whose cache key to look up.
863 * @return {string} The cache key that corresponds to that URL.
864 *
865 * @alias workbox.precaching.getCacheKeyForURL
866 */
867
868 const getCacheKeyForURL$1 = url => {
869 const precacheController = getOrCreatePrecacheController();
870 return precacheController.getCacheKeyForURL(url);
871 };
872
873 /*
874 Copyright 2019 Google LLC
875
876 Use of this source code is governed by an MIT-style
877 license that can be found in the LICENSE file or at
878 https://opensource.org/licenses/MIT.
879 */
880
881 const installListener = event => {
882 const precacheController = getOrCreatePrecacheController();
883 const plugins = precachePlugins.get();
884 event.waitUntil(precacheController.install({
885 event,
886 plugins
887 }).catch(error => {
888 {
889 logger_mjs.logger.error(`Service worker installation failed. It will ` + `be retried automatically during the next navigation.`);
890 } // Re-throw the error to ensure installation fails.
891
892
893 throw error;
894 }));
895 };
896
897 const activateListener = event => {
898 const precacheController = getOrCreatePrecacheController();
899 const plugins = precachePlugins.get();
900 event.waitUntil(precacheController.activate({
901 event,
902 plugins
903 }));
904 };
905 /**
906 * Adds items to the precache list, removing any duplicates and
907 * stores the files in the
908 * ["precache cache"]{@link module:workbox-core.cacheNames} when the service
909 * worker installs.
910 *
911 * This method can be called multiple times.
912 *
913 * Please note: This method **will not** serve any of the cached files for you.
914 * It only precaches files. To respond to a network request you call
915 * [addRoute()]{@link module:workbox-precaching.addRoute}.
916 *
917 * If you have a single array of files to precache, you can just call
918 * [precacheAndRoute()]{@link module:workbox-precaching.precacheAndRoute}.
919 *
920 * @param {Array<Object|string>} entries Array of entries to precache.
921 *
922 * @alias workbox.precaching.precache
923 */
924
925
926 const precache = entries => {
927 const precacheController = getOrCreatePrecacheController();
928 precacheController.addToCacheList(entries);
929
930 if (entries.length > 0) {
931 // NOTE: these listeners will only be added once (even if the `precache()`
932 // method is called multiple times) because event listeners are implemented
933 // as a set, where each listener must be unique.
934 addEventListener('install', installListener);
935 addEventListener('activate', activateListener);
936 }
937 };
938
939 /*
940 Copyright 2019 Google LLC
941
942 Use of this source code is governed by an MIT-style
943 license that can be found in the LICENSE file or at
944 https://opensource.org/licenses/MIT.
945 */
946 /**
947 * This method will add entries to the precache list and add a route to
948 * respond to fetch events.
949 *
950 * This is a convenience method that will call
951 * [precache()]{@link module:workbox-precaching.precache} and
952 * [addRoute()]{@link module:workbox-precaching.addRoute} in a single call.
953 *
954 * @param {Array<Object|string>} entries Array of entries to precache.
955 * @param {Object} options See
956 * [addRoute() options]{@link module:workbox-precaching.addRoute}.
957 *
958 * @alias workbox.precaching.precacheAndRoute
959 */
960
961 const precacheAndRoute = (entries, options) => {
962 precache(entries);
963 addRoute(options);
964 };
965
966 /*
967 Copyright 2018 Google LLC
968
969 Use of this source code is governed by an MIT-style
970 license that can be found in the LICENSE file or at
971 https://opensource.org/licenses/MIT.
972 */
973
974 {
975 assert_mjs.assert.isSWEnv('workbox-precaching');
976 }
977
978 exports.addPlugins = addPlugins;
979 exports.addRoute = addRoute;
980 exports.cleanupOutdatedCaches = cleanupOutdatedCaches;
981 exports.getCacheKeyForURL = getCacheKeyForURL$1;
982 exports.precache = precache;
983 exports.precacheAndRoute = precacheAndRoute;
984 exports.PrecacheController = PrecacheController;
985
986 return exports;
987
988}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
989