workbox-broadcast-update.dev.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. this.workbox = this.workbox || {};
  2. this.workbox.broadcastUpdate = (function (exports, assert_js, timeout_js, resultingClientExists_js, logger_js, WorkboxError_js, dontWaitFor_js) {
  3. 'use strict';
  4. try {
  5. self['workbox:broadcast-update:6.6.0'] && _();
  6. } catch (e) {}
  7. /*
  8. Copyright 2018 Google LLC
  9. Use of this source code is governed by an MIT-style
  10. license that can be found in the LICENSE file or at
  11. https://opensource.org/licenses/MIT.
  12. */
  13. /**
  14. * Given two `Response's`, compares several header values to see if they are
  15. * the same or not.
  16. *
  17. * @param {Response} firstResponse
  18. * @param {Response} secondResponse
  19. * @param {Array<string>} headersToCheck
  20. * @return {boolean}
  21. *
  22. * @memberof workbox-broadcast-update
  23. */
  24. const responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {
  25. {
  26. if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {
  27. throw new WorkboxError_js.WorkboxError('invalid-responses-are-same-args');
  28. }
  29. }
  30. const atLeastOneHeaderAvailable = headersToCheck.some(header => {
  31. return firstResponse.headers.has(header) && secondResponse.headers.has(header);
  32. });
  33. if (!atLeastOneHeaderAvailable) {
  34. {
  35. logger_js.logger.warn(`Unable to determine where the response has been updated ` + `because none of the headers that would be checked are present.`);
  36. logger_js.logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);
  37. } // Just return true, indicating the that responses are the same, since we
  38. // can't determine otherwise.
  39. return true;
  40. }
  41. return headersToCheck.every(header => {
  42. const headerStateComparison = firstResponse.headers.has(header) === secondResponse.headers.has(header);
  43. const headerValueComparison = firstResponse.headers.get(header) === secondResponse.headers.get(header);
  44. return headerStateComparison && headerValueComparison;
  45. });
  46. };
  47. /*
  48. Copyright 2018 Google LLC
  49. Use of this source code is governed by an MIT-style
  50. license that can be found in the LICENSE file or at
  51. https://opensource.org/licenses/MIT.
  52. */
  53. const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';
  54. const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';
  55. const NOTIFY_ALL_CLIENTS = true;
  56. const DEFAULT_HEADERS_TO_CHECK = ['content-length', 'etag', 'last-modified'];
  57. /*
  58. Copyright 2018 Google LLC
  59. Use of this source code is governed by an MIT-style
  60. license that can be found in the LICENSE file or at
  61. https://opensource.org/licenses/MIT.
  62. */
  63. // TODO(philipwalton): remove once this Safari bug fix has been released.
  64. // https://bugs.webkit.org/show_bug.cgi?id=201169
  65. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  66. /**
  67. * Generates the default payload used in update messages. By default the
  68. * payload includes the `cacheName` and `updatedURL` fields.
  69. *
  70. * @return Object
  71. * @private
  72. */
  73. function defaultPayloadGenerator(data) {
  74. return {
  75. cacheName: data.cacheName,
  76. updatedURL: data.request.url
  77. };
  78. }
  79. /**
  80. * Uses the `postMessage()` API to inform any open windows/tabs when a cached
  81. * response has been updated.
  82. *
  83. * For efficiency's sake, the underlying response bodies are not compared;
  84. * only specific response headers are checked.
  85. *
  86. * @memberof workbox-broadcast-update
  87. */
  88. class BroadcastCacheUpdate {
  89. /**
  90. * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
  91. * broadcast messages on
  92. *
  93. * @param {Object} [options]
  94. * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]
  95. * A list of headers that will be used to determine whether the responses
  96. * differ.
  97. * @param {string} [options.generatePayload] A function whose return value
  98. * will be used as the `payload` field in any cache update messages sent
  99. * to the window clients.
  100. * @param {boolean} [options.notifyAllClients=true] If true (the default) then
  101. * all open clients will receive a message. If false, then only the client
  102. * that make the original request will be notified of the update.
  103. */
  104. constructor({
  105. generatePayload,
  106. headersToCheck,
  107. notifyAllClients
  108. } = {}) {
  109. this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
  110. this._generatePayload = generatePayload || defaultPayloadGenerator;
  111. this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;
  112. }
  113. /**
  114. * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  115. * and sends a message (via `postMessage()`) to all window clients if the
  116. * responses differ. Neither of the Responses can be
  117. * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
  118. *
  119. * The message that's posted has the following format (where `payload` can
  120. * be customized via the `generatePayload` option the instance is created
  121. * with):
  122. *
  123. * ```
  124. * {
  125. * type: 'CACHE_UPDATED',
  126. * meta: 'workbox-broadcast-update',
  127. * payload: {
  128. * cacheName: 'the-cache-name',
  129. * updatedURL: 'https://example.com/'
  130. * }
  131. * }
  132. * ```
  133. *
  134. * @param {Object} options
  135. * @param {Response} [options.oldResponse] Cached response to compare.
  136. * @param {Response} options.newResponse Possibly updated response to compare.
  137. * @param {Request} options.request The request.
  138. * @param {string} options.cacheName Name of the cache the responses belong
  139. * to. This is included in the broadcast message.
  140. * @param {Event} options.event event The event that triggered
  141. * this possible cache update.
  142. * @return {Promise} Resolves once the update is sent.
  143. */
  144. async notifyIfUpdated(options) {
  145. {
  146. assert_js.assert.isType(options.cacheName, 'string', {
  147. moduleName: 'workbox-broadcast-update',
  148. className: 'BroadcastCacheUpdate',
  149. funcName: 'notifyIfUpdated',
  150. paramName: 'cacheName'
  151. });
  152. assert_js.assert.isInstance(options.newResponse, Response, {
  153. moduleName: 'workbox-broadcast-update',
  154. className: 'BroadcastCacheUpdate',
  155. funcName: 'notifyIfUpdated',
  156. paramName: 'newResponse'
  157. });
  158. assert_js.assert.isInstance(options.request, Request, {
  159. moduleName: 'workbox-broadcast-update',
  160. className: 'BroadcastCacheUpdate',
  161. funcName: 'notifyIfUpdated',
  162. paramName: 'request'
  163. });
  164. } // Without two responses there is nothing to compare.
  165. if (!options.oldResponse) {
  166. return;
  167. }
  168. if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
  169. {
  170. logger_js.logger.log(`Newer response found (and cached) for:`, options.request.url);
  171. }
  172. const messageData = {
  173. type: CACHE_UPDATED_MESSAGE_TYPE,
  174. meta: CACHE_UPDATED_MESSAGE_META,
  175. payload: this._generatePayload(options)
  176. }; // For navigation requests, wait until the new window client exists
  177. // before sending the message
  178. if (options.request.mode === 'navigate') {
  179. let resultingClientId;
  180. if (options.event instanceof FetchEvent) {
  181. resultingClientId = options.event.resultingClientId;
  182. }
  183. const resultingWin = await resultingClientExists_js.resultingClientExists(resultingClientId); // Safari does not currently implement postMessage buffering and
  184. // there's no good way to feature detect that, so to increase the
  185. // chances of the message being delivered in Safari, we add a timeout.
  186. // We also do this if `resultingClientExists()` didn't return a client,
  187. // which means it timed out, so it's worth waiting a bit longer.
  188. if (!resultingWin || isSafari) {
  189. // 3500 is chosen because (according to CrUX data) 80% of mobile
  190. // websites hit the DOMContentLoaded event in less than 3.5 seconds.
  191. // And presumably sites implementing service worker are on the
  192. // higher end of the performance spectrum.
  193. await timeout_js.timeout(3500);
  194. }
  195. }
  196. if (this._notifyAllClients) {
  197. const windows = await self.clients.matchAll({
  198. type: 'window'
  199. });
  200. for (const win of windows) {
  201. win.postMessage(messageData);
  202. }
  203. } else {
  204. // See https://github.com/GoogleChrome/workbox/issues/2895
  205. if (options.event instanceof FetchEvent) {
  206. const client = await self.clients.get(options.event.clientId);
  207. client === null || client === void 0 ? void 0 : client.postMessage(messageData);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. /*
  214. Copyright 2018 Google LLC
  215. Use of this source code is governed by an MIT-style
  216. license that can be found in the LICENSE file or at
  217. https://opensource.org/licenses/MIT.
  218. */
  219. /**
  220. * This plugin will automatically broadcast a message whenever a cached response
  221. * is updated.
  222. *
  223. * @memberof workbox-broadcast-update
  224. */
  225. class BroadcastUpdatePlugin {
  226. /**
  227. * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with
  228. * the passed options and calls its `notifyIfUpdated` method whenever the
  229. * plugin's `cacheDidUpdate` callback is invoked.
  230. *
  231. * @param {Object} [options]
  232. * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]
  233. * A list of headers that will be used to determine whether the responses
  234. * differ.
  235. * @param {string} [options.generatePayload] A function whose return value
  236. * will be used as the `payload` field in any cache update messages sent
  237. * to the window clients.
  238. */
  239. constructor(options) {
  240. /**
  241. * A "lifecycle" callback that will be triggered automatically by the
  242. * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is
  243. * added to a cache.
  244. *
  245. * @private
  246. * @param {Object} options The input object to this function.
  247. * @param {string} options.cacheName Name of the cache being updated.
  248. * @param {Response} [options.oldResponse] The previous cached value, if any.
  249. * @param {Response} options.newResponse The new value in the cache.
  250. * @param {Request} options.request The request that triggered the update.
  251. * @param {Request} options.event The event that triggered the update.
  252. */
  253. this.cacheDidUpdate = async options => {
  254. dontWaitFor_js.dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));
  255. };
  256. this._broadcastUpdate = new BroadcastCacheUpdate(options);
  257. }
  258. }
  259. exports.BroadcastCacheUpdate = BroadcastCacheUpdate;
  260. exports.BroadcastUpdatePlugin = BroadcastUpdatePlugin;
  261. exports.responsesAreSame = responsesAreSame;
  262. return exports;
  263. }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
  264. //# sourceMappingURL=workbox-broadcast-update.dev.js.map