@serwist/window 8.0.0

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.
@@ -0,0 +1,693 @@
1
+ 'use strict';
2
+
3
+ var internal = require('@serwist/core/internal');
4
+
5
+ /*
6
+ Copyright 2019 Google LLC
7
+
8
+ Use of this source code is governed by an MIT-style
9
+ license that can be found in the LICENSE file or at
10
+ https://opensource.org/licenses/MIT.
11
+ */ /**
12
+ * Sends a data object to a service worker via `postMessage` and resolves with
13
+ * a response (if any).
14
+ *
15
+ * A response can be set in a message handler in the service worker by
16
+ * calling `event.ports[0].postMessage(...)`, which will resolve the promise
17
+ * returned by `messageSW()`. If no response is set, the promise will not
18
+ * resolve.
19
+ *
20
+ * @param sw The service worker to send the message to.
21
+ * @param data An object to send to the service worker.
22
+ * @returns
23
+ */ // Better not change type of data.
24
+ // eslint-disable-next-line @typescript-eslint/ban-types
25
+ function messageSW(sw, data) {
26
+ return new Promise((resolve)=>{
27
+ const messageChannel = new MessageChannel();
28
+ messageChannel.port1.onmessage = (event)=>{
29
+ resolve(event.data);
30
+ };
31
+ sw.postMessage(data, [
32
+ messageChannel.port2
33
+ ]);
34
+ });
35
+ }
36
+
37
+ /*
38
+ Copyright 2019 Google LLC
39
+
40
+ Use of this source code is governed by an MIT-style
41
+ license that can be found in the LICENSE file or at
42
+ https://opensource.org/licenses/MIT.
43
+ */ /**
44
+ * A minimal `Event` subclass shim.
45
+ * This doesn't *actually* subclass `Event` because not all browsers support
46
+ * constructable `EventTarget`, and using a real `Event` will error.
47
+ * @private
48
+ */ class SerwistEvent {
49
+ type;
50
+ target;
51
+ sw;
52
+ originalEvent;
53
+ isExternal;
54
+ constructor(type, props){
55
+ this.type = type;
56
+ Object.assign(this, props);
57
+ }
58
+ }
59
+
60
+ /*
61
+ Copyright 2019 Google LLC
62
+
63
+ Use of this source code is governed by an MIT-style
64
+ license that can be found in the LICENSE file or at
65
+ https://opensource.org/licenses/MIT.
66
+ */ /**
67
+ * A minimal `EventTarget` shim.
68
+ * This is necessary because not all browsers support constructable
69
+ * `EventTarget`, so using a real `EventTarget` will error.
70
+ * @private
71
+ */ class SerwistEventTarget {
72
+ _eventListenerRegistry = new Map();
73
+ /**
74
+ * @param type
75
+ * @param listener
76
+ * @private
77
+ */ addEventListener(type, listener) {
78
+ const foo = this._getEventListenersByType(type);
79
+ foo.add(listener);
80
+ }
81
+ /**
82
+ * @param type
83
+ * @param listener
84
+ * @private
85
+ */ removeEventListener(type, listener) {
86
+ this._getEventListenersByType(type).delete(listener);
87
+ }
88
+ /**
89
+ * @param event
90
+ * @private
91
+ */ dispatchEvent(event) {
92
+ event.target = this;
93
+ const listeners = this._getEventListenersByType(event.type);
94
+ for (const listener of listeners){
95
+ listener(event);
96
+ }
97
+ }
98
+ /**
99
+ * Returns a Set of listeners associated with the passed event type.
100
+ * If no handlers have been registered, an empty Set is returned.
101
+ *
102
+ * @param type The event type.
103
+ * @returns An array of handler functions.
104
+ * @private
105
+ */ _getEventListenersByType(type) {
106
+ if (!this._eventListenerRegistry.has(type)) {
107
+ this._eventListenerRegistry.set(type, new Set());
108
+ }
109
+ return this._eventListenerRegistry.get(type);
110
+ }
111
+ }
112
+
113
+ /*
114
+ Copyright 2019 Google LLC
115
+
116
+ Use of this source code is governed by an MIT-style
117
+ license that can be found in the LICENSE file or at
118
+ https://opensource.org/licenses/MIT.
119
+ */ /**
120
+ * Returns true if two URLs have the same `.href` property. The URLS can be
121
+ * relative, and if they are the current location href is used to resolve URLs.
122
+ *
123
+ * @private
124
+ * @param url1
125
+ * @param url2
126
+ * @returns
127
+ */ function urlsMatch(url1, url2) {
128
+ const { href } = location;
129
+ return new URL(url1, href).href === new URL(url2, href).href;
130
+ }
131
+
132
+ // The time a SW must be in the waiting phase before we can conclude
133
+ // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically
134
+ // chosen, but it seems to avoid false positives in my testing.
135
+ const WAITING_TIMEOUT_DURATION = 200;
136
+ // The amount of time after a registration that we can reasonably conclude
137
+ // that the registration didn't trigger an update.
138
+ const REGISTRATION_TIMEOUT_DURATION = 60000;
139
+ // The de facto standard message that a service worker should be listening for
140
+ // to trigger a call to skipWaiting().
141
+ const SKIP_WAITING_MESSAGE = {
142
+ type: "SKIP_WAITING"
143
+ };
144
+ /**
145
+ * A class to aid in handling service worker registration, updates, and
146
+ * reacting to service worker lifecycle events.
147
+ *
148
+ * @fires `@serwist/window.Serwist.message`
149
+ * @fires `@serwist/window.Serwist.installed`
150
+ * @fires `@serwist/window.Serwist.waiting`
151
+ * @fires `@serwist/window.Serwist.controlling`
152
+ * @fires `@serwist/window.Serwist.activated`
153
+ * @fires `@serwist/window.Serwist.redundant`
154
+ */ class Serwist extends SerwistEventTarget {
155
+ _scriptURL;
156
+ _registerOptions = {};
157
+ _updateFoundCount = 0;
158
+ // Deferreds we can resolve later.
159
+ _swDeferred = new internal.Deferred();
160
+ _activeDeferred = new internal.Deferred();
161
+ _controllingDeferred = new internal.Deferred();
162
+ _registrationTime = 0;
163
+ _isUpdate;
164
+ _compatibleControllingSW;
165
+ _registration;
166
+ _sw;
167
+ _ownSWs = new Set();
168
+ _externalSW;
169
+ _waitingTimeout;
170
+ /**
171
+ * Creates a new Serwist instance with a script URL and service worker
172
+ * options. The script URL and options are the same as those used when
173
+ * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
174
+ *
175
+ * @param scriptURL The service worker script
176
+ * associated with this instance. Using a
177
+ * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.
178
+ * @param registerOptions The service worker options associated
179
+ * with this instance.
180
+ */ // eslint-disable-next-line @typescript-eslint/ban-types
181
+ constructor(scriptURL, registerOptions = {}){
182
+ super();
183
+ this._scriptURL = scriptURL;
184
+ this._registerOptions = registerOptions;
185
+ // Add a message listener immediately since messages received during
186
+ // page load are buffered only until the DOMContentLoaded event:
187
+ // https://github.com/GoogleChrome/workbox/issues/2202
188
+ navigator.serviceWorker.addEventListener("message", this._onMessage);
189
+ }
190
+ /**
191
+ * Registers a service worker for this instances script URL and service
192
+ * worker options. By default this method delays registration until after
193
+ * the window has loaded.
194
+ *
195
+ * @param options
196
+ */ async register({ immediate = false } = {}) {
197
+ if (process.env.NODE_ENV !== "production") {
198
+ if (this._registrationTime) {
199
+ internal.logger.error("Cannot re-register a Serwist instance after it has " + "been registered. Create a new instance instead.");
200
+ return;
201
+ }
202
+ }
203
+ if (!immediate && document.readyState !== "complete") {
204
+ await new Promise((res)=>window.addEventListener("load", res));
205
+ }
206
+ // Set this flag to true if any service worker was controlling the page
207
+ // at registration time.
208
+ this._isUpdate = Boolean(navigator.serviceWorker.controller);
209
+ // Before registering, attempt to determine if a SW is already controlling
210
+ // the page, and if that SW script (and version, if specified) matches this
211
+ // instance's script.
212
+ this._compatibleControllingSW = this._getControllingSWIfCompatible();
213
+ this._registration = await this._registerScript();
214
+ // If we have a compatible controller, store the controller as the "own"
215
+ // SW, resolve active/controlling deferreds and add necessary listeners.
216
+ if (this._compatibleControllingSW) {
217
+ this._sw = this._compatibleControllingSW;
218
+ this._activeDeferred.resolve(this._compatibleControllingSW);
219
+ this._controllingDeferred.resolve(this._compatibleControllingSW);
220
+ this._compatibleControllingSW.addEventListener("statechange", this._onStateChange, {
221
+ once: true
222
+ });
223
+ }
224
+ // If there's a waiting service worker with a matching URL before the
225
+ // `updatefound` event fires, it likely means that this site is open
226
+ // in another tab, or the user refreshed the page (and thus the previous
227
+ // page wasn't fully unloaded before this page started loading).
228
+ // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
229
+ const waitingSW = this._registration.waiting;
230
+ if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {
231
+ // Store the waiting SW as the "own" Sw, even if it means overwriting
232
+ // a compatible controller.
233
+ this._sw = waitingSW;
234
+ // Run this in the next microtask, so any code that adds an event
235
+ // listener after awaiting `register()` will get this event.
236
+ internal.dontWaitFor(Promise.resolve().then(()=>{
237
+ this.dispatchEvent(new SerwistEvent("waiting", {
238
+ sw: waitingSW,
239
+ wasWaitingBeforeRegister: true
240
+ }));
241
+ if (process.env.NODE_ENV !== "production") {
242
+ internal.logger.warn("A service worker was already waiting to activate " + "before this script was registered...");
243
+ }
244
+ }));
245
+ }
246
+ // If an "own" SW is already set, resolve the deferred.
247
+ if (this._sw) {
248
+ this._swDeferred.resolve(this._sw);
249
+ this._ownSWs.add(this._sw);
250
+ }
251
+ if (process.env.NODE_ENV !== "production") {
252
+ internal.logger.log("Successfully registered service worker.", this._scriptURL.toString());
253
+ if (navigator.serviceWorker.controller) {
254
+ if (this._compatibleControllingSW) {
255
+ internal.logger.debug("A service worker with the same script URL " + "is already controlling this page.");
256
+ } else {
257
+ internal.logger.debug("A service worker with a different script URL is " + "currently controlling the page. The browser is now fetching " + "the new script now...");
258
+ }
259
+ }
260
+ const currentPageIsOutOfScope = ()=>{
261
+ const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);
262
+ const scopeURLBasePath = new URL("./", scopeURL.href).pathname;
263
+ return !location.pathname.startsWith(scopeURLBasePath);
264
+ };
265
+ if (currentPageIsOutOfScope()) {
266
+ internal.logger.warn("The current page is not in scope for the registered " + "service worker. Was this a mistake?");
267
+ }
268
+ }
269
+ this._registration.addEventListener("updatefound", this._onUpdateFound);
270
+ navigator.serviceWorker.addEventListener("controllerchange", this._onControllerChange);
271
+ return this._registration;
272
+ }
273
+ /**
274
+ * Checks for updates of the registered service worker.
275
+ */ async update() {
276
+ if (!this._registration) {
277
+ if (process.env.NODE_ENV !== "production") {
278
+ internal.logger.error("Cannot update a Serwist instance without " + "being registered. Register the Serwist instance first.");
279
+ }
280
+ return;
281
+ }
282
+ // Try to update registration
283
+ await this._registration.update();
284
+ }
285
+ /**
286
+ * Resolves to the service worker registered by this instance as soon as it
287
+ * is active. If a service worker was already controlling at registration
288
+ * time then it will resolve to that if the script URLs (and optionally
289
+ * script versions) match, otherwise it will wait until an update is found
290
+ * and activates.
291
+ *
292
+ * @returns
293
+ */ get active() {
294
+ return this._activeDeferred.promise;
295
+ }
296
+ /**
297
+ * Resolves to the service worker registered by this instance as soon as it
298
+ * is controlling the page. If a service worker was already controlling at
299
+ * registration time then it will resolve to that if the script URLs (and
300
+ * optionally script versions) match, otherwise it will wait until an update
301
+ * is found and starts controlling the page.
302
+ * Note: the first time a service worker is installed it will active but
303
+ * not start controlling the page unless `clients.claim()` is called in the
304
+ * service worker.
305
+ *
306
+ * @returns
307
+ */ get controlling() {
308
+ return this._controllingDeferred.promise;
309
+ }
310
+ /**
311
+ * Resolves with a reference to a service worker that matches the script URL
312
+ * of this instance, as soon as it's available.
313
+ *
314
+ * If, at registration time, there's already an active or waiting service
315
+ * worker with a matching script URL, it will be used (with the waiting
316
+ * service worker taking precedence over the active service worker if both
317
+ * match, since the waiting service worker would have been registered more
318
+ * recently).
319
+ * If there's no matching active or waiting service worker at registration
320
+ * time then the promise will not resolve until an update is found and starts
321
+ * installing, at which point the installing service worker is used.
322
+ *
323
+ * @returns
324
+ */ getSW() {
325
+ // If `this._sw` is set, resolve with that as we want `getSW()` to
326
+ // return the correct (new) service worker if an update is found.
327
+ return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise;
328
+ }
329
+ /**
330
+ * Sends the passed data object to the service worker registered by this
331
+ * instance (via `@serwist/window.Serwist.getSW`) and resolves
332
+ * with a response (if any).
333
+ *
334
+ * A response can be set in a message handler in the service worker by
335
+ * calling `event.ports[0].postMessage(...)`, which will resolve the promise
336
+ * returned by `messageSW()`. If no response is set, the promise will never
337
+ * resolve.
338
+ *
339
+ * @param data An object to send to the service worker
340
+ * @returns
341
+ */ // We might be able to change the 'data' type to Record<string, unknown> in the future.
342
+ // eslint-disable-next-line @typescript-eslint/ban-types
343
+ async messageSW(data) {
344
+ const sw = await this.getSW();
345
+ return messageSW(sw, data);
346
+ }
347
+ /**
348
+ * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's
349
+ * currently in the `waiting` state associated with the current registration.
350
+ *
351
+ * If there is no current registration or no service worker is `waiting`,
352
+ * calling this will have no effect.
353
+ */ messageSkipWaiting() {
354
+ if (this._registration && this._registration.waiting) {
355
+ void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);
356
+ }
357
+ }
358
+ /**
359
+ * Checks for a service worker already controlling the page and returns
360
+ * it if its script URL matches.
361
+ *
362
+ * @private
363
+ * @returns
364
+ */ _getControllingSWIfCompatible() {
365
+ const controller = navigator.serviceWorker.controller;
366
+ if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) {
367
+ return controller;
368
+ } else {
369
+ return undefined;
370
+ }
371
+ }
372
+ /**
373
+ * Registers a service worker for this instances script URL and register
374
+ * options and tracks the time registration was complete.
375
+ *
376
+ * @private
377
+ */ async _registerScript() {
378
+ try {
379
+ // this._scriptURL may be a TrustedScriptURL, but there's no support for
380
+ // passing that to register() in lib.dom right now.
381
+ // https://github.com/GoogleChrome/workbox/issues/2855
382
+ const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);
383
+ // Keep track of when registration happened, so it can be used in the
384
+ // `this._onUpdateFound` heuristic. Also use the presence of this
385
+ // property as a way to see if `.register()` has been called.
386
+ this._registrationTime = performance.now();
387
+ return reg;
388
+ } catch (error) {
389
+ if (process.env.NODE_ENV !== "production") {
390
+ internal.logger.error(error);
391
+ }
392
+ // Re-throw the error.
393
+ throw error;
394
+ }
395
+ }
396
+ /**
397
+ * @private
398
+ */ _onUpdateFound = ()=>{
399
+ // `this._registration` will never be `undefined` after an update is found.
400
+ const registration = this._registration;
401
+ const installingSW = registration.installing;
402
+ // If the script URL passed to `navigator.serviceWorker.register()` is
403
+ // different from the current controlling SW's script URL, we know any
404
+ // successful registration calls will trigger an `updatefound` event.
405
+ // But if the registered script URL is the same as the current controlling
406
+ // SW's script URL, we'll only get an `updatefound` event if the file
407
+ // changed since it was last registered. This can be a problem if the user
408
+ // opens up the same page in a different tab, and that page registers
409
+ // a SW that triggers an update. It's a problem because this page has no
410
+ // good way of knowing whether the `updatefound` event came from the SW
411
+ // script it registered or from a registration attempt made by a newer
412
+ // version of the page running in another tab.
413
+ // To minimize the possibility of a false positive, we use the logic here:
414
+ const updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't
415
+ // add the `updatefound` event listener until the `register()` call, if
416
+ // `_updateFoundCount` is > 0 then it means this method has already
417
+ // been called, thus this SW must be external
418
+ this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this
419
+ // instance's script URL, we know it's definitely not from our
420
+ // registration.
421
+ !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) || // If all of the above are false, then we use a time-based heuristic:
422
+ // Any `updatefound` event that occurs long after our registration is
423
+ // assumed to be external.
424
+ performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // triggered by this instance.
425
+ true : false;
426
+ if (updateLikelyTriggeredExternally) {
427
+ this._externalSW = installingSW;
428
+ registration.removeEventListener("updatefound", this._onUpdateFound);
429
+ } else {
430
+ // If the update was not triggered externally we know the installing
431
+ // SW is the one we registered, so we set it.
432
+ this._sw = installingSW;
433
+ this._ownSWs.add(installingSW);
434
+ this._swDeferred.resolve(installingSW);
435
+ // The `installing` state isn't something we have a dedicated
436
+ // callback for, but we do log messages for it in development.
437
+ if (process.env.NODE_ENV !== "production") {
438
+ if (navigator.serviceWorker.controller) {
439
+ internal.logger.log("Updated service worker found. Installing now...");
440
+ } else {
441
+ internal.logger.log("Service worker is installing...");
442
+ }
443
+ }
444
+ }
445
+ // Increment the `updatefound` count, so future invocations of this
446
+ // method can be sure they were triggered externally.
447
+ ++this._updateFoundCount;
448
+ // Add a `statechange` listener regardless of whether this update was
449
+ // triggered externally, since we have callbacks for both.
450
+ installingSW.addEventListener("statechange", this._onStateChange);
451
+ };
452
+ /**
453
+ * @private
454
+ * @param originalEvent
455
+ */ _onStateChange = (originalEvent)=>{
456
+ // `this._registration` will never be `undefined` after an update is found.
457
+ const registration = this._registration;
458
+ const sw = originalEvent.target;
459
+ const { state } = sw;
460
+ const isExternal = sw === this._externalSW;
461
+ const eventProps = {
462
+ sw,
463
+ isExternal,
464
+ originalEvent
465
+ };
466
+ if (!isExternal && this._isUpdate) {
467
+ eventProps.isUpdate = true;
468
+ }
469
+ this.dispatchEvent(new SerwistEvent(state, eventProps));
470
+ if (state === "installed") {
471
+ // This timeout is used to ignore cases where the service worker calls
472
+ // `skipWaiting()` in the install event, thus moving it directly in the
473
+ // activating state. (Since all service workers *must* go through the
474
+ // waiting phase, the only way to detect `skipWaiting()` called in the
475
+ // install event is to observe that the time spent in the waiting phase
476
+ // is very short.)
477
+ // NOTE: we don't need separate timeouts for the own and external SWs
478
+ // since they can't go through these phases at the same time.
479
+ this._waitingTimeout = self.setTimeout(()=>{
480
+ // Ensure the SW is still waiting (it may now be redundant).
481
+ if (state === "installed" && registration.waiting === sw) {
482
+ this.dispatchEvent(new SerwistEvent("waiting", eventProps));
483
+ if (process.env.NODE_ENV !== "production") {
484
+ if (isExternal) {
485
+ internal.logger.warn("An external service worker has installed but is " + "waiting for this client to close before activating...");
486
+ } else {
487
+ internal.logger.warn("The service worker has installed but is waiting " + "for existing clients to close before activating...");
488
+ }
489
+ }
490
+ }
491
+ }, WAITING_TIMEOUT_DURATION);
492
+ } else if (state === "activating") {
493
+ clearTimeout(this._waitingTimeout);
494
+ if (!isExternal) {
495
+ this._activeDeferred.resolve(sw);
496
+ }
497
+ }
498
+ if (process.env.NODE_ENV !== "production") {
499
+ switch(state){
500
+ case "installed":
501
+ if (isExternal) {
502
+ internal.logger.warn("An external service worker has installed. " + "You may want to suggest users reload this page.");
503
+ } else {
504
+ internal.logger.log("Registered service worker installed.");
505
+ }
506
+ break;
507
+ case "activated":
508
+ if (isExternal) {
509
+ internal.logger.warn("An external service worker has activated.");
510
+ } else {
511
+ internal.logger.log("Registered service worker activated.");
512
+ if (sw !== navigator.serviceWorker.controller) {
513
+ internal.logger.warn("The registered service worker is active but " + "not yet controlling the page. Reload or run " + "`clients.claim()` in the service worker.");
514
+ }
515
+ }
516
+ break;
517
+ case "redundant":
518
+ if (sw === this._compatibleControllingSW) {
519
+ internal.logger.log("Previously controlling service worker now redundant!");
520
+ } else if (!isExternal) {
521
+ internal.logger.log("Registered service worker now redundant!");
522
+ }
523
+ break;
524
+ }
525
+ }
526
+ };
527
+ /**
528
+ * @private
529
+ * @param originalEvent
530
+ */ _onControllerChange = (originalEvent)=>{
531
+ const sw = this._sw;
532
+ const isExternal = sw !== navigator.serviceWorker.controller;
533
+ // Unconditionally dispatch the controlling event, with isExternal set
534
+ // to distinguish between controller changes due to the initial registration
535
+ // vs. an update-check or other tab's registration.
536
+ // See https://github.com/GoogleChrome/workbox/issues/2786
537
+ this.dispatchEvent(new SerwistEvent("controlling", {
538
+ isExternal,
539
+ originalEvent,
540
+ sw,
541
+ isUpdate: this._isUpdate
542
+ }));
543
+ if (!isExternal) {
544
+ if (process.env.NODE_ENV !== "production") {
545
+ internal.logger.log("Registered service worker now controlling this page.");
546
+ }
547
+ this._controllingDeferred.resolve(sw);
548
+ }
549
+ };
550
+ /**
551
+ * @private
552
+ * @param originalEvent
553
+ */ _onMessage = async (originalEvent)=>{
554
+ // Can't change type 'any' of data.
555
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
556
+ const { data, ports, source } = originalEvent;
557
+ // Wait until there's an "own" service worker. This is used to buffer
558
+ // `message` events that may be received prior to calling `register()`.
559
+ await this.getSW();
560
+ // If the service worker that sent the message is in the list of own
561
+ // service workers for this instance, dispatch a `message` event.
562
+ // NOTE: we check for all previously owned service workers rather than
563
+ // just the current one because some messages (e.g. cache updates) use
564
+ // a timeout when sent and may be delayed long enough for a service worker
565
+ // update to be found.
566
+ if (this._ownSWs.has(source)) {
567
+ this.dispatchEvent(new SerwistEvent("message", {
568
+ // Can't change type 'any' of data.
569
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
570
+ data,
571
+ originalEvent,
572
+ ports,
573
+ sw: source
574
+ }));
575
+ }
576
+ };
577
+ } // The jsdoc comments below outline the events this instance may dispatch:
578
+ // -----------------------------------------------------------------------
579
+ /**
580
+ * The `message` event is dispatched any time a `postMessage` is received.
581
+ *
582
+ * @event workbox-window.Workbox#message
583
+ * @type {SerwistEvent}
584
+ * @property {*} data The `data` property from the original `message` event.
585
+ * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
586
+ * event.
587
+ * @property {string} type `message`.
588
+ * @property {MessagePort[]} ports The `ports` value from `originalEvent`.
589
+ * @property {Workbox} target The `Workbox` instance.
590
+ */ /**
591
+ * The `installed` event is dispatched if the state of a
592
+ * {@link workbox-window.Workbox} instance's
593
+ * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
594
+ * changes to `installed`.
595
+ *
596
+ * Then can happen either the very first time a service worker is installed,
597
+ * or after an update to the current service worker is found. In the case
598
+ * of an update being found, the event's `isUpdate` property will be `true`.
599
+ *
600
+ * @event workbox-window.Workbox#installed
601
+ * @type {SerwistEvent}
602
+ * @property {ServiceWorker} sw The service worker instance.
603
+ * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
604
+ * event.
605
+ * @property {boolean|undefined} isUpdate True if a service worker was already
606
+ * controlling when this `Workbox` instance called `register()`.
607
+ * @property {boolean|undefined} isExternal True if this event is associated
608
+ * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
609
+ * @property {string} type `installed`.
610
+ * @property {Workbox} target The `Workbox` instance.
611
+ */ /**
612
+ * The `waiting` event is dispatched if the state of a
613
+ * {@link workbox-window.Workbox} instance's
614
+ * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
615
+ * changes to `installed` and then doesn't immediately change to `activating`.
616
+ * It may also be dispatched if a service worker with the same
617
+ * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
618
+ * was already waiting when the {@link workbox-window.Workbox#register}
619
+ * method was called.
620
+ *
621
+ * @event workbox-window.Workbox#waiting
622
+ * @type {SerwistEvent}
623
+ * @property {ServiceWorker} sw The service worker instance.
624
+ * @property {Event|undefined} originalEvent The original
625
+ * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
626
+ * event, or `undefined` in the case where the service worker was waiting
627
+ * to before `.register()` was called.
628
+ * @property {boolean|undefined} isUpdate True if a service worker was already
629
+ * controlling when this `Workbox` instance called `register()`.
630
+ * @property {boolean|undefined} isExternal True if this event is associated
631
+ * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
632
+ * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with
633
+ * a matching `scriptURL` was already waiting when this `Workbox`
634
+ * instance called `register()`.
635
+ * @property {string} type `waiting`.
636
+ * @property {Workbox} target The `Workbox` instance.
637
+ */ /**
638
+ * The `controlling` event is dispatched if a
639
+ * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
640
+ * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}
641
+ * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
642
+ * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}
643
+ * matches the `scriptURL` of the `Workbox` instance's
644
+ * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.
645
+ *
646
+ * @event workbox-window.Workbox#controlling
647
+ * @type {SerwistEvent}
648
+ * @property {ServiceWorker} sw The service worker instance.
649
+ * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
650
+ * event.
651
+ * @property {boolean|undefined} isUpdate True if a service worker was already
652
+ * controlling when this service worker was registered.
653
+ * @property {boolean|undefined} isExternal True if this event is associated
654
+ * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
655
+ * @property {string} type `controlling`.
656
+ * @property {Workbox} target The `Workbox` instance.
657
+ */ /**
658
+ * The `activated` event is dispatched if the state of a
659
+ * {@link workbox-window.Workbox} instance's
660
+ * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
661
+ * changes to `activated`.
662
+ *
663
+ * @event workbox-window.Workbox#activated
664
+ * @type {SerwistEvent}
665
+ * @property {ServiceWorker} sw The service worker instance.
666
+ * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
667
+ * event.
668
+ * @property {boolean|undefined} isUpdate True if a service worker was already
669
+ * controlling when this `Workbox` instance called `register()`.
670
+ * @property {boolean|undefined} isExternal True if this event is associated
671
+ * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
672
+ * @property {string} type `activated`.
673
+ * @property {Workbox} target The `Workbox` instance.
674
+ */ /**
675
+ * The `redundant` event is dispatched if the state of a
676
+ * {@link workbox-window.Workbox} instance's
677
+ * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
678
+ * changes to `redundant`.
679
+ *
680
+ * @event workbox-window.Workbox#redundant
681
+ * @type {SerwistEvent}
682
+ * @property {ServiceWorker} sw The service worker instance.
683
+ * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
684
+ * event.
685
+ * @property {boolean|undefined} isUpdate True if a service worker was already
686
+ * controlling when this `Workbox` instance called `register()`.
687
+ * @property {string} type `redundant`.
688
+ * @property {Workbox} target The `Workbox` instance.
689
+ */
690
+
691
+ exports.Serwist = Serwist;
692
+ exports.SerwistEvent = SerwistEvent;
693
+ exports.messageSW = messageSW;