@cobbai/react-native-sdk 1.0.0-beta.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.
Files changed (143) hide show
  1. package/CobbaiMobileRnSdk.podspec +22 -0
  2. package/LICENSE +32 -0
  3. package/README.md +386 -0
  4. package/dist/ChatPlaceholder.d.ts +13 -0
  5. package/dist/ChatPlaceholder.d.ts.map +1 -0
  6. package/dist/ChatPlaceholder.js +87 -0
  7. package/dist/CobbaiChatScreen.d.ts +4 -0
  8. package/dist/CobbaiChatScreen.d.ts.map +1 -0
  9. package/dist/CobbaiChatScreen.js +196 -0
  10. package/dist/CobbaiInAppBanner.d.ts +15 -0
  11. package/dist/CobbaiInAppBanner.d.ts.map +1 -0
  12. package/dist/CobbaiInAppBanner.js +159 -0
  13. package/dist/CobbaiLauncher.d.ts +19 -0
  14. package/dist/CobbaiLauncher.d.ts.map +1 -0
  15. package/dist/CobbaiLauncher.js +149 -0
  16. package/dist/CobbaiWebView.d.ts +28 -0
  17. package/dist/CobbaiWebView.d.ts.map +1 -0
  18. package/dist/CobbaiWebView.js +141 -0
  19. package/dist/adapters/expoAdapter.d.ts +85 -0
  20. package/dist/adapters/expoAdapter.d.ts.map +1 -0
  21. package/dist/adapters/expoAdapter.js +152 -0
  22. package/dist/adapters/firebaseAdapter.d.ts +41 -0
  23. package/dist/adapters/firebaseAdapter.d.ts.map +1 -0
  24. package/dist/adapters/firebaseAdapter.js +139 -0
  25. package/dist/adapters/iosRelayAdapter.d.ts +26 -0
  26. package/dist/adapters/iosRelayAdapter.d.ts.map +1 -0
  27. package/dist/adapters/iosRelayAdapter.js +101 -0
  28. package/dist/androidKeyboardFrame.d.ts +16 -0
  29. package/dist/androidKeyboardFrame.d.ts.map +1 -0
  30. package/dist/androidKeyboardFrame.js +34 -0
  31. package/dist/bridge/messages.d.ts +20 -0
  32. package/dist/bridge/messages.d.ts.map +1 -0
  33. package/dist/bridge/messages.js +20 -0
  34. package/dist/bridge/nativeEvent.d.ts +10 -0
  35. package/dist/bridge/nativeEvent.d.ts.map +1 -0
  36. package/dist/bridge/nativeEvent.js +15 -0
  37. package/dist/bridge/parser.d.ts +29 -0
  38. package/dist/bridge/parser.d.ts.map +1 -0
  39. package/dist/bridge/parser.js +109 -0
  40. package/dist/chatPresentation.d.ts +19 -0
  41. package/dist/chatPresentation.d.ts.map +1 -0
  42. package/dist/chatPresentation.js +51 -0
  43. package/dist/chatScreen/useInAppBannerQueue.d.ts +22 -0
  44. package/dist/chatScreen/useInAppBannerQueue.d.ts.map +1 -0
  45. package/dist/chatScreen/useInAppBannerQueue.js +60 -0
  46. package/dist/chatScreen/useKeyboardFrame.d.ts +14 -0
  47. package/dist/chatScreen/useKeyboardFrame.d.ts.map +1 -0
  48. package/dist/chatScreen/useKeyboardFrame.js +63 -0
  49. package/dist/chatScreen/useLauncherPresentation.d.ts +20 -0
  50. package/dist/chatScreen/useLauncherPresentation.d.ts.map +1 -0
  51. package/dist/chatScreen/useLauncherPresentation.js +76 -0
  52. package/dist/chatScreen/useNativeToWebSync.d.ts +17 -0
  53. package/dist/chatScreen/useNativeToWebSync.d.ts.map +1 -0
  54. package/dist/chatScreen/useNativeToWebSync.js +36 -0
  55. package/dist/chatScreen/usePushIntegration.d.ts +19 -0
  56. package/dist/chatScreen/usePushIntegration.d.ts.map +1 -0
  57. package/dist/chatScreen/usePushIntegration.js +129 -0
  58. package/dist/chatScreen/useReadyLifecycle.d.ts +33 -0
  59. package/dist/chatScreen/useReadyLifecycle.d.ts.map +1 -0
  60. package/dist/chatScreen/useReadyLifecycle.js +138 -0
  61. package/dist/chatScreen/useSheetPresentation.d.ts +25 -0
  62. package/dist/chatScreen/useSheetPresentation.d.ts.map +1 -0
  63. package/dist/chatScreen/useSheetPresentation.js +98 -0
  64. package/dist/chatUnavailable.d.ts +23 -0
  65. package/dist/chatUnavailable.d.ts.map +1 -0
  66. package/dist/chatUnavailable.js +36 -0
  67. package/dist/externalLinks.d.ts +4 -0
  68. package/dist/externalLinks.d.ts.map +1 -0
  69. package/dist/externalLinks.js +48 -0
  70. package/dist/host/buildHostHtml.d.ts +7 -0
  71. package/dist/host/buildHostHtml.d.ts.map +1 -0
  72. package/dist/host/buildHostHtml.js +101 -0
  73. package/dist/host/hostPageKey.d.ts +7 -0
  74. package/dist/host/hostPageKey.d.ts.map +1 -0
  75. package/dist/host/hostPageKey.js +18 -0
  76. package/dist/inAppBanner.d.ts +19 -0
  77. package/dist/inAppBanner.d.ts.map +1 -0
  78. package/dist/inAppBanner.js +42 -0
  79. package/dist/index.d.ts +10 -0
  80. package/dist/index.d.ts.map +1 -0
  81. package/dist/index.js +32 -0
  82. package/dist/launcher.d.ts +25 -0
  83. package/dist/launcher.d.ts.map +1 -0
  84. package/dist/launcher.js +55 -0
  85. package/dist/launcherGlyph.d.ts +2 -0
  86. package/dist/launcherGlyph.d.ts.map +1 -0
  87. package/dist/launcherGlyph.js +5 -0
  88. package/dist/openChatScreen.d.ts +13 -0
  89. package/dist/openChatScreen.d.ts.map +1 -0
  90. package/dist/openChatScreen.js +63 -0
  91. package/dist/push.d.ts +59 -0
  92. package/dist/push.d.ts.map +1 -0
  93. package/dist/push.js +309 -0
  94. package/dist/pushIntegration.d.ts +76 -0
  95. package/dist/pushIntegration.d.ts.map +1 -0
  96. package/dist/pushIntegration.js +244 -0
  97. package/dist/pushLogout.d.ts +57 -0
  98. package/dist/pushLogout.d.ts.map +1 -0
  99. package/dist/pushLogout.js +225 -0
  100. package/dist/types.d.ts +42 -0
  101. package/dist/types.d.ts.map +1 -0
  102. package/dist/types.js +2 -0
  103. package/dist/version.d.ts +8 -0
  104. package/dist/version.d.ts.map +1 -0
  105. package/dist/version.js +10 -0
  106. package/ios/CobbaiPush.m +96 -0
  107. package/ios/CobbaiPushRelay.h +59 -0
  108. package/ios/CobbaiPushRelay.m +364 -0
  109. package/package.json +69 -0
  110. package/src/ChatPlaceholder.tsx +132 -0
  111. package/src/CobbaiChatScreen.tsx +348 -0
  112. package/src/CobbaiInAppBanner.tsx +237 -0
  113. package/src/CobbaiLauncher.tsx +223 -0
  114. package/src/CobbaiWebView.tsx +242 -0
  115. package/src/adapters/expoAdapter.ts +227 -0
  116. package/src/adapters/firebaseAdapter.ts +201 -0
  117. package/src/adapters/iosRelayAdapter.ts +137 -0
  118. package/src/androidKeyboardFrame.ts +56 -0
  119. package/src/bridge/messages.ts +24 -0
  120. package/src/bridge/nativeEvent.ts +12 -0
  121. package/src/bridge/parser.ts +159 -0
  122. package/src/chatPresentation.ts +73 -0
  123. package/src/chatScreen/useInAppBannerQueue.ts +91 -0
  124. package/src/chatScreen/useKeyboardFrame.ts +89 -0
  125. package/src/chatScreen/useLauncherPresentation.ts +121 -0
  126. package/src/chatScreen/useNativeToWebSync.ts +54 -0
  127. package/src/chatScreen/usePushIntegration.ts +191 -0
  128. package/src/chatScreen/useReadyLifecycle.ts +186 -0
  129. package/src/chatScreen/useSheetPresentation.ts +147 -0
  130. package/src/chatUnavailable.ts +58 -0
  131. package/src/externalLinks.ts +56 -0
  132. package/src/host/buildHostHtml.ts +117 -0
  133. package/src/host/hostPageKey.ts +17 -0
  134. package/src/inAppBanner.ts +58 -0
  135. package/src/index.ts +53 -0
  136. package/src/launcher.ts +79 -0
  137. package/src/launcherGlyph.ts +3 -0
  138. package/src/openChatScreen.ts +78 -0
  139. package/src/push.ts +424 -0
  140. package/src/pushIntegration.ts +338 -0
  141. package/src/pushLogout.ts +277 -0
  142. package/src/types.ts +46 -0
  143. package/src/version.ts +8 -0
package/dist/push.js ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getForegroundPresentationState = getForegroundPresentationState;
4
+ exports.subscribePushStore = subscribePushStore;
5
+ exports.getPushStoreSnapshot = getPushStoreSnapshot;
6
+ exports.setMountedChatId = setMountedChatId;
7
+ exports.clearMountedChatId = clearMountedChatId;
8
+ exports.setPushConnected = setPushConnected;
9
+ exports.setPushBannerEnabled = setPushBannerEnabled;
10
+ exports.setPushBannerPresenter = setPushBannerPresenter;
11
+ exports.clearPendingUnregister = clearPendingUnregister;
12
+ exports.clearPendingOpen = clearPendingOpen;
13
+ exports.setPushToken = setPushToken;
14
+ exports.clearPushToken = clearPushToken;
15
+ exports.isCobbaiPush = isCobbaiPush;
16
+ exports.handleCobbaiPushTap = handleCobbaiPushTap;
17
+ exports.openConversationFromBanner = openConversationFromBanner;
18
+ exports.handleCobbaiPushInForeground = handleCobbaiPushInForeground;
19
+ exports.__resetPushStoreForTests = __resetPushStoreForTests;
20
+ const inAppBanner_1 = require("./inAppBanner");
21
+ const STORE_KEY = '__COBBAI_PUSH_STORE__';
22
+ // Enough for any burst of duplicate deliveries; a tap is never delivered twice far apart.
23
+ const MAX_HANDLED_TAPS = 100;
24
+ const TOKEN_PATTERN = /^[A-Za-z0-9:_\-.]{1,4096}$/;
25
+ const POSITIVE_INTEGER_STRING_PATTERN = /^[1-9][0-9]*$/;
26
+ function getPushStore() {
27
+ const globalObject = globalThis;
28
+ if (!globalObject[STORE_KEY]) {
29
+ globalObject[STORE_KEY] = {
30
+ token: null,
31
+ pendingUnregister: null,
32
+ pendingOpen: null,
33
+ mountedChatId: null,
34
+ connected: false,
35
+ bannerEnabled: true,
36
+ showBanner: null,
37
+ handledTaps: [],
38
+ listeners: new Set(),
39
+ };
40
+ }
41
+ return globalObject[STORE_KEY];
42
+ }
43
+ function notifyPushStore() {
44
+ const store = getPushStore();
45
+ store.listeners.forEach((listener) => listener());
46
+ }
47
+ function clonePushToken(token) {
48
+ return {
49
+ token: token.token,
50
+ provider: token.provider,
51
+ apnsEnvironment: token.apnsEnvironment,
52
+ };
53
+ }
54
+ function arePushTokensEqual(left, right) {
55
+ if (!left || !right) {
56
+ return left === right;
57
+ }
58
+ return (left.token === right.token &&
59
+ left.provider === right.provider &&
60
+ left.apnsEnvironment === right.apnsEnvironment);
61
+ }
62
+ function isValidPushToken(token) {
63
+ if (!TOKEN_PATTERN.test(token.token)) {
64
+ return false;
65
+ }
66
+ if (token.provider !== 'apns' && token.provider !== 'fcm') {
67
+ return false;
68
+ }
69
+ if (token.provider === 'apns') {
70
+ return token.apnsEnvironment === 'sandbox' || token.apnsEnvironment === 'production';
71
+ }
72
+ return true;
73
+ }
74
+ function toPushData(data) {
75
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
76
+ return null;
77
+ }
78
+ const record = data;
79
+ if (record.cobbai !== '1') {
80
+ return null;
81
+ }
82
+ if (typeof record.cobbai_chat_id !== 'string' || record.cobbai_chat_id.trim().length === 0) {
83
+ return null;
84
+ }
85
+ const chatId = record.cobbai_chat_id.trim();
86
+ const conversationIdRaw = record.cobbai_conversation_id;
87
+ const messageIdRaw = record.cobbai_message_id;
88
+ if (typeof conversationIdRaw !== 'string' ||
89
+ typeof messageIdRaw !== 'string' ||
90
+ !POSITIVE_INTEGER_STRING_PATTERN.test(conversationIdRaw) ||
91
+ !POSITIVE_INTEGER_STRING_PATTERN.test(messageIdRaw)) {
92
+ return null;
93
+ }
94
+ const conversationId = Number(conversationIdRaw);
95
+ const messageId = Number(messageIdRaw);
96
+ if (!Number.isSafeInteger(conversationId) || !Number.isSafeInteger(messageId)) {
97
+ return null;
98
+ }
99
+ return {
100
+ chatId,
101
+ conversationId,
102
+ messageId,
103
+ };
104
+ }
105
+ function getForegroundPresentationState() {
106
+ const store = getPushStore();
107
+ return {
108
+ mountedChatId: store.mountedChatId,
109
+ connected: store.connected,
110
+ bannerEnabled: store.bannerEnabled && store.showBanner !== null,
111
+ };
112
+ }
113
+ function subscribePushStore(listener) {
114
+ const store = getPushStore();
115
+ store.listeners.add(listener);
116
+ return () => {
117
+ const currentStore = getPushStore();
118
+ currentStore.listeners.delete(listener);
119
+ };
120
+ }
121
+ function getPushStoreSnapshot() {
122
+ const store = getPushStore();
123
+ return {
124
+ token: store.token ? clonePushToken(store.token) : null,
125
+ pendingUnregister: store.pendingUnregister ? clonePushToken(store.pendingUnregister) : null,
126
+ pendingOpen: store.pendingOpen ? { ...store.pendingOpen } : null,
127
+ mountedChatId: store.mountedChatId,
128
+ connected: store.connected,
129
+ bannerEnabled: store.bannerEnabled,
130
+ };
131
+ }
132
+ function setMountedChatId(chatId) {
133
+ const store = getPushStore();
134
+ if (store.mountedChatId === chatId) {
135
+ return;
136
+ }
137
+ store.mountedChatId = chatId;
138
+ notifyPushStore();
139
+ }
140
+ function clearMountedChatId(chatId) {
141
+ const store = getPushStore();
142
+ if (store.mountedChatId !== chatId) {
143
+ return;
144
+ }
145
+ store.mountedChatId = null;
146
+ notifyPushStore();
147
+ }
148
+ function setPushConnected(connected) {
149
+ const store = getPushStore();
150
+ if (store.connected === connected) {
151
+ return;
152
+ }
153
+ store.connected = connected;
154
+ notifyPushStore();
155
+ }
156
+ function setPushBannerEnabled(enabled) {
157
+ const store = getPushStore();
158
+ if (store.bannerEnabled === enabled) {
159
+ return;
160
+ }
161
+ store.bannerEnabled = enabled;
162
+ notifyPushStore();
163
+ }
164
+ function setPushBannerPresenter(showBanner) {
165
+ const store = getPushStore();
166
+ if (store.showBanner === showBanner) {
167
+ return;
168
+ }
169
+ store.showBanner = showBanner;
170
+ notifyPushStore();
171
+ }
172
+ function clearPendingUnregister(token) {
173
+ const store = getPushStore();
174
+ if (!arePushTokensEqual(store.pendingUnregister, token)) {
175
+ return;
176
+ }
177
+ store.pendingUnregister = null;
178
+ notifyPushStore();
179
+ }
180
+ function clearPendingOpen(pendingOpen) {
181
+ const store = getPushStore();
182
+ if (!store.pendingOpen ||
183
+ store.pendingOpen.chatId !== pendingOpen.chatId ||
184
+ store.pendingOpen.conversationId !== pendingOpen.conversationId) {
185
+ return;
186
+ }
187
+ store.pendingOpen = null;
188
+ notifyPushStore();
189
+ }
190
+ function setPushToken(token) {
191
+ if (!isValidPushToken(token)) {
192
+ if (__DEV__) {
193
+ console.warn('[cobbai][push] ignored invalid token payload');
194
+ }
195
+ return false;
196
+ }
197
+ const store = getPushStore();
198
+ const nextToken = clonePushToken(token);
199
+ const hadPendingUnregisterForSameToken = store.pendingUnregister != null && arePushTokensEqual(store.pendingUnregister, nextToken);
200
+ const tokenChanged = !arePushTokensEqual(store.token, nextToken);
201
+ store.token = nextToken;
202
+ if (hadPendingUnregisterForSameToken) {
203
+ store.pendingUnregister = null;
204
+ }
205
+ if (tokenChanged || hadPendingUnregisterForSameToken) {
206
+ notifyPushStore();
207
+ }
208
+ return true;
209
+ }
210
+ function clearPushToken() {
211
+ const store = getPushStore();
212
+ if (!store.token) {
213
+ return;
214
+ }
215
+ store.pendingUnregister = clonePushToken(store.token);
216
+ store.token = null;
217
+ notifyPushStore();
218
+ }
219
+ function isCobbaiPush(data) {
220
+ return toPushData(data) != null;
221
+ }
222
+ /**
223
+ * A tap on a notification, the tap that launched the app included. Returns true for a Cobbai push
224
+ * of the mounted chat (or of any chat while none is mounted). The same push tap can reach the SDK
225
+ * by more than one path (an adapter and the iPhone relay, or two events of one library): each one
226
+ * is handled once.
227
+ */
228
+ function handleCobbaiPushTap(data) {
229
+ const pushData = toPushData(data);
230
+ if (!pushData) {
231
+ return false;
232
+ }
233
+ const store = getPushStore();
234
+ if (store.mountedChatId && store.mountedChatId !== pushData.chatId) {
235
+ return false;
236
+ }
237
+ const tapKey = `${pushData.chatId}:${pushData.messageId}`;
238
+ if (store.handledTaps.includes(tapKey)) {
239
+ return true;
240
+ }
241
+ store.handledTaps.push(tapKey);
242
+ if (store.handledTaps.length > MAX_HANDLED_TAPS) {
243
+ store.handledTaps.shift();
244
+ }
245
+ requestPendingOpen(pushData.chatId, pushData.conversationId);
246
+ return true;
247
+ }
248
+ /** A tap on the SDK's in-app banner: opens the conversation every time (no duplicate check). */
249
+ function openConversationFromBanner(chatId, conversationId) {
250
+ requestPendingOpen(chatId, conversationId);
251
+ }
252
+ function requestPendingOpen(chatId, conversationId) {
253
+ const store = getPushStore();
254
+ store.pendingOpen = { chatId, conversationId };
255
+ notifyPushStore();
256
+ }
257
+ function handleCobbaiPushInForeground(push) {
258
+ const pushData = toPushData(push.data);
259
+ if (!pushData) {
260
+ return false;
261
+ }
262
+ const store = getPushStore();
263
+ if (!store.mountedChatId || store.mountedChatId !== pushData.chatId) {
264
+ return false;
265
+ }
266
+ if (store.connected) {
267
+ if (__DEV__) {
268
+ console.log('[cobbai][push] foreground dropped');
269
+ }
270
+ return true;
271
+ }
272
+ if (!store.bannerEnabled) {
273
+ return false;
274
+ }
275
+ const preview = (0, inAppBanner_1.normalizeInAppBannerText)(push.body);
276
+ if (!preview) {
277
+ if (__DEV__) {
278
+ console.log('[cobbai][push] foreground dropped');
279
+ }
280
+ return true;
281
+ }
282
+ if (!store.showBanner) {
283
+ return false;
284
+ }
285
+ store.showBanner({
286
+ chatId: pushData.chatId,
287
+ conversationId: pushData.conversationId,
288
+ messageId: pushData.messageId,
289
+ senderName: (0, inAppBanner_1.normalizeInAppBannerText)(push.title),
290
+ preview,
291
+ source: 'push',
292
+ });
293
+ if (__DEV__) {
294
+ console.log('[cobbai][push] foreground banner');
295
+ }
296
+ return true;
297
+ }
298
+ function __resetPushStoreForTests() {
299
+ const store = getPushStore();
300
+ store.token = null;
301
+ store.pendingUnregister = null;
302
+ store.pendingOpen = null;
303
+ store.mountedChatId = null;
304
+ store.connected = false;
305
+ store.bannerEnabled = true;
306
+ store.showBanner = null;
307
+ store.handledTaps = [];
308
+ notifyPushStore();
309
+ }
@@ -0,0 +1,76 @@
1
+ import { type CobbaiPushStorage } from './pushLogout';
2
+ import { type CobbaiForegroundPush, type CobbaiPushToken } from './push';
3
+ /**
4
+ * Push integration: the app hands its notification library to the SDK
5
+ * through an adapter, once at start-up, and the SDK does the rest — token, taps (the launching one
6
+ * included), foreground pushes, permission status.
7
+ */
8
+ /**
9
+ * - `not-asked`: the user has not answered the permission prompt yet.
10
+ * - `granted` / `denied`: the user's answer.
11
+ * - `stopped`: granted, but the app turned Cobbai pushes off (`setCobbaiPushEnabled(false)`).
12
+ * - `unavailable`: no adapter, or the notification library is not set up (e.g. Firebase config
13
+ * missing).
14
+ */
15
+ export type CobbaiPushStatus = 'not-asked' | 'granted' | 'denied' | 'stopped' | 'unavailable';
16
+ /** What an adapter reports to the SDK. */
17
+ export type CobbaiPushAdapterHandlers = {
18
+ /** The device token, when known and whenever it changes. */
19
+ token: (token: CobbaiPushToken) => void;
20
+ /** A tap on any notification, the one that launched the app included; non-Cobbai ones are ignored. */
21
+ tap: (data: unknown) => void;
22
+ /** A notification received while the app is open. Returns true when it was a Cobbai push. */
23
+ foreground: (push: CobbaiForegroundPush) => boolean;
24
+ /** The permission status, at start and whenever the adapter learns it changed. */
25
+ status: (status: CobbaiPushStatus) => void;
26
+ };
27
+ /**
28
+ * Bridges one notification library to the SDK. The SDK ships `firebaseAdapter`; an app with
29
+ * another library can write its own.
30
+ */
31
+ export type CobbaiPushAdapter = {
32
+ name: string;
33
+ /** Subscribes to the library and reports through `handlers`. Returns the unsubscribe function. */
34
+ start: (handlers: CobbaiPushAdapterHandlers) => () => void;
35
+ /** Asks the user through the library (never called by the SDK on its own). */
36
+ requestPermission: () => Promise<CobbaiPushStatus>;
37
+ };
38
+ export type CobbaiPushConfiguration = {
39
+ adapter: CobbaiPushAdapter;
40
+ /**
41
+ * Keeps the logout secrets and the pending logouts across app restarts, e.g.
42
+ * `@react-native-async-storage/async-storage`. Optional: without it they live in memory.
43
+ */
44
+ storage?: CobbaiPushStorage;
45
+ };
46
+ type StatusListener = (status: CobbaiPushStatus) => void;
47
+ /**
48
+ * Hands the app's notification library to the SDK. Call it once at start-up, outside any screen
49
+ * (the tap that launched the app must not be missed). Calling it again with the same adapter does
50
+ * nothing; with another adapter, the previous one is stopped. Returns a function that stops it.
51
+ */
52
+ export declare function configureCobbaiPush({ adapter, storage }: CobbaiPushConfiguration): () => void;
53
+ /**
54
+ * Asks the user for permission through the app's notification library, and turns Cobbai pushes
55
+ * back on. The SDK never calls it on its own.
56
+ */
57
+ export declare function requestCobbaiPushPermission(): Promise<CobbaiPushStatus>;
58
+ /**
59
+ * Turns Cobbai pushes off or back on for this device while the user stays logged in (the app's
60
+ * "stop chat notifications" switch). Off unregisters the token from Cobbai only: the device keeps
61
+ * its other notifications. Kept in memory.
62
+ */
63
+ export declare function setCobbaiPushEnabled(enabled: boolean): void;
64
+ /**
65
+ * iPhone: installs the SDK's notification relay again, after a library that took the
66
+ * notification-centre delegate without chaining (the SDK warns about it in development builds), or
67
+ * when the app turned the automatic install off (`CobbaiPushAutoInstall` = NO). Resolves with
68
+ * whether the relay is in place; false on Android.
69
+ */
70
+ export declare function reinstallCobbaiPushRelay(): Promise<boolean>;
71
+ export declare function getCobbaiPushStatus(): CobbaiPushStatus;
72
+ /** Calls `listener` with the current status, then on every change. Returns the unsubscribe function. */
73
+ export declare function subscribeCobbaiPushStatus(listener: StatusListener): () => void;
74
+ export declare function __resetPushIntegrationForTests(): void;
75
+ export {};
76
+ //# sourceMappingURL=pushIntegration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pushIntegration.d.ts","sourceRoot":"","sources":["../src/pushIntegration.ts"],"names":[],"mappings":"AAEA,OAAO,EAAwB,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAKL,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACrB,MAAM,QAAQ,CAAC;AAEhB;;;;GAIG;AAEH;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,GAAG,aAAa,CAAC;AAE9F,0CAA0C;AAC1C,MAAM,MAAM,yBAAyB,GAAG;IACtC,4DAA4D;IAC5D,KAAK,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,CAAC;IACxC,sGAAsG;IACtG,GAAG,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7B,6FAA6F;IAC7F,UAAU,EAAE,CAAC,IAAI,EAAE,oBAAoB,KAAK,OAAO,CAAC;IACpD,kFAAkF;IAClF,MAAM,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,kGAAkG;IAClG,KAAK,EAAE,CAAC,QAAQ,EAAE,yBAAyB,KAAK,MAAM,IAAI,CAAC;IAC3D,8EAA8E;IAC9E,iBAAiB,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACpD,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,OAAO,EAAE,iBAAiB,CAAC;IAC3B;;;OAGG;IACH,OAAO,CAAC,EAAE,iBAAiB,CAAC;CAC7B,CAAC;AAEF,KAAK,cAAc,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;AA2HzD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,uBAAuB,GAAG,MAAM,IAAI,CA2D7F;AAED;;;GAGG;AACH,wBAAsB,2BAA2B,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAyB7E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAiB3D;AAED;;;;;GAKG;AACH,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,OAAO,CAAC,CAGjE;AAED,wBAAgB,mBAAmB,IAAI,gBAAgB,CAEtD;AAED,wGAAwG;AACxG,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,IAAI,CAQ9E;AAED,wBAAgB,8BAA8B,IAAI,IAAI,CAOrD"}
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configureCobbaiPush = configureCobbaiPush;
4
+ exports.requestCobbaiPushPermission = requestCobbaiPushPermission;
5
+ exports.setCobbaiPushEnabled = setCobbaiPushEnabled;
6
+ exports.reinstallCobbaiPushRelay = reinstallCobbaiPushRelay;
7
+ exports.getCobbaiPushStatus = getCobbaiPushStatus;
8
+ exports.subscribeCobbaiPushStatus = subscribeCobbaiPushStatus;
9
+ exports.__resetPushIntegrationForTests = __resetPushIntegrationForTests;
10
+ const react_native_1 = require("react-native");
11
+ const iosRelayAdapter_1 = require("./adapters/iosRelayAdapter");
12
+ const pushLogout_1 = require("./pushLogout");
13
+ const push_1 = require("./push");
14
+ const STATE_KEY = '__COBBAI_PUSH_INTEGRATION__';
15
+ function getState() {
16
+ const globalObject = globalThis;
17
+ if (!globalObject[STATE_KEY]) {
18
+ globalObject[STATE_KEY] = {
19
+ adapter: null,
20
+ runningAdapter: null,
21
+ stopAdapter: null,
22
+ generation: 0,
23
+ adapterStatus: 'unavailable',
24
+ enabled: true,
25
+ lastToken: null,
26
+ statusListeners: new Set(),
27
+ };
28
+ }
29
+ return globalObject[STATE_KEY];
30
+ }
31
+ function effectiveStatus(state) {
32
+ if (!state.enabled && state.adapterStatus === 'granted') {
33
+ return 'stopped';
34
+ }
35
+ return state.adapterStatus;
36
+ }
37
+ function setAdapterStatus(state, status) {
38
+ const previous = effectiveStatus(state);
39
+ state.adapterStatus = status;
40
+ const next = effectiveStatus(state);
41
+ if (next !== previous) {
42
+ state.statusListeners.forEach((listener) => listener(next));
43
+ }
44
+ }
45
+ function notifyStatus(state) {
46
+ const status = effectiveStatus(state);
47
+ state.statusListeners.forEach((listener) => listener(status));
48
+ }
49
+ function errorMessage(error) {
50
+ return error instanceof Error ? error.message : String(error);
51
+ }
52
+ function stopCurrentAdapter(state) {
53
+ const stop = state.stopAdapter;
54
+ state.adapter = null;
55
+ state.runningAdapter = null;
56
+ state.stopAdapter = null;
57
+ state.generation += 1;
58
+ if (stop) {
59
+ try {
60
+ stop();
61
+ }
62
+ catch (error) {
63
+ if (__DEV__) {
64
+ console.warn(`[cobbai][push] adapter stop failed: ${errorMessage(error)}`);
65
+ }
66
+ }
67
+ }
68
+ }
69
+ /**
70
+ * On iPhone the SDK's native relay is the source of the token, taps, foreground
71
+ * pushes and permission: Cobbai pushes go to APNs directly and only the relay is sure to see them.
72
+ * The app's adapter runs beside it (Expo sees Cobbai pushes too: taps are handled once anyway) and
73
+ * its status reports are ignored.
74
+ */
75
+ function withIosRelay(adapter) {
76
+ const native = (0, iosRelayAdapter_1.getNativeCobbaiPush)();
77
+ if (!native) {
78
+ if (react_native_1.Platform.OS === 'ios' && __DEV__) {
79
+ console.warn('[cobbai][push][ios] the native relay is missing (run `pod install`): Cobbai pushes are not handled on iPhone');
80
+ }
81
+ return adapter;
82
+ }
83
+ const relay = (0, iosRelayAdapter_1.iosRelayAdapter)(native);
84
+ return {
85
+ name: `${adapter.name}+${relay.name}`,
86
+ start(handlers) {
87
+ const stopRelay = relay.start(handlers);
88
+ let stopAppAdapter = () => { };
89
+ try {
90
+ stopAppAdapter = adapter.start({ ...handlers, status: () => { } });
91
+ }
92
+ catch (error) {
93
+ if (__DEV__) {
94
+ console.warn(`[cobbai][push] ${adapter.name} adapter failed to start: ${errorMessage(error)}`);
95
+ }
96
+ }
97
+ return () => {
98
+ stopAppAdapter();
99
+ stopRelay();
100
+ };
101
+ },
102
+ requestPermission: () => relay.requestPermission(),
103
+ };
104
+ }
105
+ /**
106
+ * Hands the app's notification library to the SDK. Call it once at start-up, outside any screen
107
+ * (the tap that launched the app must not be missed). Calling it again with the same adapter does
108
+ * nothing; with another adapter, the previous one is stopped. Returns a function that stops it.
109
+ */
110
+ function configureCobbaiPush({ adapter, storage }) {
111
+ const state = getState();
112
+ // Also retries the logouts that could not be sent before.
113
+ void (0, pushLogout_1.setPushLogoutStorage)(storage !== null && storage !== void 0 ? storage : null);
114
+ if (state.adapter === adapter) {
115
+ const generation = state.generation;
116
+ return () => {
117
+ if (getState().generation === generation) {
118
+ stopCurrentAdapter(getState());
119
+ }
120
+ };
121
+ }
122
+ stopCurrentAdapter(state);
123
+ state.adapter = adapter;
124
+ const runningAdapter = withIosRelay(adapter);
125
+ state.runningAdapter = runningAdapter;
126
+ const generation = state.generation;
127
+ const isCurrent = () => getState().generation === generation;
128
+ const handlers = {
129
+ token: (token) => {
130
+ if (!isCurrent())
131
+ return;
132
+ state.lastToken = { ...token };
133
+ if (state.enabled) {
134
+ (0, push_1.setPushToken)(token);
135
+ }
136
+ },
137
+ tap: (data) => {
138
+ if (!isCurrent())
139
+ return;
140
+ (0, push_1.handleCobbaiPushTap)(data);
141
+ },
142
+ foreground: (push) => {
143
+ if (!isCurrent())
144
+ return false;
145
+ return (0, push_1.handleCobbaiPushInForeground)(push);
146
+ },
147
+ status: (status) => {
148
+ if (!isCurrent())
149
+ return;
150
+ setAdapterStatus(state, status);
151
+ },
152
+ };
153
+ try {
154
+ state.stopAdapter = runningAdapter.start(handlers);
155
+ }
156
+ catch (error) {
157
+ if (__DEV__) {
158
+ console.warn(`[cobbai][push] ${adapter.name} adapter failed to start: ${errorMessage(error)}`);
159
+ }
160
+ setAdapterStatus(state, 'unavailable');
161
+ }
162
+ return () => {
163
+ if (isCurrent()) {
164
+ stopCurrentAdapter(getState());
165
+ }
166
+ };
167
+ }
168
+ /**
169
+ * Asks the user for permission through the app's notification library, and turns Cobbai pushes
170
+ * back on. The SDK never calls it on its own.
171
+ */
172
+ async function requestCobbaiPushPermission() {
173
+ const state = getState();
174
+ const adapter = state.runningAdapter;
175
+ if (!adapter) {
176
+ return 'unavailable';
177
+ }
178
+ setCobbaiPushEnabled(true);
179
+ let status;
180
+ try {
181
+ status = await adapter.requestPermission();
182
+ }
183
+ catch (error) {
184
+ if (__DEV__) {
185
+ console.warn(`[cobbai][push] permission request failed: ${errorMessage(error)}`);
186
+ }
187
+ status = 'denied';
188
+ }
189
+ if (state.runningAdapter === adapter) {
190
+ setAdapterStatus(state, status);
191
+ }
192
+ return effectiveStatus(state);
193
+ }
194
+ /**
195
+ * Turns Cobbai pushes off or back on for this device while the user stays logged in (the app's
196
+ * "stop chat notifications" switch). Off unregisters the token from Cobbai only: the device keeps
197
+ * its other notifications. Kept in memory.
198
+ */
199
+ function setCobbaiPushEnabled(enabled) {
200
+ const state = getState();
201
+ if (state.enabled === enabled) {
202
+ return;
203
+ }
204
+ state.enabled = enabled;
205
+ if (enabled) {
206
+ if (state.lastToken) {
207
+ (0, push_1.setPushToken)(state.lastToken);
208
+ }
209
+ }
210
+ else {
211
+ (0, push_1.clearPushToken)();
212
+ }
213
+ notifyStatus(state);
214
+ }
215
+ /**
216
+ * iPhone: installs the SDK's notification relay again, after a library that took the
217
+ * notification-centre delegate without chaining (the SDK warns about it in development builds), or
218
+ * when the app turned the automatic install off (`CobbaiPushAutoInstall` = NO). Resolves with
219
+ * whether the relay is in place; false on Android.
220
+ */
221
+ async function reinstallCobbaiPushRelay() {
222
+ const native = (0, iosRelayAdapter_1.getNativeCobbaiPush)();
223
+ return native ? native.reinstallRelay() : false;
224
+ }
225
+ function getCobbaiPushStatus() {
226
+ return effectiveStatus(getState());
227
+ }
228
+ /** Calls `listener` with the current status, then on every change. Returns the unsubscribe function. */
229
+ function subscribeCobbaiPushStatus(listener) {
230
+ const state = getState();
231
+ state.statusListeners.add(listener);
232
+ listener(effectiveStatus(state));
233
+ return () => {
234
+ state.statusListeners.delete(listener);
235
+ };
236
+ }
237
+ function __resetPushIntegrationForTests() {
238
+ const state = getState();
239
+ stopCurrentAdapter(state);
240
+ state.adapterStatus = 'unavailable';
241
+ state.enabled = true;
242
+ state.lastToken = null;
243
+ state.statusListeners.clear();
244
+ }
@@ -0,0 +1,57 @@
1
+ import type { CobbaiPushProvider } from './push';
2
+ /**
3
+ * Logout without the WebView: every register answers an unregister secret,
4
+ * relayed to native; at logout the SDK sends `DELETE {baseUrl}/connectors/chats/push_tokens` with
5
+ * it, and keeps the request on the device until the server answers.
6
+ */
7
+ /**
8
+ * Where the SDK keeps the secrets and the pending logouts across app restarts. Shaped like
9
+ * `@react-native-async-storage/async-storage`, which can be passed as is. Without it, they live in
10
+ * memory: a logout still works while the app runs, but not after a restart for a chat that has not
11
+ * been opened since.
12
+ */
13
+ export type CobbaiPushStorage = {
14
+ getItem(key: string): Promise<string | null>;
15
+ setItem(key: string, value: string): Promise<void>;
16
+ };
17
+ type Registration = {
18
+ baseUrl: string;
19
+ chatId: string;
20
+ token: string;
21
+ provider: CobbaiPushProvider;
22
+ secret: string;
23
+ };
24
+ type LogoutState = {
25
+ storage: CobbaiPushStorage | null;
26
+ loaded: Promise<void> | null;
27
+ /** The latest secret per chat and token. */
28
+ registrations: Registration[];
29
+ /** Logouts not answered yet. */
30
+ pending: Registration[];
31
+ flushing: Promise<void> | null;
32
+ };
33
+ /**
34
+ * A logout that got no answer by then is kept and retried later. Without it, a server or captive
35
+ * portal that never answers would hold this request, every logout queued behind it, and
36
+ * `logoutCobbai()`, forever (React Native's fetch has no default timeout).
37
+ */
38
+ export declare const PUSH_LOGOUT_TIMEOUT_MS = 15000;
39
+ export declare const PUSH_LOGOUT_STORAGE_KEY = "cobbai.push.logout.v1";
40
+ /** Called by `configureCobbaiPush`: loads what the storage holds and retries pending logouts. */
41
+ export declare function setPushLogoutStorage(storage: CobbaiPushStorage | null): Promise<void>;
42
+ /** A register the server accepted, with its secret (`cobbai:push-token-registered`). */
43
+ export declare function rememberUnregisterSecret(registration: Registration): void;
44
+ /**
45
+ * Call it when the user logs out of your app: unregisters this device's push token from Cobbai,
46
+ * without the chat. Your app's own notifications are not affected. Then give the chat
47
+ * screen the next user's config (or the anonymous one): on its next ready, the SDK registers the token
48
+ * again for whoever the chat user is then.
49
+ *
50
+ * Resolves once every logout got an answer or was kept to be retried (no network, or no answer
51
+ * within PUSH_LOGOUT_TIMEOUT_MS): it never rejects.
52
+ */
53
+ export declare function logoutCobbai(): Promise<void>;
54
+ export declare function __resetPushLogoutForTests(): void;
55
+ export declare function __getPushLogoutStateForTests(): Pick<LogoutState, 'registrations' | 'pending'>;
56
+ export {};
57
+ //# sourceMappingURL=pushLogout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pushLogout.d.ts","sourceRoot":"","sources":["../src/pushLogout.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAGjD;;;;GAIG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC7C,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD,CAAC;AAEF,KAAK,YAAY,GAAG;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,KAAK,WAAW,GAAG;IACjB,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAClC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC7B,4CAA4C;IAC5C,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,gCAAgC;IAChC,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAChC,CAAC;AAGF;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,QAAS,CAAC;AAC7C,eAAO,MAAM,uBAAuB,0BAA0B,CAAC;AA2K/D,iGAAiG;AACjG,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAOrF;AAED,wFAAwF;AACxF,wBAAgB,wBAAwB,CAAC,YAAY,EAAE,YAAY,GAAG,IAAI,CAYzE;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAWlD;AAED,wBAAgB,yBAAyB,IAAI,IAAI,CAOhD;AAED,wBAAgB,4BAA4B,IAAI,IAAI,CAAC,WAAW,EAAE,eAAe,GAAG,SAAS,CAAC,CAG7F"}