@active-reach/web-sdk 1.45.3 → 1.46.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.
@@ -1 +1 @@
1
- {"version":3,"file":"AegisWebPush.d.ts","sourceRoot":"","sources":["../../src/push/AegisWebPush.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAC3B,IAAI,CACA,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,OAAO,CAAC,OAAO,CAAC,CAAC;CACvB;AAED,MAAM,WAAW,eAAe;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAC/B,cAAc,EAAE,MAAM,CAAC;IAKvB,UAAU,EAAE,MAAM,CAAC;IAInB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAe5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,gBAAgB;IAC7B,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CACvE;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,YAAY;IACzB;;uDAEmD;IACnD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,E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KG;IACH,OAAO,CAAC,gBAAgB;IA6BxB;;OAEG;YACW,YAAY;IAgB1B;;OAEG;IACH,OAAO,CAAC,eAAe;IAgEvB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,eAAe;YA+BT,qBAAqB;IA0BnC,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,cAAc;IAStB;sEACkE;IAClE,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,qBAAqB;IAW7B;kCAC8B;IAC9B,OAAO,CAAC,aAAa;CAKxB"}
@@ -1,542 +1,5 @@
1
- const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2
- class AegisWebPush {
3
- constructor(apiClient, config, eventTracker) {
4
- this.swRegistration = null;
5
- this.initialized = false;
6
- this.heartbeatTimer = null;
7
- this.hooks = /* @__PURE__ */ new Map();
8
- this.apiClient = apiClient;
9
- this.config = {
10
- serviceWorkerPath: "/aegis-sw.js",
11
- serviceWorkerScope: "/",
12
- autoPrompt: false,
13
- promptDelay: 5e3,
14
- ...config
15
- };
16
- if (eventTracker) {
17
- this.eventTracker = eventTracker;
18
- } else if (this.config.writeKey && this.config.organizationId) {
19
- this.eventTracker = this.createBuiltinEventTracker(
20
- this.config.writeKey,
21
- this.config.organizationId
22
- );
23
- } else {
24
- this.eventTracker = null;
25
- if (typeof console !== "undefined" && console.warn) {
26
- console.warn(
27
- `[Active Reach WebPush] Push lifecycle tracking is DISABLED — no eventTracker and missing writeKey/organizationId (hasWriteKey=${!!this.config.writeKey}, hasOrganizationId=${!!this.config.organizationId}). delivered/clicked/dismissed will not be recorded.`
28
- );
29
- }
30
- }
31
- }
32
- /** Built-in fallback that POSTs push lifecycle events to
33
- * `/v1/push/engagement`. The gateway forwards to event-ingress with
34
- * the canonical `push.<event>` event_type, which the
35
- * event-switchboard's SDK_ENGAGEMENT_EVENT_TO_DELIVERY_MAPPING
36
- * dual-routes onto `aegis.delivery_events` as
37
- * `channel='push', status='shown'|'dismissed'|...`. Best-effort —
38
- * failures are warned but never thrown (push SW callbacks shouldn't
39
- * reject because the analytics POST failed). */
40
- createBuiltinEventTracker(writeKey, organizationId) {
41
- const apiClient = this.apiClient;
42
- const propertyId = this.config.propertyId;
43
- const resolveContactId = () => this.resolveContactId();
44
- return {
45
- track(eventName, properties) {
46
- const contactId = properties.contact_id ?? resolveContactId();
47
- const body = {
48
- campaign_id: properties.campaign_id || "",
49
- message_id: properties.message_id || "",
50
- event_type: eventName,
51
- // e.g. 'push.delivered' — gateway tolerates either form
52
- user_id: properties.user_id || contactId,
53
- contact_id: contactId,
54
- anonymous_id: properties.anonymous_id || "",
55
- platform: properties.platform || "web",
56
- property_id: propertyId,
57
- metadata: properties.metadata ?? {}
58
- };
59
- const headers = {
60
- "X-Aegis-Write-Key": writeKey,
61
- "X-Organization-ID": organizationId,
62
- "X-Property-Id": propertyId
63
- };
64
- void Promise.resolve(
65
- apiClient.post("/v1/push/engagement", body, headers)
66
- ).catch((err) => {
67
- if (typeof console !== "undefined" && console.warn) {
68
- console.warn("[Active Reach WebPush] engagement report failed:", err);
69
- }
70
- });
71
- }
72
- };
73
- }
74
- // ── Public lifecycle hook API ──────────────────────────────────────────
75
- /** Generic typed subscribe — useful when the host wants to dispatch
76
- * multiple events through one wrapper. For single-event subscriptions
77
- * prefer the `on*` sugar methods below. */
78
- on(event, handler) {
79
- return this.register(event, handler);
80
- }
81
- /** Subscribe to push notification taps. CANCELLABLE — return `false`
82
- * (or call `evt.preventDefault()`) to suppress the SDK's default
83
- * `window.location.href = action_url` fallback. Use this to wire a
84
- * SPA router into the typed `action_type` payload (e.g. open the
85
- * cart drawer in-place instead of a full reload). */
86
- onPushTap(handler) {
87
- return this.register("push-tap", handler);
88
- }
89
- /** Subscribe to push impressions — fires after the OS notification
90
- * has actually rendered. `degraded=true` when the SW fell back to
91
- * the minimal `{title, body}` path (broken icon, etc.). */
92
- onPushShown(handler) {
93
- return this.register("push-shown", handler);
94
- }
95
- /** Subscribe to push dismissals (notification closed without a tap). */
96
- onPushDismiss(handler) {
97
- return this.register("push-dismissed", handler);
98
- }
99
- /** Subscribe to non-fatal SDK errors. Wire into Sentry / Datadog. */
100
- onError(handler) {
101
- return this.register("error", handler);
102
- }
103
- register(eventName, handler) {
104
- if (!this.hooks.has(eventName)) this.hooks.set(eventName, /* @__PURE__ */ new Set());
105
- this.hooks.get(eventName).add(handler);
106
- return () => {
107
- var _a;
108
- (_a = this.hooks.get(eventName)) == null ? void 0 : _a.delete(handler);
109
- };
110
- }
111
- emit(eventName, payload) {
112
- const handlers = this.hooks.get(eventName);
113
- if (!handlers || handlers.size === 0) return true;
114
- let proceed = true;
115
- for (const handler of handlers) {
116
- try {
117
- const result = handler(payload);
118
- if (result === false) proceed = false;
119
- } catch (err) {
120
- this.emitError(err, { event: eventName });
121
- }
122
- }
123
- return proceed;
124
- }
125
- emitError(err, context) {
126
- const handlers = this.hooks.get("error");
127
- if (!handlers || handlers.size === 0) {
128
- console.warn(
129
- "[Active Reach WebPush] error:",
130
- err instanceof Error ? err.message : String(err),
131
- context ?? {}
132
- );
133
- return;
134
- }
135
- for (const handler of handlers) {
136
- try {
137
- handler({
138
- message: err instanceof Error ? err.message : String(err),
139
- error: err,
140
- context: context ?? {}
141
- });
142
- } catch {
143
- }
144
- }
145
- }
146
- async initialize() {
147
- if (this.initialized) return;
148
- if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
149
- console.warn("[Active Reach WebPush] Push notifications not supported in this browser");
150
- return;
151
- }
152
- try {
153
- this.swRegistration = await navigator.serviceWorker.register(
154
- this.config.serviceWorkerPath,
155
- { scope: this.config.serviceWorkerScope }
156
- );
157
- await navigator.serviceWorker.ready;
158
- this.initialized = true;
159
- navigator.serviceWorker.addEventListener("message", (event) => {
160
- this.handleSWMessage(event.data);
161
- });
162
- if (typeof window !== "undefined" && Notification.permission === "granted") {
163
- this.subscribeToPush().catch((err) => {
164
- console.warn("[Active Reach WebPush] auto-resync subscribeToPush failed:", err);
165
- });
166
- if (!this.heartbeatTimer) {
167
- this.heartbeatTimer = setInterval(() => {
168
- if (Notification.permission === "granted") {
169
- this.subscribeToPush().catch((err) => {
170
- console.warn("[Active Reach WebPush] heartbeat resync failed:", err);
171
- });
172
- }
173
- }, HEARTBEAT_INTERVAL_MS);
174
- }
175
- }
176
- if (this.config.autoPrompt) {
177
- setTimeout(() => this.requestPermission(), this.config.promptDelay);
178
- }
179
- } catch (err) {
180
- console.error("[Active Reach WebPush] Service worker registration failed:", err);
181
- }
182
- }
183
- async requestPermission() {
184
- const permission = await Notification.requestPermission();
185
- if (permission === "granted") {
186
- await this.subscribeToPush();
187
- return true;
188
- }
189
- this.trackPushEvent("push.permission_denied", {});
190
- return false;
191
- }
192
- async identify(params) {
193
- var _a;
194
- try {
195
- if (params.contactId) {
196
- window.localStorage.setItem("aegis_contact_id", params.contactId);
197
- }
198
- } catch {
199
- }
200
- const subscription = await ((_a = this.swRegistration) == null ? void 0 : _a.pushManager.getSubscription());
201
- if (!subscription) return;
202
- const subscriptionJSON = subscription.toJSON();
203
- const fingerprint = await this.getStableFingerprint();
204
- await this.retryApiCall(
205
- () => this.apiClient.post(
206
- "/v1/web_push/subscriptions",
207
- {
208
- contact_id: params.contactId ?? this.resolveContactId(),
209
- endpoint: subscriptionJSON.endpoint,
210
- p256dh: subscriptionJSON.keys.p256dh,
211
- auth: subscriptionJSON.keys.auth,
212
- device_fingerprint: fingerprint,
213
- user_agent: navigator.userAgent,
214
- application_server_key: this.encodeAppServerKey(subscription)
215
- },
216
- { "X-Property-Id": this.config.propertyId }
217
- )
218
- );
219
- }
220
- /**
221
- * Log out: detach THIS device from the contact. Not a consent statement —
222
- * the contact's push opt-in / opt-out is left exactly as it was (Aman
223
- * 2026-09-25), so it calls `/v1/web_push/unbind`, never `/unsubscribe`.
224
- */
225
- async logout() {
226
- var _a;
227
- const subscription = await ((_a = this.swRegistration) == null ? void 0 : _a.pushManager.getSubscription());
228
- if (!subscription) return;
229
- const subscriptionJSON = subscription.toJSON();
230
- const fingerprint = await this.getStableFingerprint();
231
- try {
232
- await this.apiClient.post(
233
- "/v1/web_push/unbind",
234
- {
235
- contact_id: this.resolveContactId(),
236
- device_fingerprint: fingerprint,
237
- endpoint: subscriptionJSON.endpoint
238
- },
239
- { "X-Property-Id": this.config.propertyId }
240
- );
241
- } finally {
242
- try {
243
- window.localStorage.removeItem("aegis_contact_id");
244
- } catch {
245
- }
246
- }
247
- }
248
- /**
249
- * Turn push back ON for a customer who opted out — only from a VERIFIED
250
- * storefront session (the `session_code` the store's phone-OTP sign-in
251
- * minted). The server resolves the customer from that session; this SDK
252
- * never names who is opted in, so a page cannot opt anyone else in. A
253
- * registration alone never re-enables push after an opt-out.
254
- */
255
- async optIn(params) {
256
- await this.apiClient.post(
257
- "/v1/web_push/opt-in",
258
- { slug: params.slug, session_code: params.sessionCode },
259
- { "X-Property-Id": this.config.propertyId }
260
- );
261
- }
262
- // ---------------------------------------------------------------
263
- // Private
264
- // ---------------------------------------------------------------
265
- async subscribeToPush() {
266
- var _a;
267
- if (!this.swRegistration) return;
268
- const desiredKey = this.urlBase64ToUint8Array(this.config.vapidPublicKey);
269
- try {
270
- const existing = await this.swRegistration.pushManager.getSubscription();
271
- const existingKey = (_a = existing == null ? void 0 : existing.options) == null ? void 0 : _a.applicationServerKey;
272
- if (existing && existingKey) {
273
- const a = new Uint8Array(existingKey);
274
- const matches = a.length === desiredKey.length && a.every((b, i) => b === desiredKey[i]);
275
- if (!matches) {
276
- await existing.unsubscribe();
277
- this.trackPushEvent("push.resubscribed", { reason: "vapid_key_drift" });
278
- }
279
- }
280
- } catch {
281
- }
282
- const subscription = await this.swRegistration.pushManager.subscribe({
283
- userVisibleOnly: true,
284
- // An ArrayBuffer holding exactly the key bytes: TypeScript >= 5.7
285
- // types `Uint8Array` as possibly SharedArrayBuffer-backed, which
286
- // `applicationServerKey` (BufferSource) does not accept.
287
- applicationServerKey: this.toArrayBuffer(desiredKey)
288
- });
289
- const subscriptionJSON = subscription.toJSON();
290
- const fingerprint = await this.getStableFingerprint();
291
- const contactId = this.resolveContactId();
292
- await this.retryApiCall(
293
- () => this.apiClient.post(
294
- "/v1/web_push/subscriptions",
295
- {
296
- contact_id: contactId,
297
- endpoint: subscriptionJSON.endpoint,
298
- p256dh: subscriptionJSON.keys.p256dh,
299
- auth: subscriptionJSON.keys.auth,
300
- device_fingerprint: fingerprint,
301
- user_agent: navigator.userAgent,
302
- application_server_key: this.encodeAppServerKey(subscription)
303
- },
304
- { "X-Property-Id": this.config.propertyId }
305
- )
306
- );
307
- this.trackPushEvent("push.subscribed", {
308
- browser: this.getBrowserInfo(),
309
- property_id: this.config.propertyId
310
- });
311
- }
312
- /**
313
- * Stable SHA-256 device fingerprint over (first_party_cookie_id + UA stable
314
- * parts). Used as the UPSERT key on `(property_id, device_fingerprint)` —
315
- * re-subscribes after VAPID rotation or permission reset update the same
316
- * row instead of leaving dangling duplicates.
317
- */
318
- async getStableFingerprint() {
319
- const cookieId = this.config.firstPartyCookieId;
320
- const ua = navigator.userAgent || "";
321
- const platform = navigator.platform || "";
322
- const language = navigator.language || "";
323
- const input = `${cookieId}|${ua}|${platform}|${language}`;
324
- if (typeof crypto !== "undefined" && crypto.subtle) {
325
- const bytes = new TextEncoder().encode(input);
326
- const hash = await crypto.subtle.digest("SHA-256", bytes);
327
- return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
328
- }
329
- let h = 2166136261;
330
- for (let i = 0; i < input.length; i++) {
331
- h ^= input.charCodeAt(i);
332
- h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
333
- }
334
- return `fnv-${h.toString(16)}`;
335
- }
336
- /**
337
- * Resolve the current contact_id. AegisWebPush doesn't own identity, so
338
- * we look in a few well-known localStorage keys that the identity layer
339
- * of the SDK writes. If no known contact is set, we use the first-party
340
- * cookie id — the backend upgrades the row when identify() is called.
341
- */
342
- resolveContactId() {
343
- try {
344
- const fromStorage = window.localStorage.getItem("aegis_contact_id") || window.localStorage.getItem("aegis_user_id");
345
- if (fromStorage) {
346
- if (fromStorage.startsWith("{")) {
347
- try {
348
- const parsed = JSON.parse(fromStorage);
349
- if (typeof parsed.value === "string" && parsed.value) {
350
- return parsed.value;
351
- }
352
- } catch {
353
- }
354
- }
355
- return fromStorage;
356
- }
357
- } catch {
358
- }
359
- return this.config.firstPartyCookieId;
360
- }
361
- /**
362
- * Retry an API call with exponential backoff (max 3 retries: 1s, 2s, 4s).
363
- */
364
- async retryApiCall(fn, maxRetries = 3) {
365
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
366
- try {
367
- await fn();
368
- return;
369
- } catch (err) {
370
- if (attempt === maxRetries) {
371
- console.error("[Active Reach WebPush] API call failed after retries:", err);
372
- return;
373
- }
374
- const delay = 1e3 * Math.pow(2, attempt);
375
- await new Promise((r) => setTimeout(r, delay));
376
- }
377
- }
378
- }
379
- /**
380
- * Handle messages forwarded from the service worker (push click, dismiss).
381
- */
382
- handleSWMessage(data) {
383
- if (!data || typeof data.type !== "string") return;
384
- switch (data.type) {
385
- case "push.clicked": {
386
- this.trackPushEvent("push.clicked", {
387
- campaign_id: data.campaign_id,
388
- // Attribution echoed by the SW → forwarded to the engagement
389
- // event so it rolls up per-journey / per-template / per-outlet.
390
- journey_execution_id: data.journey_execution_id,
391
- lifecycle_fork_id: data.lifecycle_fork_id,
392
- location_id: data.location_id,
393
- action_url: data.action_url,
394
- action_type: data.action_type,
395
- // Button-level click attribution (delivery_events.button_*).
396
- button_id: data.button_id,
397
- button_label: data.button_label
398
- });
399
- this.dispatchPushTap(data);
400
- break;
401
- }
402
- case "push.dismissed":
403
- this.trackPushEvent("push.dismissed", {
404
- campaign_id: data.campaign_id,
405
- journey_execution_id: data.journey_execution_id,
406
- lifecycle_fork_id: data.lifecycle_fork_id,
407
- location_id: data.location_id
408
- });
409
- this.emit("push-dismissed", {
410
- campaign_id: data.campaign_id
411
- });
412
- break;
413
- case "push.delivered":
414
- this.trackPushEvent("push.delivered", {
415
- campaign_id: data.campaign_id,
416
- journey_execution_id: data.journey_execution_id,
417
- lifecycle_fork_id: data.lifecycle_fork_id,
418
- location_id: data.location_id
419
- });
420
- this.emit("push-shown", {
421
- campaign_id: data.campaign_id,
422
- degraded: data.degraded === true ? true : void 0
423
- });
424
- break;
425
- case "push.resubscribed":
426
- void this.persistResubscription(
427
- data.subscription
428
- );
429
- break;
430
- }
431
- }
432
- /**
433
- * Translate a SW `push.clicked` postMessage into a typed PushTapEvent,
434
- * dispatch through the lifecycle hook bus, and fall back to a hard
435
- * navigation if no host handler claimed it.
436
- *
437
- * The fallback path matters: if a tenant ships a push template with
438
- * an unknown `action_type` (no SPA handler registered) OR pushes the
439
- * SDK before the host wires up its `onPushTap` subscriber, we still
440
- * want the user to land somewhere — `action_url` is always set by the
441
- * SW's notificationclick handler (it falls back to '/').
442
- */
443
- dispatchPushTap(data) {
444
- if (typeof window === "undefined") return;
445
- const actionUrl = data.action_url || "/";
446
- let defaultPrevented = false;
447
- const evt = {
448
- action_type: data.action_type,
449
- action_payload: data.action_payload,
450
- action_url: actionUrl,
451
- action: data.action || "default",
452
- campaign_id: data.campaign_id,
453
- preventDefault: () => {
454
- defaultPrevented = true;
455
- evt.defaultPrevented = true;
456
- },
457
- defaultPrevented: false
458
- };
459
- const proceed = this.emit("push-tap", evt);
460
- if (proceed && !defaultPrevented) {
461
- try {
462
- window.location.href = actionUrl;
463
- } catch {
464
- }
465
- }
466
- }
467
- async persistResubscription(subscription) {
468
- if (!subscription || !subscription.endpoint || !subscription.keys) return;
469
- try {
470
- const fingerprint = await this.getStableFingerprint();
471
- await this.retryApiCall(
472
- () => this.apiClient.post(
473
- "/v1/web_push/subscriptions",
474
- {
475
- contact_id: this.resolveContactId(),
476
- endpoint: subscription.endpoint,
477
- p256dh: subscription.keys.p256dh,
478
- auth: subscription.keys.auth,
479
- device_fingerprint: fingerprint,
480
- user_agent: navigator.userAgent
481
- },
482
- { "X-Property-Id": this.config.propertyId }
483
- )
484
- );
485
- this.trackPushEvent("push.resubscribed", {});
486
- } catch (err) {
487
- console.warn("[Active Reach WebPush] persistResubscription failed:", err);
488
- }
489
- }
490
- trackPushEvent(eventName, properties) {
491
- var _a;
492
- (_a = this.eventTracker) == null ? void 0 : _a.track(eventName, {
493
- ...properties,
494
- platform: "web",
495
- browser: this.getBrowserInfo()
496
- });
497
- }
498
- getBrowserInfo() {
499
- const ua = navigator.userAgent;
500
- if (ua.includes("Edg")) return "edge";
501
- if (ua.includes("Chrome")) return "chrome";
502
- if (ua.includes("Firefox")) return "firefox";
503
- if (ua.includes("Safari")) return "safari";
504
- return "unknown";
505
- }
506
- /** base64url-encode the subscription's applicationServerKey for the
507
- * register POST's diagnostic echo (wrong-key mint detection). */
508
- encodeAppServerKey(sub) {
509
- var _a;
510
- try {
511
- const k = (_a = sub.options) == null ? void 0 : _a.applicationServerKey;
512
- if (!k) return void 0;
513
- const bytes = new Uint8Array(k);
514
- let bin = "";
515
- for (const b of bytes) bin += String.fromCharCode(b);
516
- return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
517
- } catch {
518
- return void 0;
519
- }
520
- }
521
- urlBase64ToUint8Array(base64String) {
522
- const padding = "=".repeat((4 - base64String.length % 4) % 4);
523
- const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
524
- const rawData = atob(base64);
525
- const arr = new Uint8Array(rawData.length);
526
- for (let i = 0; i < rawData.length; ++i) {
527
- arr[i] = rawData.charCodeAt(i);
528
- }
529
- return arr;
530
- }
531
- /** A fresh ArrayBuffer with exactly these bytes (never a view's larger or
532
- * shared backing buffer). */
533
- toArrayBuffer(bytes) {
534
- const buf = new ArrayBuffer(bytes.length);
535
- new Uint8Array(buf).set(bytes);
536
- return buf;
537
- }
538
- }
1
+ import { A } from "../AegisWebPush-BE9wJcx0.mjs";
539
2
  export {
540
- AegisWebPush
3
+ A as AegisWebPush
541
4
  };
542
5
  //# sourceMappingURL=AegisWebPush.js.map