123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- import { openDB, deleteDB } from 'idb';
- import '../_version.js';
- const DB_NAME = 'workbox-expiration';
- const CACHE_OBJECT_STORE = 'cache-entries';
- const normalizeURL = (unNormalizedUrl) => {
- const url = new URL(unNormalizedUrl, location.href);
- url.hash = '';
- return url.href;
- };
- class CacheTimestampsModel {
-
- constructor(cacheName) {
- this._db = null;
- this._cacheName = cacheName;
- }
-
- _upgradeDb(db) {
-
-
-
-
- const objStore = db.createObjectStore(CACHE_OBJECT_STORE, { keyPath: 'id' });
-
-
-
- objStore.createIndex('cacheName', 'cacheName', { unique: false });
- objStore.createIndex('timestamp', 'timestamp', { unique: false });
- }
-
- _upgradeDbAndDeleteOldDbs(db) {
- this._upgradeDb(db);
- if (this._cacheName) {
- void deleteDB(this._cacheName);
- }
- }
-
- async setTimestamp(url, timestamp) {
- url = normalizeURL(url);
- const entry = {
- url,
- timestamp,
- cacheName: this._cacheName,
-
-
-
- id: this._getId(url),
- };
- const db = await this.getDb();
- const tx = db.transaction(CACHE_OBJECT_STORE, 'readwrite', {
- durability: 'relaxed',
- });
- await tx.store.put(entry);
- await tx.done;
- }
-
- async getTimestamp(url) {
- const db = await this.getDb();
- const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));
- return entry === null || entry === void 0 ? void 0 : entry.timestamp;
- }
-
- async expireEntries(minTimestamp, maxCount) {
- const db = await this.getDb();
- let cursor = await db
- .transaction(CACHE_OBJECT_STORE)
- .store.index('timestamp')
- .openCursor(null, 'prev');
- const entriesToDelete = [];
- let entriesNotDeletedCount = 0;
- while (cursor) {
- const result = cursor.value;
-
-
- if (result.cacheName === this._cacheName) {
-
-
- if ((minTimestamp && result.timestamp < minTimestamp) ||
- (maxCount && entriesNotDeletedCount >= maxCount)) {
-
-
-
-
-
-
-
-
- entriesToDelete.push(cursor.value);
- }
- else {
- entriesNotDeletedCount++;
- }
- }
- cursor = await cursor.continue();
- }
-
-
-
-
- const urlsDeleted = [];
- for (const entry of entriesToDelete) {
- await db.delete(CACHE_OBJECT_STORE, entry.id);
- urlsDeleted.push(entry.url);
- }
- return urlsDeleted;
- }
-
- _getId(url) {
-
-
-
- return this._cacheName + '|' + normalizeURL(url);
- }
-
- async getDb() {
- if (!this._db) {
- this._db = await openDB(DB_NAME, 1, {
- upgrade: this._upgradeDbAndDeleteOldDbs.bind(this),
- });
- }
- return this._db;
- }
- }
- export { CacheTimestampsModel };
|