PrecacheController.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 { cacheWrapper } from 'workbox-core/_private/cacheWrapper.js';
  10. import { fetchWrapper } from 'workbox-core/_private/fetchWrapper.js';
  11. import { logger } from 'workbox-core/_private/logger.js';
  12. import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
  13. import { copyResponse } from 'workbox-core/copyResponse.js';
  14. import { createCacheKey } from './utils/createCacheKey.js';
  15. import { printCleanupDetails } from './utils/printCleanupDetails.js';
  16. import { printInstallDetails } from './utils/printInstallDetails.js';
  17. import './_version.js';
  18. /**
  19. * Performs efficient precaching of assets.
  20. *
  21. * @memberof module:workbox-precaching
  22. */
  23. class PrecacheController {
  24. /**
  25. * Create a new PrecacheController.
  26. *
  27. * @param {string} [cacheName] An optional name for the cache, to override
  28. * the default precache name.
  29. */
  30. constructor(cacheName) {
  31. this._cacheName = cacheNames.getPrecacheName(cacheName);
  32. this._urlsToCacheKeys = new Map();
  33. this._urlsToCacheModes = new Map();
  34. this._cacheKeysToIntegrities = new Map();
  35. }
  36. /**
  37. * This method will add items to the precache list, removing duplicates
  38. * and ensuring the information is valid.
  39. *
  40. * @param {
  41. * Array<module:workbox-precaching.PrecacheController.PrecacheEntry|string>
  42. * } entries Array of entries to precache.
  43. */
  44. addToCacheList(entries) {
  45. if (process.env.NODE_ENV !== 'production') {
  46. assert.isArray(entries, {
  47. moduleName: 'workbox-precaching',
  48. className: 'PrecacheController',
  49. funcName: 'addToCacheList',
  50. paramName: 'entries',
  51. });
  52. }
  53. const urlsToWarnAbout = [];
  54. for (const entry of entries) {
  55. // See https://github.com/GoogleChrome/workbox/issues/2259
  56. if (typeof entry === 'string') {
  57. urlsToWarnAbout.push(entry);
  58. }
  59. else if (entry && entry.revision === undefined) {
  60. urlsToWarnAbout.push(entry.url);
  61. }
  62. const { cacheKey, url } = createCacheKey(entry);
  63. const cacheMode = (typeof entry !== 'string' && entry.revision) ?
  64. 'reload' : 'default';
  65. if (this._urlsToCacheKeys.has(url) &&
  66. this._urlsToCacheKeys.get(url) !== cacheKey) {
  67. throw new WorkboxError('add-to-cache-list-conflicting-entries', {
  68. firstEntry: this._urlsToCacheKeys.get(url),
  69. secondEntry: cacheKey,
  70. });
  71. }
  72. if (typeof entry !== 'string' && entry.integrity) {
  73. if (this._cacheKeysToIntegrities.has(cacheKey) &&
  74. this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
  75. throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
  76. url,
  77. });
  78. }
  79. this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
  80. }
  81. this._urlsToCacheKeys.set(url, cacheKey);
  82. this._urlsToCacheModes.set(url, cacheMode);
  83. if (urlsToWarnAbout.length > 0) {
  84. const warningMessage = `Workbox is precaching URLs without revision ` +
  85. `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` +
  86. `Learn more at https://bit.ly/wb-precache`;
  87. if (process.env.NODE_ENV === 'production') {
  88. // Use console directly to display this warning without bloating
  89. // bundle sizes by pulling in all of the logger codebase in prod.
  90. console.warn(warningMessage);
  91. }
  92. else {
  93. logger.warn(warningMessage);
  94. }
  95. }
  96. }
  97. }
  98. /**
  99. * Precaches new and updated assets. Call this method from the service worker
  100. * install event.
  101. *
  102. * @param {Object} options
  103. * @param {Event} [options.event] The install event (if needed).
  104. * @param {Array<Object>} [options.plugins] Plugins to be used for fetching
  105. * and caching during install.
  106. * @return {Promise<module:workbox-precaching.InstallResult>}
  107. */
  108. async install({ event, plugins } = {}) {
  109. if (process.env.NODE_ENV !== 'production') {
  110. if (plugins) {
  111. assert.isArray(plugins, {
  112. moduleName: 'workbox-precaching',
  113. className: 'PrecacheController',
  114. funcName: 'install',
  115. paramName: 'plugins',
  116. });
  117. }
  118. }
  119. const toBePrecached = [];
  120. const alreadyPrecached = [];
  121. const cache = await self.caches.open(this._cacheName);
  122. const alreadyCachedRequests = await cache.keys();
  123. const existingCacheKeys = new Set(alreadyCachedRequests.map((request) => request.url));
  124. for (const [url, cacheKey] of this._urlsToCacheKeys) {
  125. if (existingCacheKeys.has(cacheKey)) {
  126. alreadyPrecached.push(url);
  127. }
  128. else {
  129. toBePrecached.push({ cacheKey, url });
  130. }
  131. }
  132. const precacheRequests = toBePrecached.map(({ cacheKey, url }) => {
  133. const integrity = this._cacheKeysToIntegrities.get(cacheKey);
  134. const cacheMode = this._urlsToCacheModes.get(url);
  135. return this._addURLToCache({
  136. cacheKey,
  137. cacheMode,
  138. event,
  139. integrity,
  140. plugins,
  141. url,
  142. });
  143. });
  144. await Promise.all(precacheRequests);
  145. const updatedURLs = toBePrecached.map((item) => item.url);
  146. if (process.env.NODE_ENV !== 'production') {
  147. printInstallDetails(updatedURLs, alreadyPrecached);
  148. }
  149. return {
  150. updatedURLs,
  151. notUpdatedURLs: alreadyPrecached,
  152. };
  153. }
  154. /**
  155. * Deletes assets that are no longer present in the current precache manifest.
  156. * Call this method from the service worker activate event.
  157. *
  158. * @return {Promise<module:workbox-precaching.CleanupResult>}
  159. */
  160. async activate() {
  161. const cache = await self.caches.open(this._cacheName);
  162. const currentlyCachedRequests = await cache.keys();
  163. const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
  164. const deletedURLs = [];
  165. for (const request of currentlyCachedRequests) {
  166. if (!expectedCacheKeys.has(request.url)) {
  167. await cache.delete(request);
  168. deletedURLs.push(request.url);
  169. }
  170. }
  171. if (process.env.NODE_ENV !== 'production') {
  172. printCleanupDetails(deletedURLs);
  173. }
  174. return { deletedURLs };
  175. }
  176. /**
  177. * Requests the entry and saves it to the cache if the response is valid.
  178. * By default, any response with a status code of less than 400 (including
  179. * opaque responses) is considered valid.
  180. *
  181. * If you need to use custom criteria to determine what's valid and what
  182. * isn't, then pass in an item in `options.plugins` that implements the
  183. * `cacheWillUpdate()` lifecycle event.
  184. *
  185. * @private
  186. * @param {Object} options
  187. * @param {string} options.cacheKey The string to use a cache key.
  188. * @param {string} options.url The URL to fetch and cache.
  189. * @param {string} [options.cacheMode] The cache mode for the network request.
  190. * @param {Event} [options.event] The install event (if passed).
  191. * @param {Array<Object>} [options.plugins] An array of plugins to apply to
  192. * fetch and caching.
  193. * @param {string} [options.integrity] The value to use for the `integrity`
  194. * field when making the request.
  195. */
  196. async _addURLToCache({ cacheKey, url, cacheMode, event, plugins, integrity }) {
  197. const request = new Request(url, {
  198. integrity,
  199. cache: cacheMode,
  200. credentials: 'same-origin',
  201. });
  202. let response = await fetchWrapper.fetch({
  203. event,
  204. plugins,
  205. request,
  206. });
  207. // Allow developers to override the default logic about what is and isn't
  208. // valid by passing in a plugin implementing cacheWillUpdate(), e.g.
  209. // a `CacheableResponsePlugin` instance.
  210. let cacheWillUpdatePlugin;
  211. for (const plugin of (plugins || [])) {
  212. if ('cacheWillUpdate' in plugin) {
  213. cacheWillUpdatePlugin = plugin;
  214. }
  215. }
  216. const isValidResponse = cacheWillUpdatePlugin ?
  217. // Use a callback if provided. It returns a truthy value if valid.
  218. // NOTE: invoke the method on the plugin instance so the `this` context
  219. // is correct.
  220. await cacheWillUpdatePlugin.cacheWillUpdate({ event, request, response }) :
  221. // Otherwise, default to considering any response status under 400 valid.
  222. // This includes, by default, considering opaque responses valid.
  223. response.status < 400;
  224. // Consider this a failure, leading to the `install` handler failing, if
  225. // we get back an invalid response.
  226. if (!isValidResponse) {
  227. throw new WorkboxError('bad-precaching-response', {
  228. url,
  229. status: response.status,
  230. });
  231. }
  232. // Redirected responses cannot be used to satisfy a navigation request, so
  233. // any redirected response must be "copied" rather than cloned, so the new
  234. // response doesn't contain the `redirected` flag. See:
  235. // https://bugs.chromium.org/p/chromium/issues/detail?id=669363&desc=2#c1
  236. if (response.redirected) {
  237. response = await copyResponse(response);
  238. }
  239. await cacheWrapper.put({
  240. event,
  241. plugins,
  242. response,
  243. // `request` already uses `url`. We may be able to reuse it.
  244. request: cacheKey === url ? request : new Request(cacheKey),
  245. cacheName: this._cacheName,
  246. matchOptions: {
  247. ignoreSearch: true,
  248. },
  249. });
  250. }
  251. /**
  252. * Returns a mapping of a precached URL to the corresponding cache key, taking
  253. * into account the revision information for the URL.
  254. *
  255. * @return {Map<string, string>} A URL to cache key mapping.
  256. */
  257. getURLsToCacheKeys() {
  258. return this._urlsToCacheKeys;
  259. }
  260. /**
  261. * Returns a list of all the URLs that have been precached by the current
  262. * service worker.
  263. *
  264. * @return {Array<string>} The precached URLs.
  265. */
  266. getCachedURLs() {
  267. return [...this._urlsToCacheKeys.keys()];
  268. }
  269. /**
  270. * Returns the cache key used for storing a given URL. If that URL is
  271. * unversioned, like `/index.html', then the cache key will be the original
  272. * URL with a search parameter appended to it.
  273. *
  274. * @param {string} url A URL whose cache key you want to look up.
  275. * @return {string} The versioned URL that corresponds to a cache key
  276. * for the original URL, or undefined if that URL isn't precached.
  277. */
  278. getCacheKeyForURL(url) {
  279. const urlObject = new URL(url, location.href);
  280. return this._urlsToCacheKeys.get(urlObject.href);
  281. }
  282. /**
  283. * This acts as a drop-in replacement for [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
  284. * with the following differences:
  285. *
  286. * - It knows what the name of the precache is, and only checks in that cache.
  287. * - It allows you to pass in an "original" URL without versioning parameters,
  288. * and it will automatically look up the correct cache key for the currently
  289. * active revision of that URL.
  290. *
  291. * E.g., `matchPrecache('index.html')` will find the correct precached
  292. * response for the currently active service worker, even if the actual cache
  293. * key is `'/index.html?__WB_REVISION__=1234abcd'`.
  294. *
  295. * @param {string|Request} request The key (without revisioning parameters)
  296. * to look up in the precache.
  297. * @return {Promise<Response|undefined>}
  298. */
  299. async matchPrecache(request) {
  300. const url = request instanceof Request ? request.url : request;
  301. const cacheKey = this.getCacheKeyForURL(url);
  302. if (cacheKey) {
  303. const cache = await self.caches.open(this._cacheName);
  304. return cache.match(cacheKey);
  305. }
  306. return undefined;
  307. }
  308. /**
  309. * Returns a function that can be used within a
  310. * {@link module:workbox-routing.Route} that will find a response for the
  311. * incoming request against the precache.
  312. *
  313. * If for an unexpected reason there is a cache miss for the request,
  314. * this will fall back to retrieving the `Response` via `fetch()` when
  315. * `fallbackToNetwork` is `true`.
  316. *
  317. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  318. * response from the network if there's a precache miss.
  319. * @return {module:workbox-routing~handlerCallback}
  320. */
  321. createHandler(fallbackToNetwork = true) {
  322. return async ({ request }) => {
  323. try {
  324. const response = await this.matchPrecache(request);
  325. if (response) {
  326. return response;
  327. }
  328. // This shouldn't normally happen, but there are edge cases:
  329. // https://github.com/GoogleChrome/workbox/issues/1441
  330. throw new WorkboxError('missing-precache-entry', {
  331. cacheName: this._cacheName,
  332. url: request instanceof Request ? request.url : request,
  333. });
  334. }
  335. catch (error) {
  336. if (fallbackToNetwork) {
  337. if (process.env.NODE_ENV !== 'production') {
  338. logger.debug(`Unable to respond with precached response. ` +
  339. `Falling back to network.`, error);
  340. }
  341. return fetch(request);
  342. }
  343. throw error;
  344. }
  345. };
  346. }
  347. /**
  348. * Returns a function that looks up `url` in the precache (taking into
  349. * account revision information), and returns the corresponding `Response`.
  350. *
  351. * If for an unexpected reason there is a cache miss when looking up `url`,
  352. * this will fall back to retrieving the `Response` via `fetch()` when
  353. * `fallbackToNetwork` is `true`.
  354. *
  355. * @param {string} url The precached URL which will be used to lookup the
  356. * `Response`.
  357. * @param {boolean} [fallbackToNetwork=true] Whether to attempt to get the
  358. * response from the network if there's a precache miss.
  359. * @return {module:workbox-routing~handlerCallback}
  360. */
  361. createHandlerBoundToURL(url, fallbackToNetwork = true) {
  362. const cacheKey = this.getCacheKeyForURL(url);
  363. if (!cacheKey) {
  364. throw new WorkboxError('non-precached-url', { url });
  365. }
  366. const handler = this.createHandler(fallbackToNetwork);
  367. const request = new Request(url);
  368. return () => handler({ request });
  369. }
  370. }
  371. export { PrecacheController };