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