@serwist/broadcast-update 9.0.0-preview.0 → 9.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +9 -97
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,14 +1,6 @@
1
1
  import { SerwistError, logger, assert, resultingClientExists, timeout, dontWaitFor } from '@serwist/core/internal';
2
2
 
3
- /**
4
- * Given two `Response's`, compares several header values to see if they are
5
- * the same or not.
6
- *
7
- * @param firstResponse
8
- * @param secondResponse
9
- * @param headersToCheck
10
- * @returns
11
- */ const responsesAreSame = (firstResponse, secondResponse, headersToCheck)=>{
3
+ const responsesAreSame = (firstResponse, secondResponse, headersToCheck)=>{
12
4
  if (process.env.NODE_ENV !== "production") {
13
5
  if (!(firstResponse instanceof Response && secondResponse instanceof Response)) {
14
6
  throw new SerwistError("invalid-responses-are-same-args");
@@ -22,8 +14,6 @@ import { SerwistError, logger, assert, resultingClientExists, timeout, dontWaitF
22
14
  logger.warn("Unable to determine where the response has been updated " + "because none of the headers that would be checked are present.");
23
15
  logger.debug("Attempting to compare the following: ", firstResponse, secondResponse, headersToCheck);
24
16
  }
25
- // Just return true, indicating the that responses are the same, since we
26
- // can't determine otherwise.
27
17
  return true;
28
18
  }
29
19
  return headersToCheck.every((header)=>{
@@ -33,13 +23,7 @@ import { SerwistError, logger, assert, resultingClientExists, timeout, dontWaitF
33
23
  });
34
24
  };
35
25
 
36
- /*
37
- Copyright 2018 Google LLC
38
-
39
- Use of this source code is governed by an MIT-style
40
- license that can be found in the LICENSE file or at
41
- https://opensource.org/licenses/MIT.
42
- */ const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
26
+ const CACHE_UPDATED_MESSAGE_TYPE = "CACHE_UPDATED";
43
27
  const CACHE_UPDATED_MESSAGE_META = "serwist-broadcast-update";
44
28
  const NOTIFY_ALL_CLIENTS = true;
45
29
  const DEFAULT_HEADERS_TO_CHECK = [
@@ -48,66 +32,23 @@ const DEFAULT_HEADERS_TO_CHECK = [
48
32
  "last-modified"
49
33
  ];
50
34
 
51
- // UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser
52
- // TODO(philipwalton): remove once this Safari bug fix has been released.
53
- // https://bugs.webkit.org/show_bug.cgi?id=201169
54
35
  const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
55
- /**
56
- * Generates the default payload used in update messages. By default the
57
- * payload includes the `cacheName` and `updatedURL` fields.
58
- *
59
- * @returns
60
- * @private
61
- */ function defaultPayloadGenerator(data) {
36
+ function defaultPayloadGenerator(data) {
62
37
  return {
63
38
  cacheName: data.cacheName,
64
39
  updatedURL: data.request.url
65
40
  };
66
41
  }
67
- /**
68
- * Uses the `postMessage()` API to inform any open windows/tabs when a cached
69
- * response has been updated.
70
- *
71
- * For efficiency's sake, the underlying response bodies are not compared;
72
- * only specific response headers are checked.
73
- */ class BroadcastCacheUpdate {
42
+ class BroadcastCacheUpdate {
74
43
  _headersToCheck;
75
44
  _generatePayload;
76
45
  _notifyAllClients;
77
- /**
78
- * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
79
- * broadcast messages on
80
- *
81
- * @param options
82
- */ constructor({ generatePayload, headersToCheck, notifyAllClients } = {}){
46
+ constructor({ generatePayload, headersToCheck, notifyAllClients } = {}){
83
47
  this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
84
48
  this._generatePayload = generatePayload || defaultPayloadGenerator;
85
49
  this._notifyAllClients = notifyAllClients ?? NOTIFY_ALL_CLIENTS;
86
50
  }
87
- /**
88
- * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
89
- * and sends a message (via `postMessage()`) to all window clients if the
90
- * responses differ. Neither of the Responses can be
91
- * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
92
- *
93
- * The message that's posted has the following format (where `payload` can
94
- * be customized via the `generatePayload` option the instance is created
95
- * with):
96
- *
97
- * ```
98
- * {
99
- * type: 'CACHE_UPDATED',
100
- * meta: 'workbox-broadcast-update',
101
- * payload: {
102
- * cacheName: 'the-cache-name',
103
- * updatedURL: 'https://example.com/'
104
- * }
105
- * }
106
- * ```
107
- *
108
- * @param options
109
- * @returns Resolves once the update is sent.
110
- */ async notifyIfUpdated(options) {
51
+ async notifyIfUpdated(options) {
111
52
  if (process.env.NODE_ENV !== "production") {
112
53
  assert.isType(options.cacheName, "string", {
113
54
  moduleName: "@serwist/broadcast-update",
@@ -128,7 +69,6 @@ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*saf
128
69
  paramName: "request"
129
70
  });
130
71
  }
131
- // Without two responses there is nothing to compare.
132
72
  if (!options.oldResponse) {
133
73
  return;
134
74
  }
@@ -141,24 +81,13 @@ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*saf
141
81
  meta: CACHE_UPDATED_MESSAGE_META,
142
82
  payload: this._generatePayload(options)
143
83
  };
144
- // For navigation requests, wait until the new window client exists
145
- // before sending the message
146
84
  if (options.request.mode === "navigate") {
147
85
  let resultingClientId;
148
86
  if (options.event instanceof FetchEvent) {
149
87
  resultingClientId = options.event.resultingClientId;
150
88
  }
151
89
  const resultingWin = await resultingClientExists(resultingClientId);
152
- // Safari does not currently implement postMessage buffering and
153
- // there's no good way to feature detect that, so to increase the
154
- // chances of the message being delivered in Safari, we add a timeout.
155
- // We also do this if `resultingClientExists()` didn't return a client,
156
- // which means it timed out, so it's worth waiting a bit longer.
157
90
  if (!resultingWin || isSafari) {
158
- // 3500 is chosen because (according to CrUX data) 80% of mobile
159
- // websites hit the DOMContentLoaded event in less than 3.5 seconds.
160
- // And presumably sites implementing service worker are on the
161
- // higher end of the performance spectrum.
162
91
  await timeout(3500);
163
92
  }
164
93
  }
@@ -170,7 +99,6 @@ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*saf
170
99
  win.postMessage(messageData);
171
100
  }
172
101
  } else {
173
- // See https://github.com/GoogleChrome/workbox/issues/2895
174
102
  if (options.event instanceof FetchEvent) {
175
103
  const client = await self.clients.get(options.event.clientId);
176
104
  client?.postMessage(messageData);
@@ -180,28 +108,12 @@ const isSafari = typeof navigator !== "undefined" && /^((?!chrome|android).)*saf
180
108
  }
181
109
  }
182
110
 
183
- /**
184
- * This plugin will automatically broadcast a message whenever a cached response
185
- * is updated.
186
- */ class BroadcastUpdatePlugin {
111
+ class BroadcastUpdatePlugin {
187
112
  _broadcastUpdate;
188
- /**
189
- * Construct a `@serwist/broadcast-update.BroadcastCacheUpdate` instance with
190
- * the passed options and calls its `notifyIfUpdated` method whenever the
191
- * plugin's `cacheDidUpdate` callback is invoked.
192
- *
193
- * @param options
194
- */ constructor(options){
113
+ constructor(options){
195
114
  this._broadcastUpdate = new BroadcastCacheUpdate(options);
196
115
  }
197
- /**
198
- * A "lifecycle" callback that will be triggered automatically by
199
- * `@serwist/build.RuntimeCaching` handlers when an entry is
200
- * added to a cache.
201
- *
202
- * @private
203
- * @param options The input object to this function.
204
- */ cacheDidUpdate = async (options)=>{
116
+ cacheDidUpdate = async (options)=>{
205
117
  dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));
206
118
  };
207
119
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/broadcast-update",
3
- "version": "9.0.0-preview.0",
3
+ "version": "9.0.0-preview.1",
4
4
  "type": "module",
5
5
  "description": "A service worker helper library that uses the Broadcast Channel API to announce when a cached response has updated",
6
6
  "files": [
@@ -29,12 +29,12 @@
29
29
  }
30
30
  },
31
31
  "dependencies": {
32
- "@serwist/core": "9.0.0-preview.0"
32
+ "@serwist/core": "9.0.0-preview.1"
33
33
  },
34
34
  "devDependencies": {
35
35
  "rollup": "4.9.6",
36
36
  "typescript": "5.4.0-dev.20240203",
37
- "@serwist/constants": "9.0.0-preview.0"
37
+ "@serwist/constants": "9.0.0-preview.1"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "typescript": ">=5.0.0"