PrecacheController.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. Copyright 2019 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 { assert } from 'workbox-core/_private/assert.js';
  8. import { cacheNames } from 'workbox-core/_private/cacheNames.js';
  9. import { logger } from 'workbox-core/_private/logger.js';
  10. import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
  11. import { waitUntil } from 'workbox-core/_private/waitUntil.js';
  12. import { createCacheKey } from './utils/createCacheKey.js';
  13. import { PrecacheInstallReportPlugin } from './utils/PrecacheInstallReportPlugin.js';
  14. import { PrecacheCacheKeyPlugin } from './utils/PrecacheCacheKeyPlugin.js';
  15. import { printCleanupDetails } from './utils/printCleanupDetails.js';
  16. import { printInstallDetails } from './utils/printInstallDetails.js';
  17. import { PrecacheStrategy } from './PrecacheStrategy.js';
  18. import './_version.js';
  19. /**
  20. * Performs efficient precaching of assets.
  21. *
  22. * @memberof workbox-precaching
  23. */
  24. class PrecacheController {
  25. /**
  26. * Create a new PrecacheController.
  27. *
  28. * @param {Object} [options]
  29. * @param {string} [options.cacheName] The cache to use for precaching.
  30. * @param {string} [options.plugins] Plugins to use when precaching as well
  31. * as responding to fetch events for precached assets.
  32. * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
  33. * get the response from the network if there's a precache miss.
  34. */
  35. constructor({ cacheName, plugins = [], fallbackToNetwork = true, } = {}) {
  36. this._urlsToCacheKeys = new Map();
  37. this._urlsToCacheModes = new Map();
  38. this._cacheKeysToIntegrities = new Map();
  39. this._strategy = new PrecacheStrategy({
  40. cacheName: cacheNames.getPrecacheName(cacheName),
  41. plugins: [
  42. ...plugins,
  43. new PrecacheCacheKeyPlugin({ precacheController: this }),
  44. ],
  45. fallbackToNetwork,
  46. });
  47. // Bind the install and activate methods to the instance.
  48. this.install = this.install.bind(this);
  49. this.activate = this.activate.bind(this);
  50. }
  51. /**
  52. * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
  53. * used to cache assets and respond to fetch events.
  54. */
  55. get strategy() {
  56. return this._strategy;
  57. }
  58. /**
  59. * Adds items to the precache list, removing any duplicates and
  60. * stores the files in the
  61. * {@link workbox-core.cacheNames|"precache cache"} when the service
  62. * worker installs.
  63. *
  64. * This method can be called multiple times.
  65. *
  66. * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
  67. */
  68. precache(entries) {
  69. this.addToCacheList(entries);
  70. if (!this._installAndActiveListenersAdded) {
  71. self.addEventListener('install', this.install);
  72. self.addEventListener('activate', this.activate);
  73. this._installAndActiveListenersAdded = true;
  74. }
  75. }
  76. /**
  77. * This method will add items to the precache list, removing duplicates
  78. * and ensuring the information is valid.
  79. *
  80. * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
  81. * Array of entries to precache.
  82. */
  83. addToCacheList(entries) {
  84. if (process.env.NODE_ENV !== 'production') {
  85. assert.isArray(entries, {
  86. moduleName: 'workbox-precaching',
  87. className: 'PrecacheController',
  88. funcName: 'addToCacheList',
  89. paramName: 'entries',
  90. });
  91. }
  92. const urlsToWarnAbout = [];
  93. for (const entry of entries) {
  94. // See https://github.com/GoogleChrome/workbox/issues/2259
  95. if (typeof entry === 'string') {
  96. urlsToWarnAbout.push(entry);
  97. }
  98. else if (entry && entry.revision === undefined) {
  99. urlsToWarnAbout.push(entry.url);
  100. }
  101. const { cacheKey, url } = createCacheKey(entry);
  102. const cacheMode = typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
  103. if (this._urlsToCacheKeys.has(url) &&
  104. this._urlsToCacheKeys.get(url) !== cacheKey) {
  105. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  106. firstEntry: this._urlsToCacheKeys.get(url),
  107. secondEntry: cacheKey,
  108. });
  109. }
  110. if (typeof entry !== 'string' && entry.integrity) {
  111. if (this._cacheKeysToIntegrities.has(cacheKey) &&
  112. this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  113. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  114. url,
  115. });
  116. }
  117. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  118. }
  119. this._urlsToCacheKeys.set(url, cacheKey);
  120. this._urlsToCacheModes.set(url, cacheMode);
  121. if (urlsToWarnAbout.length > 0) {
  122. const warningMessage = `Workbox is precaching URLs without revision ` +
  123. `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` +
  124. `Learn more at https://bit.ly/wb-precache`;
  125. if (process.env.NODE_ENV === 'production') {
  126. // Use console directly to display this warning without bloating
  127. // bundle sizes by pulling in all of the logger codebase in prod.
  128. console.warn(warningMessage);
  129. }
  130. else {
  131. logger.warn(warningMessage);
  132. }
  133. }
  134. }
  135. }
  136. /**
  137. * Precaches new and updated assets. Call this method from the service worker
  138. * install event.
  139. *
  140. * Note: this method calls `event.waitUntil()` for you, so you do not need
  141. * to call it yourself in your event handlers.
  142. *
  143. * @param {ExtendableEvent} event
  144. * @return {Promise<workbox-precaching.InstallResult>}
  145. */
  146. install(event) {
  147. // waitUntil returns Promise<any>
  148. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  149. return waitUntil(event, async () => {
  150. const installReportPlugin = new PrecacheInstallReportPlugin();
  151. this.strategy.plugins.push(installReportPlugin);
  152. // Cache entries one at a time.
  153. // See https://github.com/GoogleChrome/workbox/issues/2528
  154. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  155. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  156. const cacheMode = this._urlsToCacheModes.get(url);
  157. const request = new Request(url, {
  158. integrity,
  159. cache: cacheMode,
  160. credentials: 'same-origin',
  161. });
  162. await Promise.all(this.strategy.handleAll({
  163. params: { cacheKey },
  164. request,
  165. event,
  166. }));
  167. }
  168. const { updatedURLs, notUpdatedURLs } = installReportPlugin;
  169. if (process.env.NODE_ENV !== 'production') {
  170. printInstallDetails(updatedURLs, notUpdatedURLs);
  171. }
  172. return { updatedURLs, notUpdatedURLs };
  173. });
  174. }
  175. /**
  176. * Deletes assets that are no longer present in the current precache manifest.
  177. * Call this method from the service worker activate event.
  178. *
  179. * Note: this method calls `event.waitUntil()` for you, so you do not need
  180. * to call it yourself in your event handlers.
  181. *
  182. * @param {ExtendableEvent} event
  183. * @return {Promise<workbox-precaching.CleanupResult>}
  184. */
  185. activate(event) {
  186. // waitUntil returns Promise<any>
  187. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  188. return waitUntil(event, async () => {
  189. const cache = await self.caches.open(this.strategy.cacheName);
  190. const currentlyCachedRequests = await cache.keys();
  191. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  192. const deletedURLs = [];
  193. for (const request of currentlyCachedRequests) {
  194. if (!expectedCacheKeys.has(request.url)) {
  195. await cache.delete(request);
  196. deletedURLs.push(request.url);
  197. }
  198. }
  199. if (process.env.NODE_ENV !== 'production') {
  200. printCleanupDetails(deletedURLs);
  201. }
  202. return { deletedURLs };
  203. });
  204. }
  205. /**
  206. * Returns a mapping of a precached URL to the corresponding cache key, taking
  207. * into account the revision information for the URL.
  208. *
  209. * @return {Map<string, string>} A URL to cache key mapping.
  210. */
  211. getURLsToCacheKeys() {
  212. return this._urlsToCacheKeys;
  213. }
  214. /**
  215. * Returns a list of all the URLs that have been precached by the current
  216. * service worker.
  217. *
  218. * @return {Array<string>} The precached URLs.
  219. */
  220. getCachedURLs() {
  221. return [...this._urlsToCacheKeys.keys()];
  222. }
  223. /**
  224. * Returns the cache key used for storing a given URL. If that URL is
  225. * unversioned, like `/index.html', then the cache key will be the original
  226. * URL with a search parameter appended to it.
  227. *
  228. * @param {string} url A URL whose cache key you want to look up.
  229. * @return {string} The versioned URL that corresponds to a cache key
  230. * for the original URL, or undefined if that URL isn't precached.
  231. */
  232. getCacheKeyForURL(url) {
  233. const urlObject = new URL(url, location.href);
  234. return this._urlsToCacheKeys.get(urlObject.href);
  235. }
  236. /**
  237. * @param {string} url A cache key whose SRI you want to look up.
  238. * @return {string} The subresource integrity associated with the cache key,
  239. * or undefined if it's not set.
  240. */
  241. getIntegrityForCacheKey(cacheKey) {
  242. return this._cacheKeysToIntegrities.get(cacheKey);
  243. }
  244. /**
  245. * This acts as a drop-in replacement for
  246. * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  247. * with the following differences:
  248. *
  249. * - It knows what the name of the precache is, and only checks in that cache.
  250. * - It allows you to pass in an "original" URL without versioning parameters,
  251. * and it will automatically look up the correct cache key for the currently
  252. * active revision of that URL.
  253. *
  254. * E.g., `matchPrecache('index.html')` will find the correct precached
  255. * response for the currently active service worker, even if the actual cache
  256. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  257. *
  258. * @param {string|Request} request The key (without revisioning parameters)
  259. * to look up in the precache.
  260. * @return {Promise<Response|undefined>}
  261. */
  262. async matchPrecache(request) {
  263. const url = request instanceof Request ? request.url : request;
  264. const cacheKey = this.getCacheKeyForURL(url);
  265. if (cacheKey) {
  266. const cache = await self.caches.open(this.strategy.cacheName);
  267. return cache.match(cacheKey);
  268. }
  269. return undefined;
  270. }
  271. /**
  272. * Returns a function that looks up `url` in the precache (taking into
  273. * account revision information), and returns the corresponding `Response`.
  274. *
  275. * @param {string} url The precached URL which will be used to lookup the
  276. * `Response`.
  277. * @return {workbox-routing~handlerCallback}
  278. */
  279. createHandlerBoundToURL(url) {
  280. const cacheKey = this.getCacheKeyForURL(url);
  281. if (!cacheKey) {
  282. throw new WorkboxError('non-precached-url', { url });
  283. }
  284. return (options) => {
  285. options.request = new Request(url);
  286. options.params = Object.assign({ cacheKey }, options.params);
  287. return this.strategy.handle(options);
  288. };
  289. }
  290. }
  291. export { PrecacheController };