source: frontend/node_modules/workbox-precaching/src/PrecacheController.ts

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 12.0 KB
Line 
1/*
2 Copyright 2019 Google LLC
3
4 Use of this source code is governed by an MIT-style
5 license that can be found in the LICENSE file or at
6 https://opensource.org/licenses/MIT.
7*/
8
9import {assert} from 'workbox-core/_private/assert.js';
10import {cacheNames} from 'workbox-core/_private/cacheNames.js';
11import {logger} from 'workbox-core/_private/logger.js';
12import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
13import {waitUntil} from 'workbox-core/_private/waitUntil.js';
14import {Strategy} from 'workbox-strategies/Strategy.js';
15import {RouteHandlerCallback, WorkboxPlugin} from 'workbox-core/types.js';
16
17import {createCacheKey} from './utils/createCacheKey.js';
18import {PrecacheInstallReportPlugin} from './utils/PrecacheInstallReportPlugin.js';
19import {PrecacheCacheKeyPlugin} from './utils/PrecacheCacheKeyPlugin.js';
20import {printCleanupDetails} from './utils/printCleanupDetails.js';
21import {printInstallDetails} from './utils/printInstallDetails.js';
22import {PrecacheStrategy} from './PrecacheStrategy.js';
23import {PrecacheEntry, InstallResult, CleanupResult} from './_types.js';
24import './_version.js';
25
26// Give TypeScript the correct global.
27declare let self: ServiceWorkerGlobalScope;
28
29declare global {
30 interface ServiceWorkerGlobalScope {
31 __WB_MANIFEST: Array<PrecacheEntry | string>;
32 }
33}
34
35interface PrecacheControllerOptions {
36 cacheName?: string;
37 plugins?: WorkboxPlugin[];
38 fallbackToNetwork?: boolean;
39}
40
41/**
42 * Performs efficient precaching of assets.
43 *
44 * @memberof workbox-precaching
45 */
46class PrecacheController {
47 private _installAndActiveListenersAdded?: boolean;
48 private readonly _strategy: Strategy;
49 private readonly _urlsToCacheKeys: Map<string, string> = new Map();
50 private readonly _urlsToCacheModes: Map<
51 string,
52 | 'reload'
53 | 'default'
54 | 'no-store'
55 | 'no-cache'
56 | 'force-cache'
57 | 'only-if-cached'
58 > = new Map();
59 private readonly _cacheKeysToIntegrities: Map<string, string> = new Map();
60
61 /**
62 * Create a new PrecacheController.
63 *
64 * @param {Object} [options]
65 * @param {string} [options.cacheName] The cache to use for precaching.
66 * @param {string} [options.plugins] Plugins to use when precaching as well
67 * as responding to fetch events for precached assets.
68 * @param {boolean} [options.fallbackToNetwork=true] Whether to attempt to
69 * get the response from the network if there's a precache miss.
70 */
71 constructor({
72 cacheName,
73 plugins = [],
74 fallbackToNetwork = true,
75 }: PrecacheControllerOptions = {}) {
76 this._strategy = new PrecacheStrategy({
77 cacheName: cacheNames.getPrecacheName(cacheName),
78 plugins: [
79 ...plugins,
80 new PrecacheCacheKeyPlugin({precacheController: this}),
81 ],
82 fallbackToNetwork,
83 });
84
85 // Bind the install and activate methods to the instance.
86 this.install = this.install.bind(this);
87 this.activate = this.activate.bind(this);
88 }
89
90 /**
91 * @type {workbox-precaching.PrecacheStrategy} The strategy created by this controller and
92 * used to cache assets and respond to fetch events.
93 */
94 get strategy(): Strategy {
95 return this._strategy;
96 }
97
98 /**
99 * Adds items to the precache list, removing any duplicates and
100 * stores the files in the
101 * {@link workbox-core.cacheNames|"precache cache"} when the service
102 * worker installs.
103 *
104 * This method can be called multiple times.
105 *
106 * @param {Array<Object|string>} [entries=[]] Array of entries to precache.
107 */
108 precache(entries: Array<PrecacheEntry | string>): void {
109 this.addToCacheList(entries);
110
111 if (!this._installAndActiveListenersAdded) {
112 self.addEventListener('install', this.install);
113 self.addEventListener('activate', this.activate);
114 this._installAndActiveListenersAdded = true;
115 }
116 }
117
118 /**
119 * This method will add items to the precache list, removing duplicates
120 * and ensuring the information is valid.
121 *
122 * @param {Array<workbox-precaching.PrecacheController.PrecacheEntry|string>} entries
123 * Array of entries to precache.
124 */
125 addToCacheList(entries: Array<PrecacheEntry | string>): void {
126 if (process.env.NODE_ENV !== 'production') {
127 assert!.isArray(entries, {
128 moduleName: 'workbox-precaching',
129 className: 'PrecacheController',
130 funcName: 'addToCacheList',
131 paramName: 'entries',
132 });
133 }
134
135 const urlsToWarnAbout: string[] = [];
136 for (const entry of entries) {
137 // See https://github.com/GoogleChrome/workbox/issues/2259
138 if (typeof entry === 'string') {
139 urlsToWarnAbout.push(entry);
140 } else if (entry && entry.revision === undefined) {
141 urlsToWarnAbout.push(entry.url);
142 }
143
144 const {cacheKey, url} = createCacheKey(entry);
145 const cacheMode =
146 typeof entry !== 'string' && entry.revision ? 'reload' : 'default';
147
148 if (
149 this._urlsToCacheKeys.has(url) &&
150 this._urlsToCacheKeys.get(url) !== cacheKey
151 ) {
152 throw new WorkboxError('add-to-cache-list-conflicting-entries', {
153 firstEntry: this._urlsToCacheKeys.get(url),
154 secondEntry: cacheKey,
155 });
156 }
157
158 if (typeof entry !== 'string' && entry.integrity) {
159 if (
160 this._cacheKeysToIntegrities.has(cacheKey) &&
161 this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity
162 ) {
163 throw new WorkboxError('add-to-cache-list-conflicting-integrities', {
164 url,
165 });
166 }
167 this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
168 }
169
170 this._urlsToCacheKeys.set(url, cacheKey);
171 this._urlsToCacheModes.set(url, cacheMode);
172
173 if (urlsToWarnAbout.length > 0) {
174 const warningMessage =
175 `Workbox is precaching URLs without revision ` +
176 `info: ${urlsToWarnAbout.join(', ')}\nThis is generally NOT safe. ` +
177 `Learn more at https://bit.ly/wb-precache`;
178 if (process.env.NODE_ENV === 'production') {
179 // Use console directly to display this warning without bloating
180 // bundle sizes by pulling in all of the logger codebase in prod.
181 console.warn(warningMessage);
182 } else {
183 logger.warn(warningMessage);
184 }
185 }
186 }
187 }
188
189 /**
190 * Precaches new and updated assets. Call this method from the service worker
191 * install event.
192 *
193 * Note: this method calls `event.waitUntil()` for you, so you do not need
194 * to call it yourself in your event handlers.
195 *
196 * @param {ExtendableEvent} event
197 * @return {Promise<workbox-precaching.InstallResult>}
198 */
199 install(event: ExtendableEvent): Promise<InstallResult> {
200 // waitUntil returns Promise<any>
201 // eslint-disable-next-line @typescript-eslint/no-unsafe-return
202 return waitUntil(event, async () => {
203 const installReportPlugin = new PrecacheInstallReportPlugin();
204 this.strategy.plugins.push(installReportPlugin);
205
206 // Cache entries one at a time.
207 // See https://github.com/GoogleChrome/workbox/issues/2528
208 for (const [url, cacheKey] of this._urlsToCacheKeys) {
209 const integrity = this._cacheKeysToIntegrities.get(cacheKey);
210 const cacheMode = this._urlsToCacheModes.get(url);
211
212 const request = new Request(url, {
213 integrity,
214 cache: cacheMode,
215 credentials: 'same-origin',
216 });
217
218 await Promise.all(
219 this.strategy.handleAll({
220 params: {cacheKey},
221 request,
222 event,
223 }),
224 );
225 }
226
227 const {updatedURLs, notUpdatedURLs} = installReportPlugin;
228
229 if (process.env.NODE_ENV !== 'production') {
230 printInstallDetails(updatedURLs, notUpdatedURLs);
231 }
232
233 return {updatedURLs, notUpdatedURLs};
234 });
235 }
236
237 /**
238 * Deletes assets that are no longer present in the current precache manifest.
239 * Call this method from the service worker activate event.
240 *
241 * Note: this method calls `event.waitUntil()` for you, so you do not need
242 * to call it yourself in your event handlers.
243 *
244 * @param {ExtendableEvent} event
245 * @return {Promise<workbox-precaching.CleanupResult>}
246 */
247 activate(event: ExtendableEvent): Promise<CleanupResult> {
248 // waitUntil returns Promise<any>
249 // eslint-disable-next-line @typescript-eslint/no-unsafe-return
250 return waitUntil(event, async () => {
251 const cache = await self.caches.open(this.strategy.cacheName);
252 const currentlyCachedRequests = await cache.keys();
253 const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
254
255 const deletedURLs = [];
256 for (const request of currentlyCachedRequests) {
257 if (!expectedCacheKeys.has(request.url)) {
258 await cache.delete(request);
259 deletedURLs.push(request.url);
260 }
261 }
262
263 if (process.env.NODE_ENV !== 'production') {
264 printCleanupDetails(deletedURLs);
265 }
266
267 return {deletedURLs};
268 });
269 }
270
271 /**
272 * Returns a mapping of a precached URL to the corresponding cache key, taking
273 * into account the revision information for the URL.
274 *
275 * @return {Map<string, string>} A URL to cache key mapping.
276 */
277 getURLsToCacheKeys(): Map<string, string> {
278 return this._urlsToCacheKeys;
279 }
280
281 /**
282 * Returns a list of all the URLs that have been precached by the current
283 * service worker.
284 *
285 * @return {Array<string>} The precached URLs.
286 */
287 getCachedURLs(): Array<string> {
288 return [...this._urlsToCacheKeys.keys()];
289 }
290
291 /**
292 * Returns the cache key used for storing a given URL. If that URL is
293 * unversioned, like `/index.html', then the cache key will be the original
294 * URL with a search parameter appended to it.
295 *
296 * @param {string} url A URL whose cache key you want to look up.
297 * @return {string} The versioned URL that corresponds to a cache key
298 * for the original URL, or undefined if that URL isn't precached.
299 */
300 getCacheKeyForURL(url: string): string | undefined {
301 const urlObject = new URL(url, location.href);
302 return this._urlsToCacheKeys.get(urlObject.href);
303 }
304
305 /**
306 * @param {string} url A cache key whose SRI you want to look up.
307 * @return {string} The subresource integrity associated with the cache key,
308 * or undefined if it's not set.
309 */
310 getIntegrityForCacheKey(cacheKey: string): string | undefined {
311 return this._cacheKeysToIntegrities.get(cacheKey);
312 }
313
314 /**
315 * This acts as a drop-in replacement for
316 * [`cache.match()`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/match)
317 * with the following differences:
318 *
319 * - It knows what the name of the precache is, and only checks in that cache.
320 * - It allows you to pass in an "original" URL without versioning parameters,
321 * and it will automatically look up the correct cache key for the currently
322 * active revision of that URL.
323 *
324 * E.g., `matchPrecache('index.html')` will find the correct precached
325 * response for the currently active service worker, even if the actual cache
326 * key is `'/index.html?__WB_REVISION__=1234abcd'`.
327 *
328 * @param {string|Request} request The key (without revisioning parameters)
329 * to look up in the precache.
330 * @return {Promise<Response|undefined>}
331 */
332 async matchPrecache(
333 request: string | Request,
334 ): Promise<Response | undefined> {
335 const url = request instanceof Request ? request.url : request;
336 const cacheKey = this.getCacheKeyForURL(url);
337 if (cacheKey) {
338 const cache = await self.caches.open(this.strategy.cacheName);
339 return cache.match(cacheKey);
340 }
341 return undefined;
342 }
343
344 /**
345 * Returns a function that looks up `url` in the precache (taking into
346 * account revision information), and returns the corresponding `Response`.
347 *
348 * @param {string} url The precached URL which will be used to lookup the
349 * `Response`.
350 * @return {workbox-routing~handlerCallback}
351 */
352 createHandlerBoundToURL(url: string): RouteHandlerCallback {
353 const cacheKey = this.getCacheKeyForURL(url);
354 if (!cacheKey) {
355 throw new WorkboxError('non-precached-url', {url});
356 }
357 return (options) => {
358 options.request = new Request(url);
359 options.params = {cacheKey, ...options.params};
360
361 return this.strategy.handle(options);
362 };
363 }
364}
365
366export {PrecacheController};
Note: See TracBrowser for help on using the repository browser.