PrecacheRoute.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2020 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { logger } from 'workbox-core/_private/logger.js';
  8. import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
  9. import { Route } from 'workbox-routing/Route.js';
  10. import { generateURLVariations } from './utils/generateURLVariations.js';
  11. import './_version.js';
  12. /**
  13. * A subclass of {@link workbox-routing.Route} that takes a
  14. * {@link workbox-precaching.PrecacheController}
  15. * instance and uses it to match incoming requests and handle fetching
  16. * responses from the precache.
  17. *
  18. * @memberof workbox-precaching
  19. * @extends workbox-routing.Route
  20. */
  21. class PrecacheRoute extends Route {
  22. /**
  23. * @param {PrecacheController} precacheController A `PrecacheController`
  24. * instance used to both match requests and respond to fetch events.
  25. * @param {Object} [options] Options to control how requests are matched
  26. * against the list of precached URLs.
  27. * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
  28. * check cache entries for a URLs ending with '/' to see if there is a hit when
  29. * appending the `directoryIndex` value.
  30. * @param {Array<RegExp>} [options.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]] An
  31. * array of regex's to remove search params when looking for a cache match.
  32. * @param {boolean} [options.cleanURLs=true] The `cleanURLs` option will
  33. * check the cache for the URL with a `.html` added to the end of the end.
  34. * @param {workbox-precaching~urlManipulation} [options.urlManipulation]
  35. * This is a function that should take a URL and return an array of
  36. * alternative URLs that should be checked for precache matches.
  37. */
  38. constructor(precacheController, options) {
  39. const match = ({ request, }) => {
  40. const urlsToCacheKeys = precacheController.getURLsToCacheKeys();
  41. for (const possibleURL of generateURLVariations(request.url, options)) {
  42. const cacheKey = urlsToCacheKeys.get(possibleURL);
  43. if (cacheKey) {
  44. const integrity = precacheController.getIntegrityForCacheKey(cacheKey);
  45. return { cacheKey, integrity };
  46. }
  47. }
  48. if (process.env.NODE_ENV !== 'production') {
  49. logger.debug(`Precaching did not find a match for ` + getFriendlyURL(request.url));
  50. }
  51. return;
  52. };
  53. super(match, precacheController.strategy);
  54. }
  55. }
  56. export { PrecacheRoute };