@metamask-previews/notification-services-controller 0.18.0-preview-442894ce → 0.18.0-preview-9a5238f
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/dist/NotificationServicesController/NotificationServicesController.cjs +49 -48
- package/dist/NotificationServicesController/NotificationServicesController.cjs.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.cts +3 -3
- package/dist/NotificationServicesController/NotificationServicesController.d.cts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.mts +3 -3
- package/dist/NotificationServicesController/NotificationServicesController.d.mts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.mjs +49 -48
- package/dist/NotificationServicesController/NotificationServicesController.mjs.map +1 -1
- package/dist/NotificationServicesController/index.cjs +0 -1
- package/dist/NotificationServicesController/index.cjs.map +1 -1
- package/dist/NotificationServicesController/index.d.cts +0 -1
- package/dist/NotificationServicesController/index.d.cts.map +1 -1
- package/dist/NotificationServicesController/index.d.mts +0 -1
- package/dist/NotificationServicesController/index.d.mts.map +1 -1
- package/dist/NotificationServicesController/index.mjs +0 -1
- package/dist/NotificationServicesController/index.mjs.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs +40 -43
- package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts +21 -19
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts +21 -19
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +41 -44
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs.map +1 -1
- package/dist/NotificationServicesPushController/{types/push-service-interface.cjs → services/push/index.cjs} +1 -1
- package/dist/NotificationServicesPushController/services/push/index.cjs.map +1 -0
- package/dist/NotificationServicesPushController/services/push/index.d.cts +6 -0
- package/dist/NotificationServicesPushController/services/push/index.d.cts.map +1 -0
- package/dist/NotificationServicesPushController/services/push/index.d.mts +6 -0
- package/dist/NotificationServicesPushController/services/push/index.d.mts.map +1 -0
- package/dist/NotificationServicesPushController/services/push/index.mjs +2 -0
- package/dist/NotificationServicesPushController/services/push/index.mjs.map +1 -0
- package/dist/NotificationServicesPushController/{web/push-helpers.cjs → services/push/push-web.cjs} +8 -37
- package/dist/NotificationServicesPushController/services/push/push-web.cjs.map +1 -0
- package/dist/NotificationServicesPushController/services/push/push-web.d.cts +33 -0
- package/dist/NotificationServicesPushController/services/push/push-web.d.cts.map +1 -0
- package/dist/NotificationServicesPushController/services/push/push-web.d.mts +33 -0
- package/dist/NotificationServicesPushController/services/push/push-web.d.mts.map +1 -0
- package/dist/NotificationServicesPushController/{web/push-helpers.mjs → services/push/push-web.mjs} +7 -37
- package/dist/NotificationServicesPushController/services/push/push-web.mjs.map +1 -0
- package/dist/NotificationServicesPushController/services/services.cjs +28 -3
- package/dist/NotificationServicesPushController/services/services.cjs.map +1 -1
- package/dist/NotificationServicesPushController/services/services.d.cts +15 -1
- package/dist/NotificationServicesPushController/services/services.d.cts.map +1 -1
- package/dist/NotificationServicesPushController/services/services.d.mts +15 -1
- package/dist/NotificationServicesPushController/services/services.d.mts.map +1 -1
- package/dist/NotificationServicesPushController/services/services.mjs +26 -2
- package/dist/NotificationServicesPushController/services/services.mjs.map +1 -1
- package/dist/NotificationServicesPushController/types/index.cjs +15 -0
- package/dist/NotificationServicesPushController/types/index.cjs.map +1 -1
- package/dist/NotificationServicesPushController/types/index.d.cts +1 -2
- package/dist/NotificationServicesPushController/types/index.d.cts.map +1 -1
- package/dist/NotificationServicesPushController/types/index.d.mts +1 -2
- package/dist/NotificationServicesPushController/types/index.d.mts.map +1 -1
- package/dist/NotificationServicesPushController/types/index.mjs +1 -1
- package/dist/NotificationServicesPushController/types/index.mjs.map +1 -1
- package/package.json +2 -12
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.cjs +0 -14
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.cjs.map +0 -1
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.cts +0 -3
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.cts.map +0 -1
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.mts +0 -3
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.d.mts.map +0 -1
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.mjs +0 -10
- package/dist/NotificationServicesPushController/__fixtures__/mockMessenger.mjs.map +0 -1
- package/dist/NotificationServicesPushController/types/push-service-interface.cjs.map +0 -1
- package/dist/NotificationServicesPushController/types/push-service-interface.d.cts +0 -30
- package/dist/NotificationServicesPushController/types/push-service-interface.d.cts.map +0 -1
- package/dist/NotificationServicesPushController/types/push-service-interface.d.mts +0 -30
- package/dist/NotificationServicesPushController/types/push-service-interface.d.mts.map +0 -1
- package/dist/NotificationServicesPushController/types/push-service-interface.mjs +0 -2
- package/dist/NotificationServicesPushController/types/push-service-interface.mjs.map +0 -1
- package/dist/NotificationServicesPushController/web/index.cjs +0 -8
- package/dist/NotificationServicesPushController/web/index.cjs.map +0 -1
- package/dist/NotificationServicesPushController/web/index.d.cts +0 -2
- package/dist/NotificationServicesPushController/web/index.d.cts.map +0 -1
- package/dist/NotificationServicesPushController/web/index.d.mts +0 -2
- package/dist/NotificationServicesPushController/web/index.d.mts.map +0 -1
- package/dist/NotificationServicesPushController/web/index.mjs +0 -2
- package/dist/NotificationServicesPushController/web/index.mjs.map +0 -1
- package/dist/NotificationServicesPushController/web/push-helpers.cjs.map +0 -1
- package/dist/NotificationServicesPushController/web/push-helpers.d.cts +0 -37
- package/dist/NotificationServicesPushController/web/push-helpers.d.cts.map +0 -1
- package/dist/NotificationServicesPushController/web/push-helpers.d.mts +0 -37
- package/dist/NotificationServicesPushController/web/push-helpers.d.mts.map +0 -1
- package/dist/NotificationServicesPushController/web/push-helpers.mjs.map +0 -1
- package/push-services/web/package.json +0 -9
package/dist/NotificationServicesPushController/{web/push-helpers.cjs → services/push/push-web.cjs}
RENAMED
|
@@ -3,13 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.listenToPushNotificationsClicked = exports.listenToPushNotificationsReceived = exports.deleteRegToken = exports.createRegToken = exports.supportedCache = void 0;
|
|
7
7
|
const app_1 = require("firebase/app");
|
|
8
8
|
const messaging_1 = require("firebase/messaging");
|
|
9
9
|
const sw_1 = require("firebase/messaging/sw");
|
|
10
10
|
const loglevel_1 = __importDefault(require("loglevel"));
|
|
11
|
-
const NotificationServicesController_1 = require("
|
|
12
|
-
const to_raw_notification_1 = require("
|
|
11
|
+
const NotificationServicesController_1 = require("../../../NotificationServicesController/index.cjs");
|
|
12
|
+
const to_raw_notification_1 = require("../../../shared/to-raw-notification.cjs");
|
|
13
13
|
// Exported to help testing
|
|
14
14
|
// eslint-disable-next-line import-x/no-mutable-exports
|
|
15
15
|
exports.supportedCache = null;
|
|
@@ -80,16 +80,15 @@ async function deleteRegToken(env) {
|
|
|
80
80
|
await (0, messaging_1.deleteToken)(messaging);
|
|
81
81
|
return true;
|
|
82
82
|
}
|
|
83
|
-
catch {
|
|
83
|
+
catch (error) {
|
|
84
84
|
return false;
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
exports.deleteRegToken = deleteRegToken;
|
|
88
88
|
/**
|
|
89
89
|
* Service Worker Listener for when push notifications are received.
|
|
90
|
-
*
|
|
91
90
|
* @param env - push notification environment
|
|
92
|
-
* @param handler - handler to actually showing notification, MUST BE
|
|
91
|
+
* @param handler - handler to actually showing notification, MUST BE PROVEDED
|
|
93
92
|
* @returns unsubscribe handler
|
|
94
93
|
*/
|
|
95
94
|
async function listenToPushNotificationsReceived(env, handler) {
|
|
@@ -121,6 +120,7 @@ async function listenToPushNotificationsReceived(env, handler) {
|
|
|
121
120
|
const unsubscribe = () => unsubscribePushNotifications();
|
|
122
121
|
return unsubscribe;
|
|
123
122
|
}
|
|
123
|
+
exports.listenToPushNotificationsReceived = listenToPushNotificationsReceived;
|
|
124
124
|
/**
|
|
125
125
|
* Service Worker Listener for when a notification is clicked
|
|
126
126
|
*
|
|
@@ -137,34 +137,5 @@ function listenToPushNotificationsClicked(handler) {
|
|
|
137
137
|
const unsubscribe = () => self.removeEventListener('notificationclick', clickHandler);
|
|
138
138
|
return unsubscribe;
|
|
139
139
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
* 1. Creates subscriptions for receiving and clicking notifications
|
|
143
|
-
* 2. Creates click events when a notification is clicked
|
|
144
|
-
* 3. Publishes controller messenger events
|
|
145
|
-
*
|
|
146
|
-
* @param props - props for this creator function.
|
|
147
|
-
* @param props.onReceivedHandler - allows the developer to handle showing a notification
|
|
148
|
-
* @param props.onClickHandler - allows the developer to handle clicking the notification
|
|
149
|
-
* @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
|
|
150
|
-
* @returns a function that can be used by the controller
|
|
151
|
-
*/
|
|
152
|
-
function createSubscribeToPushNotifications(props) {
|
|
153
|
-
return async function (env) {
|
|
154
|
-
const onBackgroundMessageSub = await listenToPushNotificationsReceived(env, async (notification) => {
|
|
155
|
-
props.messenger.publish('NotificationServicesPushController:onNewNotifications', notification);
|
|
156
|
-
await props.onReceivedHandler(notification);
|
|
157
|
-
});
|
|
158
|
-
const onClickSub = listenToPushNotificationsClicked((event, notification) => {
|
|
159
|
-
props.messenger.publish('NotificationServicesPushController:pushNotificationClicked', notification);
|
|
160
|
-
props.onClickHandler(event, notification);
|
|
161
|
-
});
|
|
162
|
-
const unsubscribe = () => {
|
|
163
|
-
onBackgroundMessageSub?.();
|
|
164
|
-
onClickSub();
|
|
165
|
-
};
|
|
166
|
-
return unsubscribe;
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
exports.createSubscribeToPushNotifications = createSubscribeToPushNotifications;
|
|
170
|
-
//# sourceMappingURL=push-helpers.cjs.map
|
|
140
|
+
exports.listenToPushNotificationsClicked = listenToPushNotificationsClicked;
|
|
141
|
+
//# sourceMappingURL=push-web.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-web.cjs","sourceRoot":"","sources":["../../../../src/NotificationServicesPushController/services/push/push-web.ts"],"names":[],"mappings":";;;;;;AAIA,sCAAqD;AACrD,kDAA2D;AAC3D,8CAI+B;AAE/B,wDAA2B;AAG3B,sGAAqE;AACrE,iFAA+E;AAK/E,2BAA2B;AAC3B,uDAAuD;AAC5C,QAAA,cAAc,GAAmB,IAAI,CAAC;AAEjD,MAAM,mBAAmB,GAAG,KAAK,IAAI,EAAE;IACrC,sBAAc,KAAd,sBAAc,GAAK,MAAM,IAAA,gBAAW,GAAE,EAAC;IACvC,OAAO,sBAAc,CAAC;AACxB,CAAC,CAAC;AAEF,MAAM,iBAAiB,GAAG,KAAK,EAC7B,GAAwB,EACF,EAAE;IACxB,IAAI;QACF,OAAO,IAAA,YAAM,GAAE,CAAC;KACjB;IAAC,MAAM;QACN,MAAM,cAAc,GAAG;YACrB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,iBAAiB,EAAE,GAAG,CAAC,iBAAiB;YACxC,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,aAAa,EAAE,GAAG,CAAC,aAAa;SACjC,CAAC;QACF,OAAO,IAAA,mBAAa,EAAC,cAAc,CAAC,CAAC;KACtC;AACH,CAAC,CAAC;AAEF,MAAM,oBAAoB,GAAG,KAAK,EAChC,GAAwB,EACG,EAAE;IAC7B,MAAM,SAAS,GAAG,MAA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AC;AACrB,CAAC;AAbD,4EAaC","sourcesContent":["// We are defining that this file uses a webworker global scope.\n// eslint-disable-next-line spaced-comment\n/// <reference lib=\"webworker\" />\nimport type { FirebaseApp } from 'firebase/app';\nimport { getApp, initializeApp } from 'firebase/app';\nimport { getToken, deleteToken } from 'firebase/messaging';\nimport {\n getMessaging,\n onBackgroundMessage,\n isSupported,\n} from 'firebase/messaging/sw';\nimport type { Messaging, MessagePayload } from 'firebase/messaging/sw';\nimport log from 'loglevel';\n\nimport type { Types } from '../../../NotificationServicesController';\nimport { Processors } from '../../../NotificationServicesController';\nimport { toRawOnChainNotification } from '../../../shared/to-raw-notification';\nimport type { PushNotificationEnv } from '../../types/firebase';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let supportedCache: boolean | null = null;\n\nconst getPushAvailability = async () => {\n supportedCache ??= await isSupported();\n return supportedCache;\n};\n\nconst createFirebaseApp = async (\n env: PushNotificationEnv,\n): Promise<FirebaseApp> => {\n try {\n return getApp();\n } catch {\n const firebaseConfig = {\n apiKey: env.apiKey,\n authDomain: env.authDomain,\n storageBucket: env.storageBucket,\n projectId: env.projectId,\n messagingSenderId: env.messagingSenderId,\n appId: env.appId,\n measurementId: env.measurementId,\n };\n return initializeApp(firebaseConfig);\n }\n};\n\nconst getFirebaseMessaging = async (\n env: PushNotificationEnv,\n): Promise<Messaging | null> => {\n const supported = await getPushAvailability();\n if (!supported) {\n return null;\n }\n\n const app = await createFirebaseApp(env);\n return getMessaging(app);\n};\n\n/**\n * Creates a registration token for Firebase Cloud Messaging.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with the registration token or null if an error occurs.\n */\nexport async function createRegToken(\n env: PushNotificationEnv,\n): Promise<string | null> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const token = await getToken(messaging, {\n serviceWorkerRegistration: self.registration,\n vapidKey: env.vapidKey,\n });\n return token;\n } catch {\n return null;\n }\n}\n\n/**\n * Deletes the Firebase Cloud Messaging registration token.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.\n */\nexport async function deleteRegToken(\n env: PushNotificationEnv,\n): Promise<boolean> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return true;\n }\n\n await deleteToken(messaging);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Service Worker Listener for when push notifications are received.\n * @param env - push notification environment\n * @param handler - handler to actually showing notification, MUST BE PROVEDED\n * @returns unsubscribe handler\n */\nexport async function listenToPushNotificationsReceived(\n env: PushNotificationEnv,\n handler: (notification: Types.INotification) => void | Promise<void>,\n): Promise<(() => void) | null> {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const unsubscribePushNotifications = onBackgroundMessage(\n messaging,\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (payload: MessagePayload) => {\n try {\n const data: Types.UnprocessedOnChainRawNotification | undefined =\n payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;\n\n if (!data) {\n return;\n }\n\n const notificationData = toRawOnChainNotification(data);\n const notification = Processors.processNotification(notificationData);\n await handler(notification);\n } catch (error) {\n // Do Nothing, cannot parse a bad notification\n log.error('Unable to send push notification:', {\n notification: payload?.data?.data,\n error,\n });\n throw new Error('Unable to send push notification');\n }\n },\n );\n\n const unsubscribe = () => unsubscribePushNotifications();\n return unsubscribe;\n}\n\n/**\n * Service Worker Listener for when a notification is clicked\n *\n * @param handler - listen to NotificationEvent from the service worker\n * @returns unsubscribe handler\n */\nexport function listenToPushNotificationsClicked(\n handler: (e: NotificationEvent, notification?: Types.INotification) => void,\n) {\n const clickHandler = (event: NotificationEvent) => {\n // Get Data\n const data: Types.INotification = event?.notification?.data;\n handler(event, data);\n };\n\n self.addEventListener('notificationclick', clickHandler);\n const unsubscribe = () =>\n self.removeEventListener('notificationclick', clickHandler);\n return unsubscribe;\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
import type { Types } from "../../../NotificationServicesController/index.cjs";
|
|
3
|
+
import type { PushNotificationEnv } from "../../types/firebase.cjs";
|
|
4
|
+
export declare let supportedCache: boolean | null;
|
|
5
|
+
/**
|
|
6
|
+
* Creates a registration token for Firebase Cloud Messaging.
|
|
7
|
+
*
|
|
8
|
+
* @param env - env to configure push notifications
|
|
9
|
+
* @returns A promise that resolves with the registration token or null if an error occurs.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createRegToken(env: PushNotificationEnv): Promise<string | null>;
|
|
12
|
+
/**
|
|
13
|
+
* Deletes the Firebase Cloud Messaging registration token.
|
|
14
|
+
*
|
|
15
|
+
* @param env - env to configure push notifications
|
|
16
|
+
* @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
|
|
17
|
+
*/
|
|
18
|
+
export declare function deleteRegToken(env: PushNotificationEnv): Promise<boolean>;
|
|
19
|
+
/**
|
|
20
|
+
* Service Worker Listener for when push notifications are received.
|
|
21
|
+
* @param env - push notification environment
|
|
22
|
+
* @param handler - handler to actually showing notification, MUST BE PROVEDED
|
|
23
|
+
* @returns unsubscribe handler
|
|
24
|
+
*/
|
|
25
|
+
export declare function listenToPushNotificationsReceived(env: PushNotificationEnv, handler: (notification: Types.INotification) => void | Promise<void>): Promise<(() => void) | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Service Worker Listener for when a notification is clicked
|
|
28
|
+
*
|
|
29
|
+
* @param handler - listen to NotificationEvent from the service worker
|
|
30
|
+
* @returns unsubscribe handler
|
|
31
|
+
*/
|
|
32
|
+
export declare function listenToPushNotificationsClicked(handler: (e: NotificationEvent, notification?: Types.INotification) => void): () => void;
|
|
33
|
+
//# sourceMappingURL=push-web.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-web.d.cts","sourceRoot":"","sources":["../../../../src/NotificationServicesPushController/services/push/push-web.ts"],"names":[],"mappings":";AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,0DAAgD;AAGrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,iCAA6B;AAMhE,eAAO,IAAI,cAAc,EAAE,OAAO,GAAG,IAAW,CAAC;AAsCjD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAexB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,OAAO,CAAC,CAYlB;AAED;;;;;GAKG;AACH,wBAAsB,iCAAiC,CACrD,GAAG,EAAE,mBAAmB,EACxB,OAAO,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,aAAa,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACnE,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC,CAkC9B;AAED;;;;;GAKG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,CAAC,CAAC,EAAE,iBAAiB,EAAE,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAAK,IAAI,cAY5E"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
import type { Types } from "../../../NotificationServicesController/index.mjs";
|
|
3
|
+
import type { PushNotificationEnv } from "../../types/firebase.mjs";
|
|
4
|
+
export declare let supportedCache: boolean | null;
|
|
5
|
+
/**
|
|
6
|
+
* Creates a registration token for Firebase Cloud Messaging.
|
|
7
|
+
*
|
|
8
|
+
* @param env - env to configure push notifications
|
|
9
|
+
* @returns A promise that resolves with the registration token or null if an error occurs.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createRegToken(env: PushNotificationEnv): Promise<string | null>;
|
|
12
|
+
/**
|
|
13
|
+
* Deletes the Firebase Cloud Messaging registration token.
|
|
14
|
+
*
|
|
15
|
+
* @param env - env to configure push notifications
|
|
16
|
+
* @returns A promise that resolves with true if the token was successfully deleted, false otherwise.
|
|
17
|
+
*/
|
|
18
|
+
export declare function deleteRegToken(env: PushNotificationEnv): Promise<boolean>;
|
|
19
|
+
/**
|
|
20
|
+
* Service Worker Listener for when push notifications are received.
|
|
21
|
+
* @param env - push notification environment
|
|
22
|
+
* @param handler - handler to actually showing notification, MUST BE PROVEDED
|
|
23
|
+
* @returns unsubscribe handler
|
|
24
|
+
*/
|
|
25
|
+
export declare function listenToPushNotificationsReceived(env: PushNotificationEnv, handler: (notification: Types.INotification) => void | Promise<void>): Promise<(() => void) | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Service Worker Listener for when a notification is clicked
|
|
28
|
+
*
|
|
29
|
+
* @param handler - listen to NotificationEvent from the service worker
|
|
30
|
+
* @returns unsubscribe handler
|
|
31
|
+
*/
|
|
32
|
+
export declare function listenToPushNotificationsClicked(handler: (e: NotificationEvent, notification?: Types.INotification) => void): () => void;
|
|
33
|
+
//# sourceMappingURL=push-web.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-web.d.mts","sourceRoot":"","sources":["../../../../src/NotificationServicesPushController/services/push/push-web.ts"],"names":[],"mappings":";AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,0DAAgD;AAGrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,iCAA6B;AAMhE,eAAO,IAAI,cAAc,EAAE,OAAO,GAAG,IAAW,CAAC;AAsCjD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAexB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,mBAAmB,GACvB,OAAO,CAAC,OAAO,CAAC,CAYlB;AAED;;;;;GAKG;AACH,wBAAsB,iCAAiC,CACrD,GAAG,EAAE,mBAAmB,EACxB,OAAO,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,aAAa,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACnE,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC,CAkC9B;AAED;;;;;GAKG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,CAAC,CAAC,EAAE,iBAAiB,EAAE,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAAK,IAAI,cAY5E"}
|
package/dist/NotificationServicesPushController/{web/push-helpers.mjs → services/push/push-web.mjs}
RENAMED
|
@@ -9,8 +9,8 @@ import { getToken, deleteToken } from "firebase/messaging";
|
|
|
9
9
|
import { getMessaging, onBackgroundMessage, isSupported } from "firebase/messaging/sw";
|
|
10
10
|
import $log from "loglevel";
|
|
11
11
|
const log = $importDefault($log);
|
|
12
|
-
import { Processors } from "
|
|
13
|
-
import { toRawOnChainNotification } from "
|
|
12
|
+
import { Processors } from "../../../NotificationServicesController/index.mjs";
|
|
13
|
+
import { toRawOnChainNotification } from "../../../shared/to-raw-notification.mjs";
|
|
14
14
|
// Exported to help testing
|
|
15
15
|
// eslint-disable-next-line import-x/no-mutable-exports
|
|
16
16
|
export let supportedCache = null;
|
|
@@ -80,18 +80,17 @@ export async function deleteRegToken(env) {
|
|
|
80
80
|
await deleteToken(messaging);
|
|
81
81
|
return true;
|
|
82
82
|
}
|
|
83
|
-
catch {
|
|
83
|
+
catch (error) {
|
|
84
84
|
return false;
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
88
88
|
* Service Worker Listener for when push notifications are received.
|
|
89
|
-
*
|
|
90
89
|
* @param env - push notification environment
|
|
91
|
-
* @param handler - handler to actually showing notification, MUST BE
|
|
90
|
+
* @param handler - handler to actually showing notification, MUST BE PROVEDED
|
|
92
91
|
* @returns unsubscribe handler
|
|
93
92
|
*/
|
|
94
|
-
async function listenToPushNotificationsReceived(env, handler) {
|
|
93
|
+
export async function listenToPushNotificationsReceived(env, handler) {
|
|
95
94
|
const messaging = await getFirebaseMessaging(env);
|
|
96
95
|
if (!messaging) {
|
|
97
96
|
return null;
|
|
@@ -126,7 +125,7 @@ async function listenToPushNotificationsReceived(env, handler) {
|
|
|
126
125
|
* @param handler - listen to NotificationEvent from the service worker
|
|
127
126
|
* @returns unsubscribe handler
|
|
128
127
|
*/
|
|
129
|
-
function listenToPushNotificationsClicked(handler) {
|
|
128
|
+
export function listenToPushNotificationsClicked(handler) {
|
|
130
129
|
const clickHandler = (event) => {
|
|
131
130
|
// Get Data
|
|
132
131
|
const data = event?.notification?.data;
|
|
@@ -136,33 +135,4 @@ function listenToPushNotificationsClicked(handler) {
|
|
|
136
135
|
const unsubscribe = () => self.removeEventListener('notificationclick', clickHandler);
|
|
137
136
|
return unsubscribe;
|
|
138
137
|
}
|
|
139
|
-
|
|
140
|
-
* A creator function that assists creating web-specific push notification subscription:
|
|
141
|
-
* 1. Creates subscriptions for receiving and clicking notifications
|
|
142
|
-
* 2. Creates click events when a notification is clicked
|
|
143
|
-
* 3. Publishes controller messenger events
|
|
144
|
-
*
|
|
145
|
-
* @param props - props for this creator function.
|
|
146
|
-
* @param props.onReceivedHandler - allows the developer to handle showing a notification
|
|
147
|
-
* @param props.onClickHandler - allows the developer to handle clicking the notification
|
|
148
|
-
* @param props.messenger - the controller messenger to publish the `onNewNotifications` and `pushNotificationsClicked` events
|
|
149
|
-
* @returns a function that can be used by the controller
|
|
150
|
-
*/
|
|
151
|
-
export function createSubscribeToPushNotifications(props) {
|
|
152
|
-
return async function (env) {
|
|
153
|
-
const onBackgroundMessageSub = await listenToPushNotificationsReceived(env, async (notification) => {
|
|
154
|
-
props.messenger.publish('NotificationServicesPushController:onNewNotifications', notification);
|
|
155
|
-
await props.onReceivedHandler(notification);
|
|
156
|
-
});
|
|
157
|
-
const onClickSub = listenToPushNotificationsClicked((event, notification) => {
|
|
158
|
-
props.messenger.publish('NotificationServicesPushController:pushNotificationClicked', notification);
|
|
159
|
-
props.onClickHandler(event, notification);
|
|
160
|
-
});
|
|
161
|
-
const unsubscribe = () => {
|
|
162
|
-
onBackgroundMessageSub?.();
|
|
163
|
-
onClickSub();
|
|
164
|
-
};
|
|
165
|
-
return unsubscribe;
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
//# sourceMappingURL=push-helpers.mjs.map
|
|
138
|
+
//# sourceMappingURL=push-web.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push-web.mjs","sourceRoot":"","sources":["../../../../src/NotificationServicesPushController/services/push/push-web.ts"],"names":[],"mappings":";;;;;;AAIA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,qBAAqB;AACrD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,2BAA2B;AAC3D,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,WAAW,EACZ,8BAA8B;AAE/B,OAAO,IAAG,iBAAiB;;AAG3B,OAAO,EAAE,UAAU,EAAE,0DAAgD;AACrE,OAAO,EAAE,wBAAwB,EAAE,gDAA4C;AAK/E,2BAA2B;AAC3B,uDAAuD;AACvD,MAAM,CAAC,IAAI,cAAc,GAAmB,IAAI,CAAC;AAEjD,MAAM,mBAAmB,GAAG,KAAK,IAAI,EAAE;IACrC,cAAc,KAAd,cAAc,GAAK,MAAM,WAAW,EAAE,EAAC;IACvC,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEF,MAAM,iBAAiB,GAAG,KAAK,EAC7B,GAAwB,EACF,EAAE;IACxB,IAAI;QACF,OAAO,MAAM,EAAE,CAAC;KACjB;IAAC,MAAM;QACN,MAAM,cAAc,GAAG;YACrB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,aAAa,EAAE,GAAG,CAAC,aAAa;YAChC,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,iBAAiB,EAAE,GAAG,CAAC,iBAAiB;YACxC,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,aAAa,EAAE,GAAG,C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AAC,CAAC;IACzD,MAAM,WAAW,GAAG,GAAG,EAAE,CACvB,IAAI,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,YAAY,CAAC,CAAC;IAC9D,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["// We are defining that this file uses a webworker global scope.\n// eslint-disable-next-line spaced-comment\n/// <reference lib=\"webworker\" />\nimport type { FirebaseApp } from 'firebase/app';\nimport { getApp, initializeApp } from 'firebase/app';\nimport { getToken, deleteToken } from 'firebase/messaging';\nimport {\n getMessaging,\n onBackgroundMessage,\n isSupported,\n} from 'firebase/messaging/sw';\nimport type { Messaging, MessagePayload } from 'firebase/messaging/sw';\nimport log from 'loglevel';\n\nimport type { Types } from '../../../NotificationServicesController';\nimport { Processors } from '../../../NotificationServicesController';\nimport { toRawOnChainNotification } from '../../../shared/to-raw-notification';\nimport type { PushNotificationEnv } from '../../types/firebase';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let supportedCache: boolean | null = null;\n\nconst getPushAvailability = async () => {\n supportedCache ??= await isSupported();\n return supportedCache;\n};\n\nconst createFirebaseApp = async (\n env: PushNotificationEnv,\n): Promise<FirebaseApp> => {\n try {\n return getApp();\n } catch {\n const firebaseConfig = {\n apiKey: env.apiKey,\n authDomain: env.authDomain,\n storageBucket: env.storageBucket,\n projectId: env.projectId,\n messagingSenderId: env.messagingSenderId,\n appId: env.appId,\n measurementId: env.measurementId,\n };\n return initializeApp(firebaseConfig);\n }\n};\n\nconst getFirebaseMessaging = async (\n env: PushNotificationEnv,\n): Promise<Messaging | null> => {\n const supported = await getPushAvailability();\n if (!supported) {\n return null;\n }\n\n const app = await createFirebaseApp(env);\n return getMessaging(app);\n};\n\n/**\n * Creates a registration token for Firebase Cloud Messaging.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with the registration token or null if an error occurs.\n */\nexport async function createRegToken(\n env: PushNotificationEnv,\n): Promise<string | null> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const token = await getToken(messaging, {\n serviceWorkerRegistration: self.registration,\n vapidKey: env.vapidKey,\n });\n return token;\n } catch {\n return null;\n }\n}\n\n/**\n * Deletes the Firebase Cloud Messaging registration token.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.\n */\nexport async function deleteRegToken(\n env: PushNotificationEnv,\n): Promise<boolean> {\n try {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return true;\n }\n\n await deleteToken(messaging);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Service Worker Listener for when push notifications are received.\n * @param env - push notification environment\n * @param handler - handler to actually showing notification, MUST BE PROVEDED\n * @returns unsubscribe handler\n */\nexport async function listenToPushNotificationsReceived(\n env: PushNotificationEnv,\n handler: (notification: Types.INotification) => void | Promise<void>,\n): Promise<(() => void) | null> {\n const messaging = await getFirebaseMessaging(env);\n if (!messaging) {\n return null;\n }\n\n const unsubscribePushNotifications = onBackgroundMessage(\n messaging,\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (payload: MessagePayload) => {\n try {\n const data: Types.UnprocessedOnChainRawNotification | undefined =\n payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;\n\n if (!data) {\n return;\n }\n\n const notificationData = toRawOnChainNotification(data);\n const notification = Processors.processNotification(notificationData);\n await handler(notification);\n } catch (error) {\n // Do Nothing, cannot parse a bad notification\n log.error('Unable to send push notification:', {\n notification: payload?.data?.data,\n error,\n });\n throw new Error('Unable to send push notification');\n }\n },\n );\n\n const unsubscribe = () => unsubscribePushNotifications();\n return unsubscribe;\n}\n\n/**\n * Service Worker Listener for when a notification is clicked\n *\n * @param handler - listen to NotificationEvent from the service worker\n * @returns unsubscribe handler\n */\nexport function listenToPushNotificationsClicked(\n handler: (e: NotificationEvent, notification?: Types.INotification) => void,\n) {\n const clickHandler = (event: NotificationEvent) => {\n // Get Data\n const data: Types.INotification = event?.notification?.data;\n handler(event, data);\n };\n\n self.addEventListener('notificationclick', clickHandler);\n const unsubscribe = () =>\n self.removeEventListener('notificationclick', clickHandler);\n return unsubscribe;\n}\n"]}
|
|
@@ -26,9 +26,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
26
26
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
27
|
};
|
|
28
28
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.updateTriggerPushNotifications = exports.deactivatePushNotifications = exports.activatePushNotifications = exports.updateLinksAPI = exports.getPushNotificationLinks = void 0;
|
|
29
|
+
exports.listenToPushNotifications = exports.updateTriggerPushNotifications = exports.deactivatePushNotifications = exports.activatePushNotifications = exports.updateLinksAPI = exports.getPushNotificationLinks = void 0;
|
|
30
30
|
const loglevel_1 = __importDefault(require("loglevel"));
|
|
31
31
|
const endpoints = __importStar(require("./endpoints.cjs"));
|
|
32
|
+
const push_web_1 = require("./push/push-web.cjs");
|
|
32
33
|
/**
|
|
33
34
|
* Fetches push notification links from a remote endpoint using a BearerToken for authorization.
|
|
34
35
|
*
|
|
@@ -63,7 +64,9 @@ exports.getPushNotificationLinks = getPushNotificationLinks;
|
|
|
63
64
|
async function updateLinksAPI(bearerToken, triggers, regTokens) {
|
|
64
65
|
try {
|
|
65
66
|
const body = {
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
66
68
|
trigger_ids: triggers,
|
|
69
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
67
70
|
registration_tokens: regTokens,
|
|
68
71
|
};
|
|
69
72
|
const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {
|
|
@@ -88,12 +91,12 @@ exports.updateLinksAPI = updateLinksAPI;
|
|
|
88
91
|
* @returns A promise that resolves with an object containing the success status and the BearerToken token.
|
|
89
92
|
*/
|
|
90
93
|
async function activatePushNotifications(params) {
|
|
91
|
-
const { bearerToken, triggers, env, createRegToken, platform } = params;
|
|
94
|
+
const { bearerToken, triggers, env, createRegToken, platform, fcmToken } = params;
|
|
92
95
|
const notificationLinks = await getPushNotificationLinks(bearerToken);
|
|
93
96
|
if (!notificationLinks) {
|
|
94
97
|
return null;
|
|
95
98
|
}
|
|
96
|
-
const regToken = await createRegToken(env).catch(() => null);
|
|
99
|
+
const regToken = fcmToken ?? (await createRegToken(env).catch(() => null));
|
|
97
100
|
if (!regToken) {
|
|
98
101
|
return null;
|
|
99
102
|
}
|
|
@@ -169,4 +172,26 @@ async function updateTriggerPushNotifications(params) {
|
|
|
169
172
|
};
|
|
170
173
|
}
|
|
171
174
|
exports.updateTriggerPushNotifications = updateTriggerPushNotifications;
|
|
175
|
+
/**
|
|
176
|
+
* Listens to push notifications and invokes the provided callback function with the received notification data.
|
|
177
|
+
*
|
|
178
|
+
* @param params - listen params
|
|
179
|
+
* @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.
|
|
180
|
+
*/
|
|
181
|
+
async function listenToPushNotifications(params) {
|
|
182
|
+
const { env, listenToPushReceived, listenToPushClicked } = params;
|
|
183
|
+
/*
|
|
184
|
+
Push notifications require 2 listeners that need tracking (when creating and for tearing down):
|
|
185
|
+
1. handling receiving a push notification (and the content we want to display)
|
|
186
|
+
2. handling when a user clicks on a push notification
|
|
187
|
+
*/
|
|
188
|
+
const unsubscribePushNotifications = await (0, push_web_1.listenToPushNotificationsReceived)(env, listenToPushReceived);
|
|
189
|
+
const unsubscribeNotificationClicks = (0, push_web_1.listenToPushNotificationsClicked)(listenToPushClicked);
|
|
190
|
+
const unsubscribe = () => {
|
|
191
|
+
unsubscribePushNotifications?.();
|
|
192
|
+
unsubscribeNotificationClicks();
|
|
193
|
+
};
|
|
194
|
+
return unsubscribe;
|
|
195
|
+
}
|
|
196
|
+
exports.listenToPushNotifications = listenToPushNotifications;
|
|
172
197
|
//# sourceMappingURL=services.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.cjs","sourceRoot":"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AAmC,GAAG,MAAM,cAAc,CAC9D,WAAW,EACX,QAAQ,EACR,iBAAiB,CAAC,mBAAmB,CACtC,CAAC;IAEF,OAAO;QACL,mCAAmC;QACnC,QAAQ,EAAE,WAAW,IAAI,IAAI;KAC9B,CAAC;AACJ,CAAC;AAjDD,wEAiDC","sourcesContent":["import log from 'loglevel';\n\nimport * as endpoints from './endpoints';\nimport type { PushNotificationEnv } from '../types';\nimport type {\n CreateRegToken,\n DeleteRegToken,\n} from '../types/push-service-interface';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n trigger_ids: string[];\n registration_tokens: RegToken[];\n};\n\n/**\n * Fetches push notification links from a remote endpoint using a BearerToken for authorization.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @returns A promise that resolves with the links result or null if an error occurs.\n */\nexport async function getPushNotificationLinks(\n bearerToken: string,\n): Promise<LinksResult | null> {\n try {\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n headers: { Authorization: `Bearer ${bearerToken}` },\n });\n if (!response.ok) {\n log.error('Failed to fetch the push notification links');\n throw new Error('Failed to fetch the push notification links');\n }\n return response.json() as Promise<LinksResult>;\n } catch (error) {\n log.error('Failed to fetch the push notification links', error);\n return null;\n }\n}\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n trigger_ids: triggers,\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n\n if (!notificationLinks) {\n return null;\n }\n\n const regToken = await createRegToken(env).catch(() => null);\n if (!regToken) {\n return null;\n }\n\n const newRegTokens = new Set(notificationLinks.registration_tokens);\n newRegTokens.add({ token: regToken, platform });\n\n await updateLinksAPI(bearerToken, triggers, Array.from(newRegTokens));\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token and unlinking triggers.\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, bearerToken, triggers, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return false;\n }\n\n const filteredRegTokens = notificationLinks.registration_tokens.filter(\n (r) => r.token !== regToken,\n );\n\n const isTokenRemovedFromAPI = await updateLinksAPI(\n bearerToken,\n triggers,\n filteredRegTokens,\n );\n if (!isTokenRemovedFromAPI) {\n return false;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n isTriggersLinkedToPushNotifications: boolean;\n fcmToken?: string | null;\n}> {\n const {\n bearerToken,\n regToken,\n triggers,\n createRegToken,\n platform,\n deleteRegToken,\n env,\n } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return { isTriggersLinkedToPushNotifications: false };\n }\n // Create new registration token if doesn't exist\n const hasRegToken = Boolean(\n regToken &&\n notificationLinks.registration_tokens.some((r) => r.token === regToken),\n );\n\n let newRegToken: string | null = null;\n if (!hasRegToken) {\n await deleteRegToken(env);\n newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n notificationLinks.registration_tokens.push({\n token: newRegToken,\n platform,\n });\n }\n\n const isTriggersLinkedToPushNotifications = await updateLinksAPI(\n bearerToken,\n triggers,\n notificationLinks.registration_tokens,\n );\n\n return {\n isTriggersLinkedToPushNotifications,\n fcmToken: newRegToken ?? null,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA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G,MAAM,cAAc,CAC9D,WAAW,EACX,QAAQ,EACR,iBAAiB,CAAC,mBAAmB,CACtC,CAAC;IAEF,OAAO;QACL,mCAAmC;QACnC,QAAQ,EAAE,WAAW,IAAI,IAAI;KAC9B,CAAC;AACJ,CAAC;AAjDD,wEAiDC;AAaD;;;;;GAKG;AACI,KAAK,UAAU,yBAAyB,CAC7C,MAAuC;IAEvC,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,GAAG,MAAM,CAAC;IAElE;;;;MAIE;IACF,MAAM,4BAA4B,GAAG,MAAM,IAAA,4CAAiC,EAC1E,GAAG,EACH,oBAAoB,CACrB,CAAC;IACF,MAAM,6BAA6B,GACjC,IAAA,2CAAgC,EAAC,mBAAmB,CAAC,CAAC;IAExD,MAAM,WAAW,GAAG,GAAG,EAAE;QACvB,4BAA4B,EAAE,EAAE,CAAC;QACjC,6BAA6B,EAAE,CAAC;IAClC,CAAC,CAAC;IAEF,OAAO,WAAW,CAAC;AACrB,CAAC;AAvBD,8DAuBC","sourcesContent":["import log from 'loglevel';\n\nimport type { Types } from '../../NotificationServicesController';\nimport type { PushNotificationEnv } from '../types';\nimport * as endpoints from './endpoints';\nimport type { CreateRegToken, DeleteRegToken } from './push';\nimport {\n listenToPushNotificationsClicked,\n listenToPushNotificationsReceived,\n} from './push/push-web';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: string[];\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: RegToken[];\n};\n\n/**\n * Fetches push notification links from a remote endpoint using a BearerToken for authorization.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @returns A promise that resolves with the links result or null if an error occurs.\n */\nexport async function getPushNotificationLinks(\n bearerToken: string,\n): Promise<LinksResult | null> {\n try {\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n headers: { Authorization: `Bearer ${bearerToken}` },\n });\n if (!response.ok) {\n log.error('Failed to fetch the push notification links');\n throw new Error('Failed to fetch the push notification links');\n }\n return response.json() as Promise<LinksResult>;\n } catch (error) {\n log.error('Failed to fetch the push notification links', error);\n return null;\n }\n}\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: triggers,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n fcmToken?: string;\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform, fcmToken } =\n params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n\n if (!notificationLinks) {\n return null;\n }\n\n const regToken = fcmToken ?? (await createRegToken(env).catch(() => null));\n if (!regToken) {\n return null;\n }\n\n const newRegTokens = new Set(notificationLinks.registration_tokens);\n newRegTokens.add({ token: regToken, platform });\n\n await updateLinksAPI(bearerToken, triggers, Array.from(newRegTokens));\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token and unlinking triggers.\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, bearerToken, triggers, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return false;\n }\n\n const filteredRegTokens = notificationLinks.registration_tokens.filter(\n (r) => r.token !== regToken,\n );\n\n const isTokenRemovedFromAPI = await updateLinksAPI(\n bearerToken,\n triggers,\n filteredRegTokens,\n );\n if (!isTokenRemovedFromAPI) {\n return false;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n isTriggersLinkedToPushNotifications: boolean;\n fcmToken?: string | null;\n}> {\n const {\n bearerToken,\n regToken,\n triggers,\n createRegToken,\n platform,\n deleteRegToken,\n env,\n } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return { isTriggersLinkedToPushNotifications: false };\n }\n // Create new registration token if doesn't exist\n const hasRegToken = Boolean(\n regToken &&\n notificationLinks.registration_tokens.some((r) => r.token === regToken),\n );\n\n let newRegToken: string | null = null;\n if (!hasRegToken) {\n await deleteRegToken(env);\n newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n notificationLinks.registration_tokens.push({\n token: newRegToken,\n platform,\n });\n }\n\n const isTriggersLinkedToPushNotifications = await updateLinksAPI(\n bearerToken,\n triggers,\n notificationLinks.registration_tokens,\n );\n\n return {\n isTriggersLinkedToPushNotifications,\n fcmToken: newRegToken ?? null,\n };\n}\n\ntype ListenToPushNotificationsParams = {\n env: PushNotificationEnv;\n listenToPushReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n listenToPushClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n};\n\n/**\n * Listens to push notifications and invokes the provided callback function with the received notification data.\n *\n * @param params - listen params\n * @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.\n */\nexport async function listenToPushNotifications(\n params: ListenToPushNotificationsParams,\n): Promise<() => void> {\n const { env, listenToPushReceived, listenToPushClicked } = params;\n\n /*\n Push notifications require 2 listeners that need tracking (when creating and for tearing down):\n 1. handling receiving a push notification (and the content we want to display)\n 2. handling when a user clicks on a push notification\n */\n const unsubscribePushNotifications = await listenToPushNotificationsReceived(\n env,\n listenToPushReceived,\n );\n const unsubscribeNotificationClicks =\n listenToPushNotificationsClicked(listenToPushClicked);\n\n const unsubscribe = () => {\n unsubscribePushNotifications?.();\n unsubscribeNotificationClicks();\n };\n\n return unsubscribe;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { Types } from "../../NotificationServicesController/index.cjs";
|
|
1
2
|
import type { PushNotificationEnv } from "../types/index.cjs";
|
|
2
|
-
import type { CreateRegToken, DeleteRegToken } from "
|
|
3
|
+
import type { CreateRegToken, DeleteRegToken } from "./push/index.cjs";
|
|
3
4
|
export type RegToken = {
|
|
4
5
|
token: string;
|
|
5
6
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
@@ -33,6 +34,7 @@ type ActivatePushNotificationsParams = {
|
|
|
33
34
|
env: PushNotificationEnv;
|
|
34
35
|
createRegToken: CreateRegToken;
|
|
35
36
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
37
|
+
fcmToken?: string;
|
|
36
38
|
};
|
|
37
39
|
/**
|
|
38
40
|
* Enables push notifications by registering the device and linking triggers.
|
|
@@ -78,5 +80,17 @@ export declare function updateTriggerPushNotifications(params: UpdateTriggerPush
|
|
|
78
80
|
isTriggersLinkedToPushNotifications: boolean;
|
|
79
81
|
fcmToken?: string | null;
|
|
80
82
|
}>;
|
|
83
|
+
type ListenToPushNotificationsParams = {
|
|
84
|
+
env: PushNotificationEnv;
|
|
85
|
+
listenToPushReceived: (notification: Types.INotification) => void | Promise<void>;
|
|
86
|
+
listenToPushClicked: (event: NotificationEvent, notification?: Types.INotification) => void;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Listens to push notifications and invokes the provided callback function with the received notification data.
|
|
90
|
+
*
|
|
91
|
+
* @param params - listen params
|
|
92
|
+
* @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.
|
|
93
|
+
*/
|
|
94
|
+
export declare function listenToPushNotifications(params: ListenToPushNotificationsParams): Promise<() => void>;
|
|
81
95
|
export {};
|
|
82
96
|
//# sourceMappingURL=services.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesP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AAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,iCAAiC,GACxC,OAAO,CAAC,OAAO,CAAC,CAgClB;AAED,KAAK,oCAAoC,GAAG;IAE1C,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAG/C,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,MAAM,EAAE,oCAAoC,GAC3C,OAAO,CAAC;IACT,mCAAmC,EAAE,OAAO,CAAC;IAC7C,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B,CAAC,CA4CD;AAED,KAAK,+BAA+B,GAAG;IACrC,GAAG,EAAE,mBAAmB,CAAC;IACzB,oBAAoB,EAAE,CACpB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,mBAAmB,EAAE,CACnB,KAAK,EAAE,iBAAiB,EACxB,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAC/B,IAAI,CAAC;CACX,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,IAAI,CAAC,CAqBrB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { Types } from "../../NotificationServicesController/index.mjs";
|
|
1
2
|
import type { PushNotificationEnv } from "../types/index.mjs";
|
|
2
|
-
import type { CreateRegToken, DeleteRegToken } from "
|
|
3
|
+
import type { CreateRegToken, DeleteRegToken } from "./push/index.mjs";
|
|
3
4
|
export type RegToken = {
|
|
4
5
|
token: string;
|
|
5
6
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
@@ -33,6 +34,7 @@ type ActivatePushNotificationsParams = {
|
|
|
33
34
|
env: PushNotificationEnv;
|
|
34
35
|
createRegToken: CreateRegToken;
|
|
35
36
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
37
|
+
fcmToken?: string;
|
|
36
38
|
};
|
|
37
39
|
/**
|
|
38
40
|
* Enables push notifications by registering the device and linking triggers.
|
|
@@ -78,5 +80,17 @@ export declare function updateTriggerPushNotifications(params: UpdateTriggerPush
|
|
|
78
80
|
isTriggersLinkedToPushNotifications: boolean;
|
|
79
81
|
fcmToken?: string | null;
|
|
80
82
|
}>;
|
|
83
|
+
type ListenToPushNotificationsParams = {
|
|
84
|
+
env: PushNotificationEnv;
|
|
85
|
+
listenToPushReceived: (notification: Types.INotification) => void | Promise<void>;
|
|
86
|
+
listenToPushClicked: (event: NotificationEvent, notification?: Types.INotification) => void;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Listens to push notifications and invokes the provided callback function with the received notification data.
|
|
90
|
+
*
|
|
91
|
+
* @param params - listen params
|
|
92
|
+
* @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.
|
|
93
|
+
*/
|
|
94
|
+
export declare function listenToPushNotifications(params: ListenToPushNotificationsParams): Promise<() => void>;
|
|
81
95
|
export {};
|
|
82
96
|
//# sourceMappingURL=services.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,uDAA6C;AAClE,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAAiB;AAEpD,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C,GACxC,OAAO,CAAC,OAAO,CAAC,CAgClB;AAED,KAAK,oCAAoC,GAAG;IAE1C,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAG/C,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,MAAM,EAAE,oCAAoC,GAC3C,OAAO,CAAC;IACT,mCAAmC,EAAE,OAAO,CAAC;IAC7C,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B,CAAC,CA4CD;AAED,KAAK,+BAA+B,GAAG;IACrC,GAAG,EAAE,mBAAmB,CAAC;IACzB,oBAAoB,EAAE,CACpB,YAAY,EAAE,KAAK,CAAC,aAAa,KAC9B,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,mBAAmB,EAAE,CACnB,KAAK,EAAE,iBAAiB,EACxB,YAAY,CAAC,EAAE,KAAK,CAAC,aAAa,KAC/B,IAAI,CAAC;CACX,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,IAAI,CAAC,CAqBrB"}
|
|
@@ -7,6 +7,7 @@ function $importDefault(module) {
|
|
|
7
7
|
import $log from "loglevel";
|
|
8
8
|
const log = $importDefault($log);
|
|
9
9
|
import * as endpoints from "./endpoints.mjs";
|
|
10
|
+
import { listenToPushNotificationsClicked, listenToPushNotificationsReceived } from "./push/push-web.mjs";
|
|
10
11
|
/**
|
|
11
12
|
* Fetches push notification links from a remote endpoint using a BearerToken for authorization.
|
|
12
13
|
*
|
|
@@ -40,7 +41,9 @@ export async function getPushNotificationLinks(bearerToken) {
|
|
|
40
41
|
export async function updateLinksAPI(bearerToken, triggers, regTokens) {
|
|
41
42
|
try {
|
|
42
43
|
const body = {
|
|
44
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
43
45
|
trigger_ids: triggers,
|
|
46
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
44
47
|
registration_tokens: regTokens,
|
|
45
48
|
};
|
|
46
49
|
const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {
|
|
@@ -64,12 +67,12 @@ export async function updateLinksAPI(bearerToken, triggers, regTokens) {
|
|
|
64
67
|
* @returns A promise that resolves with an object containing the success status and the BearerToken token.
|
|
65
68
|
*/
|
|
66
69
|
export async function activatePushNotifications(params) {
|
|
67
|
-
const { bearerToken, triggers, env, createRegToken, platform } = params;
|
|
70
|
+
const { bearerToken, triggers, env, createRegToken, platform, fcmToken } = params;
|
|
68
71
|
const notificationLinks = await getPushNotificationLinks(bearerToken);
|
|
69
72
|
if (!notificationLinks) {
|
|
70
73
|
return null;
|
|
71
74
|
}
|
|
72
|
-
const regToken = await createRegToken(env).catch(() => null);
|
|
75
|
+
const regToken = fcmToken ?? (await createRegToken(env).catch(() => null));
|
|
73
76
|
if (!regToken) {
|
|
74
77
|
return null;
|
|
75
78
|
}
|
|
@@ -142,4 +145,25 @@ export async function updateTriggerPushNotifications(params) {
|
|
|
142
145
|
fcmToken: newRegToken ?? null,
|
|
143
146
|
};
|
|
144
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Listens to push notifications and invokes the provided callback function with the received notification data.
|
|
150
|
+
*
|
|
151
|
+
* @param params - listen params
|
|
152
|
+
* @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.
|
|
153
|
+
*/
|
|
154
|
+
export async function listenToPushNotifications(params) {
|
|
155
|
+
const { env, listenToPushReceived, listenToPushClicked } = params;
|
|
156
|
+
/*
|
|
157
|
+
Push notifications require 2 listeners that need tracking (when creating and for tearing down):
|
|
158
|
+
1. handling receiving a push notification (and the content we want to display)
|
|
159
|
+
2. handling when a user clicks on a push notification
|
|
160
|
+
*/
|
|
161
|
+
const unsubscribePushNotifications = await listenToPushNotificationsReceived(env, listenToPushReceived);
|
|
162
|
+
const unsubscribeNotificationClicks = listenToPushNotificationsClicked(listenToPushClicked);
|
|
163
|
+
const unsubscribe = () => {
|
|
164
|
+
unsubscribePushNotifications?.();
|
|
165
|
+
unsubscribeNotificationClicks();
|
|
166
|
+
};
|
|
167
|
+
return unsubscribe;
|
|
168
|
+
}
|
|
145
169
|
//# sourceMappingURL=services.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,KAAK,SAAS,wBAAoB;AAoBzC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,WAAmB;IAEnB,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,EAAE;YACnE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE;SACpD,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,GAAG,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;YACzD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;SAChE;QACD,OAAO,QAAQ,CAAC,IAAI,EAA0B,CAAC;KAChD;IAAC,OAAO,KAAK,EAAE;QACd,GAAG,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,WAAmB,EACnB,QAAkB,EAClB,SAAqB;IAErB,IAAI;QACF,MAAM,IAAI,GAAgB;YACxB,WAAW,EAA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,CAAC,KAAK,KAAK,QAAQ,CAAC,CAC1E,CAAC;IAEF,IAAI,WAAW,GAAkB,IAAI,CAAC;IACtC,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;QAC1B,WAAW,GAAG,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;QACxC,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;SAC9D;QACD,iBAAiB,CAAC,mBAAmB,CAAC,IAAI,CAAC;YACzC,KAAK,EAAE,WAAW;YAClB,QAAQ;SACT,CAAC,CAAC;KACJ;IAED,MAAM,mCAAmC,GAAG,MAAM,cAAc,CAC9D,WAAW,EACX,QAAQ,EACR,iBAAiB,CAAC,mBAAmB,CACtC,CAAC;IAEF,OAAO;QACL,mCAAmC;QACnC,QAAQ,EAAE,WAAW,IAAI,IAAI;KAC9B,CAAC;AACJ,CAAC","sourcesContent":["import log from 'loglevel';\n\nimport * as endpoints from './endpoints';\nimport type { PushNotificationEnv } from '../types';\nimport type {\n CreateRegToken,\n DeleteRegToken,\n} from '../types/push-service-interface';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n trigger_ids: string[];\n registration_tokens: RegToken[];\n};\n\n/**\n * Fetches push notification links from a remote endpoint using a BearerToken for authorization.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @returns A promise that resolves with the links result or null if an error occurs.\n */\nexport async function getPushNotificationLinks(\n bearerToken: string,\n): Promise<LinksResult | null> {\n try {\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n headers: { Authorization: `Bearer ${bearerToken}` },\n });\n if (!response.ok) {\n log.error('Failed to fetch the push notification links');\n throw new Error('Failed to fetch the push notification links');\n }\n return response.json() as Promise<LinksResult>;\n } catch (error) {\n log.error('Failed to fetch the push notification links', error);\n return null;\n }\n}\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n trigger_ids: triggers,\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n\n if (!notificationLinks) {\n return null;\n }\n\n const regToken = await createRegToken(env).catch(() => null);\n if (!regToken) {\n return null;\n }\n\n const newRegTokens = new Set(notificationLinks.registration_tokens);\n newRegTokens.add({ token: regToken, platform });\n\n await updateLinksAPI(bearerToken, triggers, Array.from(newRegTokens));\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token and unlinking triggers.\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, bearerToken, triggers, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return false;\n }\n\n const filteredRegTokens = notificationLinks.registration_tokens.filter(\n (r) => r.token !== regToken,\n );\n\n const isTokenRemovedFromAPI = await updateLinksAPI(\n bearerToken,\n triggers,\n filteredRegTokens,\n );\n if (!isTokenRemovedFromAPI) {\n return false;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n isTriggersLinkedToPushNotifications: boolean;\n fcmToken?: string | null;\n}> {\n const {\n bearerToken,\n regToken,\n triggers,\n createRegToken,\n platform,\n deleteRegToken,\n env,\n } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return { isTriggersLinkedToPushNotifications: false };\n }\n // Create new registration token if doesn't exist\n const hasRegToken = Boolean(\n regToken &&\n notificationLinks.registration_tokens.some((r) => r.token === regToken),\n );\n\n let newRegToken: string | null = null;\n if (!hasRegToken) {\n await deleteRegToken(env);\n newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n notificationLinks.registration_tokens.push({\n token: newRegToken,\n platform,\n });\n }\n\n const isTriggersLinkedToPushNotifications = await updateLinksAPI(\n bearerToken,\n triggers,\n notificationLinks.registration_tokens,\n );\n\n return {\n isTriggersLinkedToPushNotifications,\n fcmToken: newRegToken ?? null,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,IAAG,iBAAiB;;AAI3B,OAAO,KAAK,SAAS,wBAAoB;AAEzC,OAAO,EACL,gCAAgC,EAChC,iCAAiC,EAClC,4BAAwB;AAiBzB;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,WAAmB;IAEnB,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,EAAE;YACnE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE;SACpD,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,GAAG,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAC;YACzD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;SAChE;QACD,OAAO,QAAQ,CAAC,IAAI,EAA0B,CAAC;KAChD;IAAC,OAAO,KAAK,EAAE;QACd,GAAG,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,WAAmB,EACnB,QAAkB,EAClB,SAAqB;IAErB,IAAI;QACF,MAAM,IAAI,GAAgB;YACxB,gEAAgE;YAChE,WAAW,EAAE,QAAQ;YACrB,gEAAgE;YAChE,mBAAmB,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E,CAAC,CAAC,CAAC,KAAK,KAAK,QAAQ,CAAC,CAC1E,CAAC;IAEF,IAAI,WAAW,GAAkB,IAAI,CAAC;IACtC,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;QAC1B,WAAW,GAAG,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;QACxC,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;SAC9D;QACD,iBAAiB,CAAC,mBAAmB,CAAC,IAAI,CAAC;YACzC,KAAK,EAAE,WAAW;YAClB,QAAQ;SACT,CAAC,CAAC;KACJ;IAED,MAAM,mCAAmC,GAAG,MAAM,cAAc,CAC9D,WAAW,EACX,QAAQ,EACR,iBAAiB,CAAC,mBAAmB,CACtC,CAAC;IAEF,OAAO;QACL,mCAAmC;QACnC,QAAQ,EAAE,WAAW,IAAI,IAAI;KAC9B,CAAC;AACJ,CAAC;AAaD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,MAAuC;IAEvC,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,GAAG,MAAM,CAAC;IAElE;;;;MAIE;IACF,MAAM,4BAA4B,GAAG,MAAM,iCAAiC,CAC1E,GAAG,EACH,oBAAoB,CACrB,CAAC;IACF,MAAM,6BAA6B,GACjC,gCAAgC,CAAC,mBAAmB,CAAC,CAAC;IAExD,MAAM,WAAW,GAAG,GAAG,EAAE;QACvB,4BAA4B,EAAE,EAAE,CAAC;QACjC,6BAA6B,EAAE,CAAC;IAClC,CAAC,CAAC;IAEF,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import log from 'loglevel';\n\nimport type { Types } from '../../NotificationServicesController';\nimport type { PushNotificationEnv } from '../types';\nimport * as endpoints from './endpoints';\nimport type { CreateRegToken, DeleteRegToken } from './push';\nimport {\n listenToPushNotificationsClicked,\n listenToPushNotificationsReceived,\n} from './push/push-web';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: string[];\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: RegToken[];\n};\n\n/**\n * Fetches push notification links from a remote endpoint using a BearerToken for authorization.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @returns A promise that resolves with the links result or null if an error occurs.\n */\nexport async function getPushNotificationLinks(\n bearerToken: string,\n): Promise<LinksResult | null> {\n try {\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n headers: { Authorization: `Bearer ${bearerToken}` },\n });\n if (!response.ok) {\n log.error('Failed to fetch the push notification links');\n throw new Error('Failed to fetch the push notification links');\n }\n return response.json() as Promise<LinksResult>;\n } catch (error) {\n log.error('Failed to fetch the push notification links', error);\n return null;\n }\n}\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n trigger_ids: triggers,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n fcmToken?: string;\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform, fcmToken } =\n params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n\n if (!notificationLinks) {\n return null;\n }\n\n const regToken = fcmToken ?? (await createRegToken(env).catch(() => null));\n if (!regToken) {\n return null;\n }\n\n const newRegTokens = new Set(notificationLinks.registration_tokens);\n newRegTokens.add({ token: regToken, platform });\n\n await updateLinksAPI(bearerToken, triggers, Array.from(newRegTokens));\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token and unlinking triggers.\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, bearerToken, triggers, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return false;\n }\n\n const filteredRegTokens = notificationLinks.registration_tokens.filter(\n (r) => r.token !== regToken,\n );\n\n const isTokenRemovedFromAPI = await updateLinksAPI(\n bearerToken,\n triggers,\n filteredRegTokens,\n );\n if (!isTokenRemovedFromAPI) {\n return false;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n regToken: string;\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n isTriggersLinkedToPushNotifications: boolean;\n fcmToken?: string | null;\n}> {\n const {\n bearerToken,\n regToken,\n triggers,\n createRegToken,\n platform,\n deleteRegToken,\n env,\n } = params;\n\n const notificationLinks = await getPushNotificationLinks(bearerToken);\n if (!notificationLinks) {\n return { isTriggersLinkedToPushNotifications: false };\n }\n // Create new registration token if doesn't exist\n const hasRegToken = Boolean(\n regToken &&\n notificationLinks.registration_tokens.some((r) => r.token === regToken),\n );\n\n let newRegToken: string | null = null;\n if (!hasRegToken) {\n await deleteRegToken(env);\n newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n notificationLinks.registration_tokens.push({\n token: newRegToken,\n platform,\n });\n }\n\n const isTriggersLinkedToPushNotifications = await updateLinksAPI(\n bearerToken,\n triggers,\n notificationLinks.registration_tokens,\n );\n\n return {\n isTriggersLinkedToPushNotifications,\n fcmToken: newRegToken ?? null,\n };\n}\n\ntype ListenToPushNotificationsParams = {\n env: PushNotificationEnv;\n listenToPushReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n listenToPushClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n};\n\n/**\n * Listens to push notifications and invokes the provided callback function with the received notification data.\n *\n * @param params - listen params\n * @returns A promise that resolves to an unsubscribe function to stop listening to push notifications.\n */\nexport async function listenToPushNotifications(\n params: ListenToPushNotificationsParams,\n): Promise<() => void> {\n const { env, listenToPushReceived, listenToPushClicked } = params;\n\n /*\n Push notifications require 2 listeners that need tracking (when creating and for tearing down):\n 1. handling receiving a push notification (and the content we want to display)\n 2. handling when a user clicks on a push notification\n */\n const unsubscribePushNotifications = await listenToPushNotificationsReceived(\n env,\n listenToPushReceived,\n );\n const unsubscribeNotificationClicks =\n listenToPushNotificationsClicked(listenToPushClicked);\n\n const unsubscribe = () => {\n unsubscribePushNotifications?.();\n unsubscribeNotificationClicks();\n };\n\n return unsubscribe;\n}\n"]}
|