123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972 |
- this.workbox = this.workbox || {};
- this.workbox.expiration = (function (exports, assert_js, dontWaitFor_js, logger_js, WorkboxError_js, cacheNames_js, getFriendlyURL_js, registerQuotaErrorCallback_js) {
- 'use strict';
- function _extends() {
- _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
- let idbProxyableTypes;
- let cursorAdvanceMethods;
- function getIdbProxyableTypes() {
- return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
- }
- function getCursorAdvanceMethods() {
- return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
- }
- const cursorRequestMap = new WeakMap();
- const transactionDoneMap = new WeakMap();
- const transactionStoreNamesMap = new WeakMap();
- const transformCache = new WeakMap();
- const reverseTransformCache = new WeakMap();
- function promisifyRequest(request) {
- const promise = new Promise((resolve, reject) => {
- const unlisten = () => {
- request.removeEventListener('success', success);
- request.removeEventListener('error', error);
- };
- const success = () => {
- resolve(wrap(request.result));
- unlisten();
- };
- const error = () => {
- reject(request.error);
- unlisten();
- };
- request.addEventListener('success', success);
- request.addEventListener('error', error);
- });
- promise.then(value => {
-
-
- if (value instanceof IDBCursor) {
- cursorRequestMap.set(value, request);
- }
- }).catch(() => {});
-
- reverseTransformCache.set(promise, request);
- return promise;
- }
- function cacheDonePromiseForTransaction(tx) {
-
- if (transactionDoneMap.has(tx)) return;
- const done = new Promise((resolve, reject) => {
- const unlisten = () => {
- tx.removeEventListener('complete', complete);
- tx.removeEventListener('error', error);
- tx.removeEventListener('abort', error);
- };
- const complete = () => {
- resolve();
- unlisten();
- };
- const error = () => {
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
- unlisten();
- };
- tx.addEventListener('complete', complete);
- tx.addEventListener('error', error);
- tx.addEventListener('abort', error);
- });
- transactionDoneMap.set(tx, done);
- }
- let idbProxyTraps = {
- get(target, prop, receiver) {
- if (target instanceof IDBTransaction) {
-
- if (prop === 'done') return transactionDoneMap.get(target);
- if (prop === 'objectStoreNames') {
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
- }
- if (prop === 'store') {
- return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
- }
- }
- return wrap(target[prop]);
- },
- set(target, prop, value) {
- target[prop] = value;
- return true;
- },
- has(target, prop) {
- if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
- return true;
- }
- return prop in target;
- }
- };
- function replaceTraps(callback) {
- idbProxyTraps = callback(idbProxyTraps);
- }
- function wrapFunction(func) {
-
-
-
- if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) {
- return function (storeNames, ...args) {
- const tx = func.call(unwrap(this), storeNames, ...args);
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
- return wrap(tx);
- };
- }
-
-
-
-
- if (getCursorAdvanceMethods().includes(func)) {
- return function (...args) {
-
-
- func.apply(unwrap(this), args);
- return wrap(cursorRequestMap.get(this));
- };
- }
- return function (...args) {
-
-
- return wrap(func.apply(unwrap(this), args));
- };
- }
- function transformCachableValue(value) {
- if (typeof value === 'function') return wrapFunction(value);
-
- if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
- if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
- return value;
- }
- function wrap(value) {
-
-
- if (value instanceof IDBRequest) return promisifyRequest(value);
-
- if (transformCache.has(value)) return transformCache.get(value);
- const newValue = transformCachableValue(value);
-
- if (newValue !== value) {
- transformCache.set(value, newValue);
- reverseTransformCache.set(newValue, value);
- }
- return newValue;
- }
- const unwrap = value => reverseTransformCache.get(value);
-
- function openDB(name, version, {
- blocked,
- upgrade,
- blocking,
- terminated
- } = {}) {
- const request = indexedDB.open(name, version);
- const openPromise = wrap(request);
- if (upgrade) {
- request.addEventListener('upgradeneeded', event => {
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));
- });
- }
- if (blocked) request.addEventListener('blocked', () => blocked());
- openPromise.then(db => {
- if (terminated) db.addEventListener('close', () => terminated());
- if (blocking) db.addEventListener('versionchange', () => blocking());
- }).catch(() => {});
- return openPromise;
- }
-
- function deleteDB(name, {
- blocked
- } = {}) {
- const request = indexedDB.deleteDatabase(name);
- if (blocked) request.addEventListener('blocked', () => blocked());
- return wrap(request).then(() => undefined);
- }
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
- const writeMethods = ['put', 'add', 'delete', 'clear'];
- const cachedMethods = new Map();
- function getMethod(target, prop) {
- if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
- return;
- }
- if (cachedMethods.get(prop)) return cachedMethods.get(prop);
- const targetFuncName = prop.replace(/FromIndex$/, '');
- const useIndex = prop !== targetFuncName;
- const isWrite = writeMethods.includes(targetFuncName);
- if (
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
- return;
- }
- const method = async function (storeName, ...args) {
-
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
- let target = tx.store;
- if (useIndex) target = target.index(args.shift());
-
-
-
-
- return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
- };
- cachedMethods.set(prop, method);
- return method;
- }
- replaceTraps(oldTraps => _extends({}, oldTraps, {
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
- }));
- try {
- self['workbox:expiration:6.6.0'] && _();
- } catch (e) {}
-
- 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;
- }
- }
-
-
- class CacheExpiration {
-
- constructor(cacheName, config = {}) {
- this._isRunning = false;
- this._rerunRequested = false;
- {
- assert_js.assert.isType(cacheName, 'string', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'cacheName'
- });
- if (!(config.maxEntries || config.maxAgeSeconds)) {
- throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor'
- });
- }
- if (config.maxEntries) {
- assert_js.assert.isType(config.maxEntries, 'number', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'config.maxEntries'
- });
- }
- if (config.maxAgeSeconds) {
- assert_js.assert.isType(config.maxAgeSeconds, 'number', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'constructor',
- paramName: 'config.maxAgeSeconds'
- });
- }
- }
- this._maxEntries = config.maxEntries;
- this._maxAgeSeconds = config.maxAgeSeconds;
- this._matchOptions = config.matchOptions;
- this._cacheName = cacheName;
- this._timestampModel = new CacheTimestampsModel(cacheName);
- }
-
- async expireEntries() {
- if (this._isRunning) {
- this._rerunRequested = true;
- return;
- }
- this._isRunning = true;
- const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
- const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
- const cache = await self.caches.open(this._cacheName);
- for (const url of urlsExpired) {
- await cache.delete(url, this._matchOptions);
- }
- {
- if (urlsExpired.length > 0) {
- logger_js.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
- logger_js.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
- urlsExpired.forEach(url => logger_js.logger.log(` ${url}`));
- logger_js.logger.groupEnd();
- } else {
- logger_js.logger.debug(`Cache expiration ran and found no entries to remove.`);
- }
- }
- this._isRunning = false;
- if (this._rerunRequested) {
- this._rerunRequested = false;
- dontWaitFor_js.dontWaitFor(this.expireEntries());
- }
- }
-
- async updateTimestamp(url) {
- {
- assert_js.assert.isType(url, 'string', {
- moduleName: 'workbox-expiration',
- className: 'CacheExpiration',
- funcName: 'updateTimestamp',
- paramName: 'url'
- });
- }
- await this._timestampModel.setTimestamp(url, Date.now());
- }
-
- async isURLExpired(url) {
- if (!this._maxAgeSeconds) {
- {
- throw new WorkboxError_js.WorkboxError(`expired-test-without-max-age`, {
- methodName: 'isURLExpired',
- paramName: 'maxAgeSeconds'
- });
- }
- } else {
- const timestamp = await this._timestampModel.getTimestamp(url);
- const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
- return timestamp !== undefined ? timestamp < expireOlderThan : true;
- }
- }
-
- async delete() {
-
-
- this._rerunRequested = false;
- await this._timestampModel.expireEntries(Infinity);
- }
- }
-
-
- class ExpirationPlugin {
-
- constructor(config = {}) {
-
- this.cachedResponseWillBeUsed = async ({
- event,
- request,
- cacheName,
- cachedResponse
- }) => {
- if (!cachedResponse) {
- return null;
- }
- const isFresh = this._isResponseDateFresh(cachedResponse);
-
- const cacheExpiration = this._getCacheExpiration(cacheName);
- dontWaitFor_js.dontWaitFor(cacheExpiration.expireEntries());
-
- const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
- if (event) {
- try {
- event.waitUntil(updateTimestampDone);
- } catch (error) {
- {
-
- if ('request' in event) {
- logger_js.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL_js.getFriendlyURL(event.request.url)}'.`);
- }
- }
- }
- }
- return isFresh ? cachedResponse : null;
- };
-
- this.cacheDidUpdate = async ({
- cacheName,
- request
- }) => {
- {
- assert_js.assert.isType(cacheName, 'string', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'cacheDidUpdate',
- paramName: 'cacheName'
- });
- assert_js.assert.isInstance(request, Request, {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'cacheDidUpdate',
- paramName: 'request'
- });
- }
- const cacheExpiration = this._getCacheExpiration(cacheName);
- await cacheExpiration.updateTimestamp(request.url);
- await cacheExpiration.expireEntries();
- };
- {
- if (!(config.maxEntries || config.maxAgeSeconds)) {
- throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor'
- });
- }
- if (config.maxEntries) {
- assert_js.assert.isType(config.maxEntries, 'number', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor',
- paramName: 'config.maxEntries'
- });
- }
- if (config.maxAgeSeconds) {
- assert_js.assert.isType(config.maxAgeSeconds, 'number', {
- moduleName: 'workbox-expiration',
- className: 'Plugin',
- funcName: 'constructor',
- paramName: 'config.maxAgeSeconds'
- });
- }
- }
- this._config = config;
- this._maxAgeSeconds = config.maxAgeSeconds;
- this._cacheExpirations = new Map();
- if (config.purgeOnQuotaError) {
- registerQuotaErrorCallback_js.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
- }
- }
-
- _getCacheExpiration(cacheName) {
- if (cacheName === cacheNames_js.cacheNames.getRuntimeName()) {
- throw new WorkboxError_js.WorkboxError('expire-custom-caches-only');
- }
- let cacheExpiration = this._cacheExpirations.get(cacheName);
- if (!cacheExpiration) {
- cacheExpiration = new CacheExpiration(cacheName, this._config);
- this._cacheExpirations.set(cacheName, cacheExpiration);
- }
- return cacheExpiration;
- }
-
- _isResponseDateFresh(cachedResponse) {
- if (!this._maxAgeSeconds) {
-
- return true;
- }
-
-
- const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
- if (dateHeaderTimestamp === null) {
-
- return true;
- }
-
- const now = Date.now();
- return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
- }
-
- _getDateHeaderTimestamp(cachedResponse) {
- if (!cachedResponse.headers.has('date')) {
- return null;
- }
- const dateHeader = cachedResponse.headers.get('date');
- const parsedDate = new Date(dateHeader);
- const headerTime = parsedDate.getTime();
-
- if (isNaN(headerTime)) {
- return null;
- }
- return headerTime;
- }
-
- async deleteCacheAndMetadata() {
-
-
- for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
- await self.caches.delete(cacheName);
- await cacheExpiration.delete();
- }
- this._cacheExpirations = new Map();
- }
- }
- exports.CacheExpiration = CacheExpiration;
- exports.ExpirationPlugin = ExpirationPlugin;
- return exports;
- }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core));
|