123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372 |
- import { assert } from 'workbox-core/_private/assert.js';
- import { cacheNames } from 'workbox-core/_private/cacheNames.js';
- import { cacheWrapper } from 'workbox-core/_private/cacheWrapper.js';
- import { fetchWrapper } from 'workbox-core/_private/fetchWrapper.js';
- import { logger } from 'workbox-core/_private/logger.js';
- import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
- import { copyResponse } from 'workbox-core/copyResponse.js';
- import { createCacheKey } from './utils/createCacheKey.js';
- import { printCleanupDetails } from './utils/printCleanupDetails.js';
- import { printInstallDetails } from './utils/printInstallDetails.js';
- import './_version.js';
- class PrecacheController {
-
- constructor(cacheName) {
- this._cacheName = cacheNames.getPrecacheName(cacheName);
- this._urlsToCacheKeys = new Map();
- this._urlsToCacheModes = new Map();
- this._cacheKeysToIntegrities = new Map();
- }
-
- addToCacheList(entries) {
- if (process.env.NODE_ENV !== 'production') {
- assert.isArray(entries, {
- moduleName: 'workbox-precaching',
- className: 'PrecacheController',
- funcName: 'addToCacheList',
- paramName: 'entries',
- });
- }
- const urlsToWarnAbout = [];
- for (const entry of entries) {
-
- if (typeof entry === 'string') {
- urlsToWarnAbout.push(entry);
- }
- else if (entry && entry.revision === undefined) {
- urlsToWarnAbout.push(entry.url);
- }
- const { cacheKey, url } = createCacheKey(entry);
- const cacheMode = (typeof entry !== 'string' && entry.revision) ?
- 'reload' : 'default';
- if (this._urlsToCacheKeys.has(url) &&
- this._urlsToCacheKeys.get(url) !== cacheKey) {
- throw new WorkboxError('add-to-cache-list-conflicting-entries', {
- firstEntry: this._urlsToCacheKeys.get(url),
- secondEntry: cacheKey,
- });
- }
- if (typeof entry !== 'string' && entry.integrity) {
- if (this._cacheKeysToIntegrities.has(cacheKey) &&
- this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
- throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
- url,
- });
- }
- this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
- }
- this._urlsToCacheKeys.set(url, cacheKey);
- this._urlsToCacheModes.set(url, cacheMode);
- if (urlsToWarnAbout.length > 0) {
- const warningMessage = `Workbox is precaching URLs without revision ` +
- `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` +
- `Learn more at https://bit.ly/wb-precache`;
- if (process.env.NODE_ENV === 'production') {
-
-
- console.warn(warningMessage);
- }
- else {
- logger.warn(warningMessage);
- }
- }
- }
- }
-
- async install({ event, plugins } = {}) {
- if (process.env.NODE_ENV !== 'production') {
- if (plugins) {
- assert.isArray(plugins, {
- moduleName: 'workbox-precaching',
- className: 'PrecacheController',
- funcName: 'install',
- paramName: 'plugins',
- });
- }
- }
- const toBePrecached = [];
- const alreadyPrecached = [];
- const cache = await self.caches.open(this._cacheName);
- const alreadyCachedRequests = await cache.keys();
- const existingCacheKeys = new Set(alreadyCachedRequests.map((request) => request.url));
- for (const [url, cacheKey] of this._urlsToCacheKeys) {
- if (existingCacheKeys.has(cacheKey)) {
- alreadyPrecached.push(url);
- }
- else {
- toBePrecached.push({ cacheKey, url });
- }
- }
- const precacheRequests = toBePrecached.map(({ cacheKey, url }) => {
- const integrity = this._cacheKeysToIntegrities.get(cacheKey);
- const cacheMode = this._urlsToCacheModes.get(url);
- return this._addURLToCache({
- cacheKey,
- cacheMode,
- event,
- integrity,
- plugins,
- url,
- });
- });
- await Promise.all(precacheRequests);
- const updatedURLs = toBePrecached.map((item) => item.url);
- if (process.env.NODE_ENV !== 'production') {
- printInstallDetails(updatedURLs, alreadyPrecached);
- }
- return {
- updatedURLs,
- notUpdatedURLs: alreadyPrecached,
- };
- }
-
- async activate() {
- const cache = await self.caches.open(this._cacheName);
- const currentlyCachedRequests = await cache.keys();
- const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
- const deletedURLs = [];
- for (const request of currentlyCachedRequests) {
- if (!expectedCacheKeys.has(request.url)) {
- await cache.delete(request);
- deletedURLs.push(request.url);
- }
- }
- if (process.env.NODE_ENV !== 'production') {
- printCleanupDetails(deletedURLs);
- }
- return { deletedURLs };
- }
-
- async _addURLToCache({ cacheKey, url, cacheMode, event, plugins, integrity }) {
- const request = new Request(url, {
- integrity,
- cache: cacheMode,
- credentials: 'same-origin',
- });
- let response = await fetchWrapper.fetch({
- event,
- plugins,
- request,
- });
-
-
-
- let cacheWillUpdatePlugin;
- for (const plugin of (plugins || [])) {
- if ('cacheWillUpdate' in plugin) {
- cacheWillUpdatePlugin = plugin;
- }
- }
- const isValidResponse = cacheWillUpdatePlugin ?
-
-
-
- await cacheWillUpdatePlugin.cacheWillUpdate({ event, request, response }) :
-
-
- response.status < 400;
-
-
- if (!isValidResponse) {
- throw new WorkboxError('bad-precaching-response', {
- url,
- status: response.status,
- });
- }
-
-
-
-
- if (response.redirected) {
- response = await copyResponse(response);
- }
- await cacheWrapper.put({
- event,
- plugins,
- response,
-
- request: cacheKey === url ? request : new Request(cacheKey),
- cacheName: this._cacheName,
- matchOptions: {
- ignoreSearch: true,
- },
- });
- }
-
- getURLsToCacheKeys() {
- return this._urlsToCacheKeys;
- }
-
- getCachedURLs() {
- return [...this._urlsToCacheKeys.keys()];
- }
-
- getCacheKeyForURL(url) {
- const urlObject = new URL(url, location.href);
- return this._urlsToCacheKeys.get(urlObject.href);
- }
-
- async matchPrecache(request) {
- const url = request instanceof Request ? request.url : request;
- const cacheKey = this.getCacheKeyForURL(url);
- if (cacheKey) {
- const cache = await self.caches.open(this._cacheName);
- return cache.match(cacheKey);
- }
- return undefined;
- }
-
- createHandler(fallbackToNetwork = true) {
- return async ({ request }) => {
- try {
- const response = await this.matchPrecache(request);
- if (response) {
- return response;
- }
-
-
- throw new WorkboxError('missing-precache-entry', {
- cacheName: this._cacheName,
- url: request instanceof Request ? request.url : request,
- });
- }
- catch (error) {
- if (fallbackToNetwork) {
- if (process.env.NODE_ENV !== 'production') {
- logger.debug(`Unable to respond with precached response. ` +
- `Falling back to network.`, error);
- }
- return fetch(request);
- }
- throw error;
- }
- };
- }
-
- createHandlerBoundToURL(url, fallbackToNetwork = true) {
- const cacheKey = this.getCacheKeyForURL(url);
- if (!cacheKey) {
- throw new WorkboxError('non-precached-url', { url });
- }
- const handler = this.createHandler(fallbackToNetwork);
- const request = new Request(url);
- return () => handler({ request });
- }
- }
- export { PrecacheController };
|