UNPKG

34.2 kBJavaScriptView Raw
1/**
2 * @license Angular v10.2.3
3 * (c) 2010-2020 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7(function (global, factory) {
8 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/core'), require('rxjs'), require('rxjs/operators')) :
9 typeof define === 'function' && define.amd ? define('@angular/service-worker', ['exports', '@angular/common', '@angular/core', 'rxjs', 'rxjs/operators'], factory) :
10 (global = global || self, factory((global.ng = global.ng || {}, global.ng.serviceWorker = {}), global.ng.common, global.ng.core, global.rxjs, global.rxjs.operators));
11}(this, (function (exports, common, core, rxjs, operators) { 'use strict';
12
13 /*! *****************************************************************************
14 Copyright (c) Microsoft Corporation.
15
16 Permission to use, copy, modify, and/or distribute this software for any
17 purpose with or without fee is hereby granted.
18
19 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25 PERFORMANCE OF THIS SOFTWARE.
26 ***************************************************************************** */
27 /* global Reflect, Promise */
28 var extendStatics = function (d, b) {
29 extendStatics = Object.setPrototypeOf ||
30 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31 function (d, b) { for (var p in b)
32 if (b.hasOwnProperty(p))
33 d[p] = b[p]; };
34 return extendStatics(d, b);
35 };
36 function __extends(d, b) {
37 extendStatics(d, b);
38 function __() { this.constructor = d; }
39 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40 }
41 var __assign = function () {
42 __assign = Object.assign || function __assign(t) {
43 for (var s, i = 1, n = arguments.length; i < n; i++) {
44 s = arguments[i];
45 for (var p in s)
46 if (Object.prototype.hasOwnProperty.call(s, p))
47 t[p] = s[p];
48 }
49 return t;
50 };
51 return __assign.apply(this, arguments);
52 };
53 function __rest(s, e) {
54 var t = {};
55 for (var p in s)
56 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
57 t[p] = s[p];
58 if (s != null && typeof Object.getOwnPropertySymbols === "function")
59 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
60 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
61 t[p[i]] = s[p[i]];
62 }
63 return t;
64 }
65 function __decorate(decorators, target, key, desc) {
66 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
67 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
68 r = Reflect.decorate(decorators, target, key, desc);
69 else
70 for (var i = decorators.length - 1; i >= 0; i--)
71 if (d = decorators[i])
72 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
73 return c > 3 && r && Object.defineProperty(target, key, r), r;
74 }
75 function __param(paramIndex, decorator) {
76 return function (target, key) { decorator(target, key, paramIndex); };
77 }
78 function __metadata(metadataKey, metadataValue) {
79 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
80 return Reflect.metadata(metadataKey, metadataValue);
81 }
82 function __awaiter(thisArg, _arguments, P, generator) {
83 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
84 return new (P || (P = Promise))(function (resolve, reject) {
85 function fulfilled(value) { try {
86 step(generator.next(value));
87 }
88 catch (e) {
89 reject(e);
90 } }
91 function rejected(value) { try {
92 step(generator["throw"](value));
93 }
94 catch (e) {
95 reject(e);
96 } }
97 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
98 step((generator = generator.apply(thisArg, _arguments || [])).next());
99 });
100 }
101 function __generator(thisArg, body) {
102 var _ = { label: 0, sent: function () { if (t[0] & 1)
103 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
104 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
105 function verb(n) { return function (v) { return step([n, v]); }; }
106 function step(op) {
107 if (f)
108 throw new TypeError("Generator is already executing.");
109 while (_)
110 try {
111 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
112 return t;
113 if (y = 0, t)
114 op = [op[0] & 2, t.value];
115 switch (op[0]) {
116 case 0:
117 case 1:
118 t = op;
119 break;
120 case 4:
121 _.label++;
122 return { value: op[1], done: false };
123 case 5:
124 _.label++;
125 y = op[1];
126 op = [0];
127 continue;
128 case 7:
129 op = _.ops.pop();
130 _.trys.pop();
131 continue;
132 default:
133 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
134 _ = 0;
135 continue;
136 }
137 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
138 _.label = op[1];
139 break;
140 }
141 if (op[0] === 6 && _.label < t[1]) {
142 _.label = t[1];
143 t = op;
144 break;
145 }
146 if (t && _.label < t[2]) {
147 _.label = t[2];
148 _.ops.push(op);
149 break;
150 }
151 if (t[2])
152 _.ops.pop();
153 _.trys.pop();
154 continue;
155 }
156 op = body.call(thisArg, _);
157 }
158 catch (e) {
159 op = [6, e];
160 y = 0;
161 }
162 finally {
163 f = t = 0;
164 }
165 if (op[0] & 5)
166 throw op[1];
167 return { value: op[0] ? op[1] : void 0, done: true };
168 }
169 }
170 var __createBinding = Object.create ? (function (o, m, k, k2) {
171 if (k2 === undefined)
172 k2 = k;
173 Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
174 }) : (function (o, m, k, k2) {
175 if (k2 === undefined)
176 k2 = k;
177 o[k2] = m[k];
178 });
179 function __exportStar(m, exports) {
180 for (var p in m)
181 if (p !== "default" && !exports.hasOwnProperty(p))
182 __createBinding(exports, m, p);
183 }
184 function __values(o) {
185 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
186 if (m)
187 return m.call(o);
188 if (o && typeof o.length === "number")
189 return {
190 next: function () {
191 if (o && i >= o.length)
192 o = void 0;
193 return { value: o && o[i++], done: !o };
194 }
195 };
196 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
197 }
198 function __read(o, n) {
199 var m = typeof Symbol === "function" && o[Symbol.iterator];
200 if (!m)
201 return o;
202 var i = m.call(o), r, ar = [], e;
203 try {
204 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
205 ar.push(r.value);
206 }
207 catch (error) {
208 e = { error: error };
209 }
210 finally {
211 try {
212 if (r && !r.done && (m = i["return"]))
213 m.call(i);
214 }
215 finally {
216 if (e)
217 throw e.error;
218 }
219 }
220 return ar;
221 }
222 function __spread() {
223 for (var ar = [], i = 0; i < arguments.length; i++)
224 ar = ar.concat(__read(arguments[i]));
225 return ar;
226 }
227 function __spreadArrays() {
228 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
229 s += arguments[i].length;
230 for (var r = Array(s), k = 0, i = 0; i < il; i++)
231 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
232 r[k] = a[j];
233 return r;
234 }
235 ;
236 function __await(v) {
237 return this instanceof __await ? (this.v = v, this) : new __await(v);
238 }
239 function __asyncGenerator(thisArg, _arguments, generator) {
240 if (!Symbol.asyncIterator)
241 throw new TypeError("Symbol.asyncIterator is not defined.");
242 var g = generator.apply(thisArg, _arguments || []), i, q = [];
243 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
244 function verb(n) { if (g[n])
245 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
246 function resume(n, v) { try {
247 step(g[n](v));
248 }
249 catch (e) {
250 settle(q[0][3], e);
251 } }
252 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
253 function fulfill(value) { resume("next", value); }
254 function reject(value) { resume("throw", value); }
255 function settle(f, v) { if (f(v), q.shift(), q.length)
256 resume(q[0][0], q[0][1]); }
257 }
258 function __asyncDelegator(o) {
259 var i, p;
260 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
261 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
262 }
263 function __asyncValues(o) {
264 if (!Symbol.asyncIterator)
265 throw new TypeError("Symbol.asyncIterator is not defined.");
266 var m = o[Symbol.asyncIterator], i;
267 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
268 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
269 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
270 }
271 function __makeTemplateObject(cooked, raw) {
272 if (Object.defineProperty) {
273 Object.defineProperty(cooked, "raw", { value: raw });
274 }
275 else {
276 cooked.raw = raw;
277 }
278 return cooked;
279 }
280 ;
281 var __setModuleDefault = Object.create ? (function (o, v) {
282 Object.defineProperty(o, "default", { enumerable: true, value: v });
283 }) : function (o, v) {
284 o["default"] = v;
285 };
286 function __importStar(mod) {
287 if (mod && mod.__esModule)
288 return mod;
289 var result = {};
290 if (mod != null)
291 for (var k in mod)
292 if (Object.hasOwnProperty.call(mod, k))
293 __createBinding(result, mod, k);
294 __setModuleDefault(result, mod);
295 return result;
296 }
297 function __importDefault(mod) {
298 return (mod && mod.__esModule) ? mod : { default: mod };
299 }
300 function __classPrivateFieldGet(receiver, privateMap) {
301 if (!privateMap.has(receiver)) {
302 throw new TypeError("attempted to get private field on non-instance");
303 }
304 return privateMap.get(receiver);
305 }
306 function __classPrivateFieldSet(receiver, privateMap, value) {
307 if (!privateMap.has(receiver)) {
308 throw new TypeError("attempted to set private field on non-instance");
309 }
310 privateMap.set(receiver, value);
311 return value;
312 }
313
314 /**
315 * @license
316 * Copyright Google LLC All Rights Reserved.
317 *
318 * Use of this source code is governed by an MIT-style license that can be
319 * found in the LICENSE file at https://angular.io/license
320 */
321 var ERR_SW_NOT_SUPPORTED = 'Service workers are disabled or not supported by this browser';
322 function errorObservable(message) {
323 return rxjs.defer(function () { return rxjs.throwError(new Error(message)); });
324 }
325 /**
326 * @publicApi
327 */
328 var NgswCommChannel = /** @class */ (function () {
329 function NgswCommChannel(serviceWorker) {
330 this.serviceWorker = serviceWorker;
331 if (!serviceWorker) {
332 this.worker = this.events = this.registration = errorObservable(ERR_SW_NOT_SUPPORTED);
333 }
334 else {
335 var controllerChangeEvents = rxjs.fromEvent(serviceWorker, 'controllerchange');
336 var controllerChanges = controllerChangeEvents.pipe(operators.map(function () { return serviceWorker.controller; }));
337 var currentController = rxjs.defer(function () { return rxjs.of(serviceWorker.controller); });
338 var controllerWithChanges = rxjs.concat(currentController, controllerChanges);
339 this.worker = controllerWithChanges.pipe(operators.filter(function (c) { return !!c; }));
340 this.registration = (this.worker.pipe(operators.switchMap(function () { return serviceWorker.getRegistration(); })));
341 var rawEvents = rxjs.fromEvent(serviceWorker, 'message');
342 var rawEventPayload = rawEvents.pipe(operators.map(function (event) { return event.data; }));
343 var eventsUnconnected = rawEventPayload.pipe(operators.filter(function (event) { return event && event.type; }));
344 var events = eventsUnconnected.pipe(operators.publish());
345 events.connect();
346 this.events = events;
347 }
348 }
349 NgswCommChannel.prototype.postMessage = function (action, payload) {
350 return this.worker
351 .pipe(operators.take(1), operators.tap(function (sw) {
352 sw.postMessage(Object.assign({ action: action }, payload));
353 }))
354 .toPromise()
355 .then(function () { return undefined; });
356 };
357 NgswCommChannel.prototype.postMessageWithStatus = function (type, payload, nonce) {
358 var waitForStatus = this.waitForStatus(nonce);
359 var postMessage = this.postMessage(type, payload);
360 return Promise.all([waitForStatus, postMessage]).then(function () { return undefined; });
361 };
362 NgswCommChannel.prototype.generateNonce = function () {
363 return Math.round(Math.random() * 10000000);
364 };
365 NgswCommChannel.prototype.eventsOfType = function (type) {
366 var filterFn = function (event) { return event.type === type; };
367 return this.events.pipe(operators.filter(filterFn));
368 };
369 NgswCommChannel.prototype.nextEventOfType = function (type) {
370 return this.eventsOfType(type).pipe(operators.take(1));
371 };
372 NgswCommChannel.prototype.waitForStatus = function (nonce) {
373 return this.eventsOfType('STATUS')
374 .pipe(operators.filter(function (event) { return event.nonce === nonce; }), operators.take(1), operators.map(function (event) {
375 if (event.status) {
376 return undefined;
377 }
378 throw new Error(event.error);
379 }))
380 .toPromise();
381 };
382 Object.defineProperty(NgswCommChannel.prototype, "isEnabled", {
383 get: function () {
384 return !!this.serviceWorker;
385 },
386 enumerable: false,
387 configurable: true
388 });
389 return NgswCommChannel;
390 }());
391
392 /**
393 * @license
394 * Copyright Google LLC All Rights Reserved.
395 *
396 * Use of this source code is governed by an MIT-style license that can be
397 * found in the LICENSE file at https://angular.io/license
398 */
399 /**
400 * Subscribe and listen to
401 * [Web Push
402 * Notifications](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) through
403 * Angular Service Worker.
404 *
405 * @usageNotes
406 *
407 * You can inject a `SwPush` instance into any component or service
408 * as a dependency.
409 *
410 * <code-example path="service-worker/push/module.ts" region="inject-sw-push"
411 * header="app.component.ts"></code-example>
412 *
413 * To subscribe, call `SwPush.requestSubscription()`, which asks the user for permission.
414 * The call returns a `Promise` with a new
415 * [`PushSubscription`](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription)
416 * instance.
417 *
418 * <code-example path="service-worker/push/module.ts" region="subscribe-to-push"
419 * header="app.component.ts"></code-example>
420 *
421 * A request is rejected if the user denies permission, or if the browser
422 * blocks or does not support the Push API or ServiceWorkers.
423 * Check `SwPush.isEnabled` to confirm status.
424 *
425 * Invoke Push Notifications by pushing a message with the following payload.
426 *
427 * ```ts
428 * {
429 * "notification": {
430 * "actions": NotificationAction[],
431 * "badge": USVString
432 * "body": DOMString,
433 * "data": any,
434 * "dir": "auto"|"ltr"|"rtl",
435 * "icon": USVString,
436 * "image": USVString,
437 * "lang": DOMString,
438 * "renotify": boolean,
439 * "requireInteraction": boolean,
440 * "silent": boolean,
441 * "tag": DOMString,
442 * "timestamp": DOMTimeStamp,
443 * "title": DOMString,
444 * "vibrate": number[]
445 * }
446 * }
447 * ```
448 *
449 * Only `title` is required. See `Notification`
450 * [instance
451 * properties](https://developer.mozilla.org/en-US/docs/Web/API/Notification#Instance_properties).
452 *
453 * While the subscription is active, Service Worker listens for
454 * [PushEvent](https://developer.mozilla.org/en-US/docs/Web/API/PushEvent)
455 * occurrences and creates
456 * [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification)
457 * instances in response.
458 *
459 * Unsubscribe using `SwPush.unsubscribe()`.
460 *
461 * An application can subscribe to `SwPush.notificationClicks` observable to be notified when a user
462 * clicks on a notification. For example:
463 *
464 * <code-example path="service-worker/push/module.ts" region="subscribe-to-notification-clicks"
465 * header="app.component.ts"></code-example>
466 *
467 * @see [Push Notifications](https://developers.google.com/web/fundamentals/codelabs/push-notifications/)
468 * @see [Angular Push Notifications](https://blog.angular-university.io/angular-push-notifications/)
469 * @see [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
470 * @see [MDN: Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API)
471 * @see [MDN: Web Push API Notifications best practices](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices)
472 *
473 * @publicApi
474 */
475 var SwPush = /** @class */ (function () {
476 function SwPush(sw) {
477 this.sw = sw;
478 this.subscriptionChanges = new rxjs.Subject();
479 if (!sw.isEnabled) {
480 this.messages = rxjs.NEVER;
481 this.notificationClicks = rxjs.NEVER;
482 this.subscription = rxjs.NEVER;
483 return;
484 }
485 this.messages = this.sw.eventsOfType('PUSH').pipe(operators.map(function (message) { return message.data; }));
486 this.notificationClicks =
487 this.sw.eventsOfType('NOTIFICATION_CLICK').pipe(operators.map(function (message) { return message.data; }));
488 this.pushManager = this.sw.registration.pipe(operators.map(function (registration) { return registration.pushManager; }));
489 var workerDrivenSubscriptions = this.pushManager.pipe(operators.switchMap(function (pm) { return pm.getSubscription(); }));
490 this.subscription = rxjs.merge(workerDrivenSubscriptions, this.subscriptionChanges);
491 }
492 Object.defineProperty(SwPush.prototype, "isEnabled", {
493 /**
494 * True if the Service Worker is enabled (supported by the browser and enabled via
495 * `ServiceWorkerModule`).
496 */
497 get: function () {
498 return this.sw.isEnabled;
499 },
500 enumerable: false,
501 configurable: true
502 });
503 /**
504 * Subscribes to Web Push Notifications,
505 * after requesting and receiving user permission.
506 *
507 * @param options An object containing the `serverPublicKey` string.
508 * @returns A Promise that resolves to the new subscription object.
509 */
510 SwPush.prototype.requestSubscription = function (options) {
511 var _this = this;
512 if (!this.sw.isEnabled) {
513 return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
514 }
515 var pushOptions = { userVisibleOnly: true };
516 var key = this.decodeBase64(options.serverPublicKey.replace(/_/g, '/').replace(/-/g, '+'));
517 var applicationServerKey = new Uint8Array(new ArrayBuffer(key.length));
518 for (var i = 0; i < key.length; i++) {
519 applicationServerKey[i] = key.charCodeAt(i);
520 }
521 pushOptions.applicationServerKey = applicationServerKey;
522 return this.pushManager.pipe(operators.switchMap(function (pm) { return pm.subscribe(pushOptions); }), operators.take(1))
523 .toPromise()
524 .then(function (sub) {
525 _this.subscriptionChanges.next(sub);
526 return sub;
527 });
528 };
529 /**
530 * Unsubscribes from Service Worker push notifications.
531 *
532 * @returns A Promise that is resolved when the operation succeeds, or is rejected if there is no
533 * active subscription or the unsubscribe operation fails.
534 */
535 SwPush.prototype.unsubscribe = function () {
536 var _this = this;
537 if (!this.sw.isEnabled) {
538 return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
539 }
540 var doUnsubscribe = function (sub) {
541 if (sub === null) {
542 throw new Error('Not subscribed to push notifications.');
543 }
544 return sub.unsubscribe().then(function (success) {
545 if (!success) {
546 throw new Error('Unsubscribe failed!');
547 }
548 _this.subscriptionChanges.next(null);
549 });
550 };
551 return this.subscription.pipe(operators.take(1), operators.switchMap(doUnsubscribe)).toPromise();
552 };
553 SwPush.prototype.decodeBase64 = function (input) {
554 return atob(input);
555 };
556 return SwPush;
557 }());
558 SwPush.decorators = [
559 { type: core.Injectable }
560 ];
561 SwPush.ctorParameters = function () { return [
562 { type: NgswCommChannel }
563 ]; };
564
565 /**
566 * @license
567 * Copyright Google LLC All Rights Reserved.
568 *
569 * Use of this source code is governed by an MIT-style license that can be
570 * found in the LICENSE file at https://angular.io/license
571 */
572 /**
573 * Subscribe to update notifications from the Service Worker, trigger update
574 * checks, and forcibly activate updates.
575 *
576 * @publicApi
577 */
578 var SwUpdate = /** @class */ (function () {
579 function SwUpdate(sw) {
580 this.sw = sw;
581 if (!sw.isEnabled) {
582 this.available = rxjs.NEVER;
583 this.activated = rxjs.NEVER;
584 return;
585 }
586 this.available = this.sw.eventsOfType('UPDATE_AVAILABLE');
587 this.activated = this.sw.eventsOfType('UPDATE_ACTIVATED');
588 }
589 Object.defineProperty(SwUpdate.prototype, "isEnabled", {
590 /**
591 * True if the Service Worker is enabled (supported by the browser and enabled via
592 * `ServiceWorkerModule`).
593 */
594 get: function () {
595 return this.sw.isEnabled;
596 },
597 enumerable: false,
598 configurable: true
599 });
600 SwUpdate.prototype.checkForUpdate = function () {
601 if (!this.sw.isEnabled) {
602 return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
603 }
604 var statusNonce = this.sw.generateNonce();
605 return this.sw.postMessageWithStatus('CHECK_FOR_UPDATES', { statusNonce: statusNonce }, statusNonce);
606 };
607 SwUpdate.prototype.activateUpdate = function () {
608 if (!this.sw.isEnabled) {
609 return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
610 }
611 var statusNonce = this.sw.generateNonce();
612 return this.sw.postMessageWithStatus('ACTIVATE_UPDATE', { statusNonce: statusNonce }, statusNonce);
613 };
614 return SwUpdate;
615 }());
616 SwUpdate.decorators = [
617 { type: core.Injectable }
618 ];
619 SwUpdate.ctorParameters = function () { return [
620 { type: NgswCommChannel }
621 ]; };
622
623 /**
624 * Token that can be used to provide options for `ServiceWorkerModule` outside of
625 * `ServiceWorkerModule.register()`.
626 *
627 * You can use this token to define a provider that generates the registration options at runtime,
628 * for example via a function call:
629 *
630 * {@example service-worker/registration-options/module.ts region="registration-options"
631 * header="app.module.ts"}
632 *
633 * @publicApi
634 */
635 var SwRegistrationOptions = /** @class */ (function () {
636 function SwRegistrationOptions() {
637 }
638 return SwRegistrationOptions;
639 }());
640 var SCRIPT = new core.InjectionToken('NGSW_REGISTER_SCRIPT');
641 function ngswAppInitializer(injector, script, options, platformId) {
642 var initializer = function () {
643 if (!(common.isPlatformBrowser(platformId) && ('serviceWorker' in navigator) &&
644 options.enabled !== false)) {
645 return;
646 }
647 // Wait for service worker controller changes, and fire an INITIALIZE action when a new SW
648 // becomes active. This allows the SW to initialize itself even if there is no application
649 // traffic.
650 navigator.serviceWorker.addEventListener('controllerchange', function () {
651 if (navigator.serviceWorker.controller !== null) {
652 navigator.serviceWorker.controller.postMessage({ action: 'INITIALIZE' });
653 }
654 });
655 var readyToRegister$;
656 if (typeof options.registrationStrategy === 'function') {
657 readyToRegister$ = options.registrationStrategy();
658 }
659 else {
660 var _a = __read((options.registrationStrategy || 'registerWhenStable:30000').split(':')), strategy = _a[0], args = _a.slice(1);
661 switch (strategy) {
662 case 'registerImmediately':
663 readyToRegister$ = rxjs.of(null);
664 break;
665 case 'registerWithDelay':
666 readyToRegister$ = delayWithTimeout(+args[0] || 0);
667 break;
668 case 'registerWhenStable':
669 readyToRegister$ = !args[0] ? whenStable(injector) :
670 rxjs.merge(whenStable(injector), delayWithTimeout(+args[0]));
671 break;
672 default:
673 // Unknown strategy.
674 throw new Error("Unknown ServiceWorker registration strategy: " + options.registrationStrategy);
675 }
676 }
677 // Don't return anything to avoid blocking the application until the SW is registered.
678 // Also, run outside the Angular zone to avoid preventing the app from stabilizing (especially
679 // given that some registration strategies wait for the app to stabilize).
680 // Catch and log the error if SW registration fails to avoid uncaught rejection warning.
681 var ngZone = injector.get(core.NgZone);
682 ngZone.runOutsideAngular(function () { return readyToRegister$.pipe(operators.take(1)).subscribe(function () { return navigator.serviceWorker.register(script, { scope: options.scope })
683 .catch(function (err) { return console.error('Service worker registration failed with:', err); }); }); });
684 };
685 return initializer;
686 }
687 function delayWithTimeout(timeout) {
688 return rxjs.of(null).pipe(operators.delay(timeout));
689 }
690 function whenStable(injector) {
691 var appRef = injector.get(core.ApplicationRef);
692 return appRef.isStable.pipe(operators.filter(function (stable) { return stable; }));
693 }
694 function ngswCommChannelFactory(opts, platformId) {
695 return new NgswCommChannel(common.isPlatformBrowser(platformId) && opts.enabled !== false ? navigator.serviceWorker :
696 undefined);
697 }
698 /**
699 * @publicApi
700 */
701 var ServiceWorkerModule = /** @class */ (function () {
702 function ServiceWorkerModule() {
703 }
704 /**
705 * Register the given Angular Service Worker script.
706 *
707 * If `enabled` is set to `false` in the given options, the module will behave as if service
708 * workers are not supported by the browser, and the service worker will not be registered.
709 */
710 ServiceWorkerModule.register = function (script, opts) {
711 if (opts === void 0) { opts = {}; }
712 return {
713 ngModule: ServiceWorkerModule,
714 providers: [
715 { provide: SCRIPT, useValue: script },
716 { provide: SwRegistrationOptions, useValue: opts },
717 {
718 provide: NgswCommChannel,
719 useFactory: ngswCommChannelFactory,
720 deps: [SwRegistrationOptions, core.PLATFORM_ID]
721 },
722 {
723 provide: core.APP_INITIALIZER,
724 useFactory: ngswAppInitializer,
725 deps: [core.Injector, SCRIPT, SwRegistrationOptions, core.PLATFORM_ID],
726 multi: true,
727 },
728 ],
729 };
730 };
731 return ServiceWorkerModule;
732 }());
733 ServiceWorkerModule.decorators = [
734 { type: core.NgModule, args: [{
735 providers: [SwPush, SwUpdate],
736 },] }
737 ];
738
739 /**
740 * @license
741 * Copyright Google LLC All Rights Reserved.
742 *
743 * Use of this source code is governed by an MIT-style license that can be
744 * found in the LICENSE file at https://angular.io/license
745 */
746
747 /**
748 * @license
749 * Copyright Google LLC All Rights Reserved.
750 *
751 * Use of this source code is governed by an MIT-style license that can be
752 * found in the LICENSE file at https://angular.io/license
753 */
754 // This file only reexports content of the `src` folder. Keep it that way.
755
756 /**
757 * @license
758 * Copyright Google LLC All Rights Reserved.
759 *
760 * Use of this source code is governed by an MIT-style license that can be
761 * found in the LICENSE file at https://angular.io/license
762 */
763
764 /**
765 * Generated bundle index. Do not edit.
766 */
767
768 exports.ServiceWorkerModule = ServiceWorkerModule;
769 exports.SwPush = SwPush;
770 exports.SwRegistrationOptions = SwRegistrationOptions;
771 exports.SwUpdate = SwUpdate;
772 exports.ɵangular_packages_service_worker_service_worker_a = NgswCommChannel;
773 exports.ɵangular_packages_service_worker_service_worker_b = SCRIPT;
774 exports.ɵangular_packages_service_worker_service_worker_c = ngswAppInitializer;
775 exports.ɵangular_packages_service_worker_service_worker_d = ngswCommChannelFactory;
776
777 Object.defineProperty(exports, '__esModule', { value: true });
778
779})));
780//# sourceMappingURL=service-worker.umd.js.map