source: frontend/node_modules/workbox-broadcast-update/BroadcastCacheUpdate.js

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: 7.4 KB
Line 
1/*
2 Copyright 2018 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*/
8import { assert } from 'workbox-core/_private/assert.js';
9import { timeout } from 'workbox-core/_private/timeout.js';
10import { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';
11import { logger } from 'workbox-core/_private/logger.js';
12import { responsesAreSame } from './responsesAreSame.js';
13import { CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } from './utils/constants.js';
14import './_version.js';
15// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser
16// TODO(philipwalton): remove once this Safari bug fix has been released.
17// https://bugs.webkit.org/show_bug.cgi?id=201169
18const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
19/**
20 * Generates the default payload used in update messages. By default the
21 * payload includes the `cacheName` and `updatedURL` fields.
22 *
23 * @return Object
24 * @private
25 */
26function defaultPayloadGenerator(data) {
27 return {
28 cacheName: data.cacheName,
29 updatedURL: data.request.url,
30 };
31}
32/**
33 * Uses the `postMessage()` API to inform any open windows/tabs when a cached
34 * response has been updated.
35 *
36 * For efficiency's sake, the underlying response bodies are not compared;
37 * only specific response headers are checked.
38 *
39 * @memberof workbox-broadcast-update
40 */
41class BroadcastCacheUpdate {
42 /**
43 * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
44 * broadcast messages on
45 *
46 * @param {Object} [options]
47 * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]
48 * A list of headers that will be used to determine whether the responses
49 * differ.
50 * @param {string} [options.generatePayload] A function whose return value
51 * will be used as the `payload` field in any cache update messages sent
52 * to the window clients.
53 * @param {boolean} [options.notifyAllClients=true] If true (the default) then
54 * all open clients will receive a message. If false, then only the client
55 * that make the original request will be notified of the update.
56 */
57 constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {
58 this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
59 this._generatePayload = generatePayload || defaultPayloadGenerator;
60 this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;
61 }
62 /**
63 * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
64 * and sends a message (via `postMessage()`) to all window clients if the
65 * responses differ. Neither of the Responses can be
66 * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
67 *
68 * The message that's posted has the following format (where `payload` can
69 * be customized via the `generatePayload` option the instance is created
70 * with):
71 *
72 * ```
73 * {
74 * type: 'CACHE_UPDATED',
75 * meta: 'workbox-broadcast-update',
76 * payload: {
77 * cacheName: 'the-cache-name',
78 * updatedURL: 'https://example.com/'
79 * }
80 * }
81 * ```
82 *
83 * @param {Object} options
84 * @param {Response} [options.oldResponse] Cached response to compare.
85 * @param {Response} options.newResponse Possibly updated response to compare.
86 * @param {Request} options.request The request.
87 * @param {string} options.cacheName Name of the cache the responses belong
88 * to. This is included in the broadcast message.
89 * @param {Event} options.event event The event that triggered
90 * this possible cache update.
91 * @return {Promise} Resolves once the update is sent.
92 */
93 async notifyIfUpdated(options) {
94 if (process.env.NODE_ENV !== 'production') {
95 assert.isType(options.cacheName, 'string', {
96 moduleName: 'workbox-broadcast-update',
97 className: 'BroadcastCacheUpdate',
98 funcName: 'notifyIfUpdated',
99 paramName: 'cacheName',
100 });
101 assert.isInstance(options.newResponse, Response, {
102 moduleName: 'workbox-broadcast-update',
103 className: 'BroadcastCacheUpdate',
104 funcName: 'notifyIfUpdated',
105 paramName: 'newResponse',
106 });
107 assert.isInstance(options.request, Request, {
108 moduleName: 'workbox-broadcast-update',
109 className: 'BroadcastCacheUpdate',
110 funcName: 'notifyIfUpdated',
111 paramName: 'request',
112 });
113 }
114 // Without two responses there is nothing to compare.
115 if (!options.oldResponse) {
116 return;
117 }
118 if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
119 if (process.env.NODE_ENV !== 'production') {
120 logger.log(`Newer response found (and cached) for:`, options.request.url);
121 }
122 const messageData = {
123 type: CACHE_UPDATED_MESSAGE_TYPE,
124 meta: CACHE_UPDATED_MESSAGE_META,
125 payload: this._generatePayload(options),
126 };
127 // For navigation requests, wait until the new window client exists
128 // before sending the message
129 if (options.request.mode === 'navigate') {
130 let resultingClientId;
131 if (options.event instanceof FetchEvent) {
132 resultingClientId = options.event.resultingClientId;
133 }
134 const resultingWin = await resultingClientExists(resultingClientId);
135 // Safari does not currently implement postMessage buffering and
136 // there's no good way to feature detect that, so to increase the
137 // chances of the message being delivered in Safari, we add a timeout.
138 // We also do this if `resultingClientExists()` didn't return a client,
139 // which means it timed out, so it's worth waiting a bit longer.
140 if (!resultingWin || isSafari) {
141 // 3500 is chosen because (according to CrUX data) 80% of mobile
142 // websites hit the DOMContentLoaded event in less than 3.5 seconds.
143 // And presumably sites implementing service worker are on the
144 // higher end of the performance spectrum.
145 await timeout(3500);
146 }
147 }
148 if (this._notifyAllClients) {
149 const windows = await self.clients.matchAll({ type: 'window' });
150 for (const win of windows) {
151 win.postMessage(messageData);
152 }
153 }
154 else {
155 // See https://github.com/GoogleChrome/workbox/issues/2895
156 if (options.event instanceof FetchEvent) {
157 const client = await self.clients.get(options.event.clientId);
158 client === null || client === void 0 ? void 0 : client.postMessage(messageData);
159 }
160 }
161 }
162 }
163}
164export { BroadcastCacheUpdate };
Note: See TracBrowser for help on using the repository browser.