workbox-expiration.dev.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. this.workbox = this.workbox || {};
  2. this.workbox.expiration = (function (exports, DBWrapper_mjs, deleteDatabase_mjs, WorkboxError_mjs, assert_mjs, logger_mjs, cacheNames_mjs, getFriendlyURL_mjs, registerQuotaErrorCallback_mjs) {
  3. 'use strict';
  4. try {
  5. self['workbox:expiration:4.3.1'] && _();
  6. } catch (e) {} // eslint-disable-line
  7. /*
  8. Copyright 2018 Google LLC
  9. Use of this source code is governed by an MIT-style
  10. license that can be found in the LICENSE file or at
  11. https://opensource.org/licenses/MIT.
  12. */
  13. const DB_NAME = 'workbox-expiration';
  14. const OBJECT_STORE_NAME = 'cache-entries';
  15. const normalizeURL = unNormalizedUrl => {
  16. const url = new URL(unNormalizedUrl, location);
  17. url.hash = '';
  18. return url.href;
  19. };
  20. /**
  21. * Returns the timestamp model.
  22. *
  23. * @private
  24. */
  25. class CacheTimestampsModel {
  26. /**
  27. *
  28. * @param {string} cacheName
  29. *
  30. * @private
  31. */
  32. constructor(cacheName) {
  33. this._cacheName = cacheName;
  34. this._db = new DBWrapper_mjs.DBWrapper(DB_NAME, 1, {
  35. onupgradeneeded: event => this._handleUpgrade(event)
  36. });
  37. }
  38. /**
  39. * Should perform an upgrade of indexedDB.
  40. *
  41. * @param {Event} event
  42. *
  43. * @private
  44. */
  45. _handleUpgrade(event) {
  46. const db = event.target.result; // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
  47. // have to use the `id` keyPath here and create our own values (a
  48. // concatenation of `url + cacheName`) instead of simply using
  49. // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
  50. const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
  51. keyPath: 'id'
  52. }); // TODO(philipwalton): once we don't have to support EdgeHTML, we can
  53. // create a single index with the keyPath `['cacheName', 'timestamp']`
  54. // instead of doing both these indexes.
  55. objStore.createIndex('cacheName', 'cacheName', {
  56. unique: false
  57. });
  58. objStore.createIndex('timestamp', 'timestamp', {
  59. unique: false
  60. }); // Previous versions of `workbox-expiration` used `this._cacheName`
  61. // as the IDBDatabase name.
  62. deleteDatabase_mjs.deleteDatabase(this._cacheName);
  63. }
  64. /**
  65. * @param {string} url
  66. * @param {number} timestamp
  67. *
  68. * @private
  69. */
  70. async setTimestamp(url, timestamp) {
  71. url = normalizeURL(url);
  72. await this._db.put(OBJECT_STORE_NAME, {
  73. url,
  74. timestamp,
  75. cacheName: this._cacheName,
  76. // Creating an ID from the URL and cache name won't be necessary once
  77. // Edge switches to Chromium and all browsers we support work with
  78. // array keyPaths.
  79. id: this._getId(url)
  80. });
  81. }
  82. /**
  83. * Returns the timestamp stored for a given URL.
  84. *
  85. * @param {string} url
  86. * @return {number}
  87. *
  88. * @private
  89. */
  90. async getTimestamp(url) {
  91. const entry = await this._db.get(OBJECT_STORE_NAME, this._getId(url));
  92. return entry.timestamp;
  93. }
  94. /**
  95. * Iterates through all the entries in the object store (from newest to
  96. * oldest) and removes entries once either `maxCount` is reached or the
  97. * entry's timestamp is less than `minTimestamp`.
  98. *
  99. * @param {number} minTimestamp
  100. * @param {number} maxCount
  101. *
  102. * @private
  103. */
  104. async expireEntries(minTimestamp, maxCount) {
  105. const entriesToDelete = await this._db.transaction(OBJECT_STORE_NAME, 'readwrite', (txn, done) => {
  106. const store = txn.objectStore(OBJECT_STORE_NAME);
  107. const entriesToDelete = [];
  108. let entriesNotDeletedCount = 0;
  109. store.index('timestamp').openCursor(null, 'prev').onsuccess = ({
  110. target
  111. }) => {
  112. const cursor = target.result;
  113. if (cursor) {
  114. const result = cursor.value; // TODO(philipwalton): once we can use a multi-key index, we
  115. // won't have to check `cacheName` here.
  116. if (result.cacheName === this._cacheName) {
  117. // Delete an entry if it's older than the max age or
  118. // if we already have the max number allowed.
  119. if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
  120. // TODO(philipwalton): we should be able to delete the
  121. // entry right here, but doing so causes an iteration
  122. // bug in Safari stable (fixed in TP). Instead we can
  123. // store the keys of the entries to delete, and then
  124. // delete the separate transactions.
  125. // https://github.com/GoogleChrome/workbox/issues/1978
  126. // cursor.delete();
  127. // We only need to return the URL, not the whole entry.
  128. entriesToDelete.push(cursor.value);
  129. } else {
  130. entriesNotDeletedCount++;
  131. }
  132. }
  133. cursor.continue();
  134. } else {
  135. done(entriesToDelete);
  136. }
  137. };
  138. }); // TODO(philipwalton): once the Safari bug in the following issue is fixed,
  139. // we should be able to remove this loop and do the entry deletion in the
  140. // cursor loop above:
  141. // https://github.com/GoogleChrome/workbox/issues/1978
  142. const urlsDeleted = [];
  143. for (const entry of entriesToDelete) {
  144. await this._db.delete(OBJECT_STORE_NAME, entry.id);
  145. urlsDeleted.push(entry.url);
  146. }
  147. return urlsDeleted;
  148. }
  149. /**
  150. * Takes a URL and returns an ID that will be unique in the object store.
  151. *
  152. * @param {string} url
  153. * @return {string}
  154. *
  155. * @private
  156. */
  157. _getId(url) {
  158. // Creating an ID from the URL and cache name won't be necessary once
  159. // Edge switches to Chromium and all browsers we support work with
  160. // array keyPaths.
  161. return this._cacheName + '|' + normalizeURL(url);
  162. }
  163. }
  164. /*
  165. Copyright 2018 Google LLC
  166. Use of this source code is governed by an MIT-style
  167. license that can be found in the LICENSE file or at
  168. https://opensource.org/licenses/MIT.
  169. */
  170. /**
  171. * The `CacheExpiration` class allows you define an expiration and / or
  172. * limit on the number of responses stored in a
  173. * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
  174. *
  175. * @memberof workbox.expiration
  176. */
  177. class CacheExpiration {
  178. /**
  179. * To construct a new CacheExpiration instance you must provide at least
  180. * one of the `config` properties.
  181. *
  182. * @param {string} cacheName Name of the cache to apply restrictions to.
  183. * @param {Object} config
  184. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  185. * Entries used the least will be removed as the maximum is reached.
  186. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  187. * it's treated as stale and removed.
  188. */
  189. constructor(cacheName, config = {}) {
  190. {
  191. assert_mjs.assert.isType(cacheName, 'string', {
  192. moduleName: 'workbox-expiration',
  193. className: 'CacheExpiration',
  194. funcName: 'constructor',
  195. paramName: 'cacheName'
  196. });
  197. if (!(config.maxEntries || config.maxAgeSeconds)) {
  198. throw new WorkboxError_mjs.WorkboxError('max-entries-or-age-required', {
  199. moduleName: 'workbox-expiration',
  200. className: 'CacheExpiration',
  201. funcName: 'constructor'
  202. });
  203. }
  204. if (config.maxEntries) {
  205. assert_mjs.assert.isType(config.maxEntries, 'number', {
  206. moduleName: 'workbox-expiration',
  207. className: 'CacheExpiration',
  208. funcName: 'constructor',
  209. paramName: 'config.maxEntries'
  210. }); // TODO: Assert is positive
  211. }
  212. if (config.maxAgeSeconds) {
  213. assert_mjs.assert.isType(config.maxAgeSeconds, 'number', {
  214. moduleName: 'workbox-expiration',
  215. className: 'CacheExpiration',
  216. funcName: 'constructor',
  217. paramName: 'config.maxAgeSeconds'
  218. }); // TODO: Assert is positive
  219. }
  220. }
  221. this._isRunning = false;
  222. this._rerunRequested = false;
  223. this._maxEntries = config.maxEntries;
  224. this._maxAgeSeconds = config.maxAgeSeconds;
  225. this._cacheName = cacheName;
  226. this._timestampModel = new CacheTimestampsModel(cacheName);
  227. }
  228. /**
  229. * Expires entries for the given cache and given criteria.
  230. */
  231. async expireEntries() {
  232. if (this._isRunning) {
  233. this._rerunRequested = true;
  234. return;
  235. }
  236. this._isRunning = true;
  237. const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : undefined;
  238. const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); // Delete URLs from the cache
  239. const cache = await caches.open(this._cacheName);
  240. for (const url of urlsExpired) {
  241. await cache.delete(url);
  242. }
  243. {
  244. if (urlsExpired.length > 0) {
  245. logger_mjs.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
  246. logger_mjs.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
  247. urlsExpired.forEach(url => logger_mjs.logger.log(` ${url}`));
  248. logger_mjs.logger.groupEnd();
  249. } else {
  250. logger_mjs.logger.debug(`Cache expiration ran and found no entries to remove.`);
  251. }
  252. }
  253. this._isRunning = false;
  254. if (this._rerunRequested) {
  255. this._rerunRequested = false;
  256. this.expireEntries();
  257. }
  258. }
  259. /**
  260. * Update the timestamp for the given URL. This ensures the when
  261. * removing entries based on maximum entries, most recently used
  262. * is accurate or when expiring, the timestamp is up-to-date.
  263. *
  264. * @param {string} url
  265. */
  266. async updateTimestamp(url) {
  267. {
  268. assert_mjs.assert.isType(url, 'string', {
  269. moduleName: 'workbox-expiration',
  270. className: 'CacheExpiration',
  271. funcName: 'updateTimestamp',
  272. paramName: 'url'
  273. });
  274. }
  275. await this._timestampModel.setTimestamp(url, Date.now());
  276. }
  277. /**
  278. * Can be used to check if a URL has expired or not before it's used.
  279. *
  280. * This requires a look up from IndexedDB, so can be slow.
  281. *
  282. * Note: This method will not remove the cached entry, call
  283. * `expireEntries()` to remove indexedDB and Cache entries.
  284. *
  285. * @param {string} url
  286. * @return {boolean}
  287. */
  288. async isURLExpired(url) {
  289. {
  290. if (!this._maxAgeSeconds) {
  291. throw new WorkboxError_mjs.WorkboxError(`expired-test-without-max-age`, {
  292. methodName: 'isURLExpired',
  293. paramName: 'maxAgeSeconds'
  294. });
  295. }
  296. }
  297. const timestamp = await this._timestampModel.getTimestamp(url);
  298. const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
  299. return timestamp < expireOlderThan;
  300. }
  301. /**
  302. * Removes the IndexedDB object store used to keep track of cache expiration
  303. * metadata.
  304. */
  305. async delete() {
  306. // Make sure we don't attempt another rerun if we're called in the middle of
  307. // a cache expiration.
  308. this._rerunRequested = false;
  309. await this._timestampModel.expireEntries(Infinity); // Expires all.
  310. }
  311. }
  312. /*
  313. Copyright 2018 Google LLC
  314. Use of this source code is governed by an MIT-style
  315. license that can be found in the LICENSE file or at
  316. https://opensource.org/licenses/MIT.
  317. */
  318. /**
  319. * This plugin can be used in the Workbox APIs to regularly enforce a
  320. * limit on the age and / or the number of cached requests.
  321. *
  322. * Whenever a cached request is used or updated, this plugin will look
  323. * at the used Cache and remove any old or extra requests.
  324. *
  325. * When using `maxAgeSeconds`, requests may be used *once* after expiring
  326. * because the expiration clean up will not have occurred until *after* the
  327. * cached request has been used. If the request has a "Date" header, then
  328. * a light weight expiration check is performed and the request will not be
  329. * used immediately.
  330. *
  331. * When using `maxEntries`, the entry least-recently requested will be removed from the cache first.
  332. *
  333. * @memberof workbox.expiration
  334. */
  335. class Plugin {
  336. /**
  337. * @param {Object} config
  338. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  339. * Entries used the least will be removed as the maximum is reached.
  340. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  341. * it's treated as stale and removed.
  342. * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
  343. * automatic deletion if the available storage quota has been exceeded.
  344. */
  345. constructor(config = {}) {
  346. {
  347. if (!(config.maxEntries || config.maxAgeSeconds)) {
  348. throw new WorkboxError_mjs.WorkboxError('max-entries-or-age-required', {
  349. moduleName: 'workbox-expiration',
  350. className: 'Plugin',
  351. funcName: 'constructor'
  352. });
  353. }
  354. if (config.maxEntries) {
  355. assert_mjs.assert.isType(config.maxEntries, 'number', {
  356. moduleName: 'workbox-expiration',
  357. className: 'Plugin',
  358. funcName: 'constructor',
  359. paramName: 'config.maxEntries'
  360. });
  361. }
  362. if (config.maxAgeSeconds) {
  363. assert_mjs.assert.isType(config.maxAgeSeconds, 'number', {
  364. moduleName: 'workbox-expiration',
  365. className: 'Plugin',
  366. funcName: 'constructor',
  367. paramName: 'config.maxAgeSeconds'
  368. });
  369. }
  370. }
  371. this._config = config;
  372. this._maxAgeSeconds = config.maxAgeSeconds;
  373. this._cacheExpirations = new Map();
  374. if (config.purgeOnQuotaError) {
  375. registerQuotaErrorCallback_mjs.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
  376. }
  377. }
  378. /**
  379. * A simple helper method to return a CacheExpiration instance for a given
  380. * cache name.
  381. *
  382. * @param {string} cacheName
  383. * @return {CacheExpiration}
  384. *
  385. * @private
  386. */
  387. _getCacheExpiration(cacheName) {
  388. if (cacheName === cacheNames_mjs.cacheNames.getRuntimeName()) {
  389. throw new WorkboxError_mjs.WorkboxError('expire-custom-caches-only');
  390. }
  391. let cacheExpiration = this._cacheExpirations.get(cacheName);
  392. if (!cacheExpiration) {
  393. cacheExpiration = new CacheExpiration(cacheName, this._config);
  394. this._cacheExpirations.set(cacheName, cacheExpiration);
  395. }
  396. return cacheExpiration;
  397. }
  398. /**
  399. * A "lifecycle" callback that will be triggered automatically by the
  400. * `workbox.strategies` handlers when a `Response` is about to be returned
  401. * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
  402. * the handler. It allows the `Response` to be inspected for freshness and
  403. * prevents it from being used if the `Response`'s `Date` header value is
  404. * older than the configured `maxAgeSeconds`.
  405. *
  406. * @param {Object} options
  407. * @param {string} options.cacheName Name of the cache the response is in.
  408. * @param {Response} options.cachedResponse The `Response` object that's been
  409. * read from a cache and whose freshness should be checked.
  410. * @return {Response} Either the `cachedResponse`, if it's
  411. * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
  412. *
  413. * @private
  414. */
  415. cachedResponseWillBeUsed({
  416. event,
  417. request,
  418. cacheName,
  419. cachedResponse
  420. }) {
  421. if (!cachedResponse) {
  422. return null;
  423. }
  424. let isFresh = this._isResponseDateFresh(cachedResponse); // Expire entries to ensure that even if the expiration date has
  425. // expired, it'll only be used once.
  426. const cacheExpiration = this._getCacheExpiration(cacheName);
  427. cacheExpiration.expireEntries(); // Update the metadata for the request URL to the current timestamp,
  428. // but don't `await` it as we don't want to block the response.
  429. const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
  430. if (event) {
  431. try {
  432. event.waitUntil(updateTimestampDone);
  433. } catch (error) {
  434. {
  435. logger_mjs.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for '${getFriendlyURL_mjs.getFriendlyURL(event.request.url)}'.`);
  436. }
  437. }
  438. }
  439. return isFresh ? cachedResponse : null;
  440. }
  441. /**
  442. * @param {Response} cachedResponse
  443. * @return {boolean}
  444. *
  445. * @private
  446. */
  447. _isResponseDateFresh(cachedResponse) {
  448. if (!this._maxAgeSeconds) {
  449. // We aren't expiring by age, so return true, it's fresh
  450. return true;
  451. } // Check if the 'date' header will suffice a quick expiration check.
  452. // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
  453. // discussion.
  454. const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
  455. if (dateHeaderTimestamp === null) {
  456. // Unable to parse date, so assume it's fresh.
  457. return true;
  458. } // If we have a valid headerTime, then our response is fresh iff the
  459. // headerTime plus maxAgeSeconds is greater than the current time.
  460. const now = Date.now();
  461. return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
  462. }
  463. /**
  464. * This method will extract the data header and parse it into a useful
  465. * value.
  466. *
  467. * @param {Response} cachedResponse
  468. * @return {number}
  469. *
  470. * @private
  471. */
  472. _getDateHeaderTimestamp(cachedResponse) {
  473. if (!cachedResponse.headers.has('date')) {
  474. return null;
  475. }
  476. const dateHeader = cachedResponse.headers.get('date');
  477. const parsedDate = new Date(dateHeader);
  478. const headerTime = parsedDate.getTime(); // If the Date header was invalid for some reason, parsedDate.getTime()
  479. // will return NaN.
  480. if (isNaN(headerTime)) {
  481. return null;
  482. }
  483. return headerTime;
  484. }
  485. /**
  486. * A "lifecycle" callback that will be triggered automatically by the
  487. * `workbox.strategies` handlers when an entry is added to a cache.
  488. *
  489. * @param {Object} options
  490. * @param {string} options.cacheName Name of the cache that was updated.
  491. * @param {string} options.request The Request for the cached entry.
  492. *
  493. * @private
  494. */
  495. async cacheDidUpdate({
  496. cacheName,
  497. request
  498. }) {
  499. {
  500. assert_mjs.assert.isType(cacheName, 'string', {
  501. moduleName: 'workbox-expiration',
  502. className: 'Plugin',
  503. funcName: 'cacheDidUpdate',
  504. paramName: 'cacheName'
  505. });
  506. assert_mjs.assert.isInstance(request, Request, {
  507. moduleName: 'workbox-expiration',
  508. className: 'Plugin',
  509. funcName: 'cacheDidUpdate',
  510. paramName: 'request'
  511. });
  512. }
  513. const cacheExpiration = this._getCacheExpiration(cacheName);
  514. await cacheExpiration.updateTimestamp(request.url);
  515. await cacheExpiration.expireEntries();
  516. }
  517. /**
  518. * This is a helper method that performs two operations:
  519. *
  520. * - Deletes *all* the underlying Cache instances associated with this plugin
  521. * instance, by calling caches.delete() on your behalf.
  522. * - Deletes the metadata from IndexedDB used to keep track of expiration
  523. * details for each Cache instance.
  524. *
  525. * When using cache expiration, calling this method is preferable to calling
  526. * `caches.delete()` directly, since this will ensure that the IndexedDB
  527. * metadata is also cleanly removed and open IndexedDB instances are deleted.
  528. *
  529. * Note that if you're *not* using cache expiration for a given cache, calling
  530. * `caches.delete()` and passing in the cache's name should be sufficient.
  531. * There is no Workbox-specific method needed for cleanup in that case.
  532. */
  533. async deleteCacheAndMetadata() {
  534. // Do this one at a time instead of all at once via `Promise.all()` to
  535. // reduce the chance of inconsistency if a promise rejects.
  536. for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
  537. await caches.delete(cacheName);
  538. await cacheExpiration.delete();
  539. } // Reset this._cacheExpirations to its initial state.
  540. this._cacheExpirations = new Map();
  541. }
  542. }
  543. /*
  544. Copyright 2018 Google LLC
  545. Use of this source code is governed by an MIT-style
  546. license that can be found in the LICENSE file or at
  547. https://opensource.org/licenses/MIT.
  548. */
  549. exports.CacheExpiration = CacheExpiration;
  550. exports.Plugin = Plugin;
  551. return exports;
  552. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core));
  553. //# sourceMappingURL=workbox-expiration.dev.js.map