web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

649 lines
22 KiB

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