@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.
- package/CobbaiMobileRnSdk.podspec +22 -0
- package/LICENSE +32 -0
- package/README.md +386 -0
- package/dist/ChatPlaceholder.d.ts +13 -0
- package/dist/ChatPlaceholder.d.ts.map +1 -0
- package/dist/ChatPlaceholder.js +87 -0
- package/dist/CobbaiChatScreen.d.ts +4 -0
- package/dist/CobbaiChatScreen.d.ts.map +1 -0
- package/dist/CobbaiChatScreen.js +196 -0
- package/dist/CobbaiInAppBanner.d.ts +15 -0
- package/dist/CobbaiInAppBanner.d.ts.map +1 -0
- package/dist/CobbaiInAppBanner.js +159 -0
- package/dist/CobbaiLauncher.d.ts +19 -0
- package/dist/CobbaiLauncher.d.ts.map +1 -0
- package/dist/CobbaiLauncher.js +149 -0
- package/dist/CobbaiWebView.d.ts +28 -0
- package/dist/CobbaiWebView.d.ts.map +1 -0
- package/dist/CobbaiWebView.js +141 -0
- package/dist/adapters/expoAdapter.d.ts +85 -0
- package/dist/adapters/expoAdapter.d.ts.map +1 -0
- package/dist/adapters/expoAdapter.js +152 -0
- package/dist/adapters/firebaseAdapter.d.ts +41 -0
- package/dist/adapters/firebaseAdapter.d.ts.map +1 -0
- package/dist/adapters/firebaseAdapter.js +139 -0
- package/dist/adapters/iosRelayAdapter.d.ts +26 -0
- package/dist/adapters/iosRelayAdapter.d.ts.map +1 -0
- package/dist/adapters/iosRelayAdapter.js +101 -0
- package/dist/androidKeyboardFrame.d.ts +16 -0
- package/dist/androidKeyboardFrame.d.ts.map +1 -0
- package/dist/androidKeyboardFrame.js +34 -0
- package/dist/bridge/messages.d.ts +20 -0
- package/dist/bridge/messages.d.ts.map +1 -0
- package/dist/bridge/messages.js +20 -0
- package/dist/bridge/nativeEvent.d.ts +10 -0
- package/dist/bridge/nativeEvent.d.ts.map +1 -0
- package/dist/bridge/nativeEvent.js +15 -0
- package/dist/bridge/parser.d.ts +29 -0
- package/dist/bridge/parser.d.ts.map +1 -0
- package/dist/bridge/parser.js +109 -0
- package/dist/chatPresentation.d.ts +19 -0
- package/dist/chatPresentation.d.ts.map +1 -0
- package/dist/chatPresentation.js +51 -0
- package/dist/chatScreen/useInAppBannerQueue.d.ts +22 -0
- package/dist/chatScreen/useInAppBannerQueue.d.ts.map +1 -0
- package/dist/chatScreen/useInAppBannerQueue.js +60 -0
- package/dist/chatScreen/useKeyboardFrame.d.ts +14 -0
- package/dist/chatScreen/useKeyboardFrame.d.ts.map +1 -0
- package/dist/chatScreen/useKeyboardFrame.js +63 -0
- package/dist/chatScreen/useLauncherPresentation.d.ts +20 -0
- package/dist/chatScreen/useLauncherPresentation.d.ts.map +1 -0
- package/dist/chatScreen/useLauncherPresentation.js +76 -0
- package/dist/chatScreen/useNativeToWebSync.d.ts +17 -0
- package/dist/chatScreen/useNativeToWebSync.d.ts.map +1 -0
- package/dist/chatScreen/useNativeToWebSync.js +36 -0
- package/dist/chatScreen/usePushIntegration.d.ts +19 -0
- package/dist/chatScreen/usePushIntegration.d.ts.map +1 -0
- package/dist/chatScreen/usePushIntegration.js +129 -0
- package/dist/chatScreen/useReadyLifecycle.d.ts +33 -0
- package/dist/chatScreen/useReadyLifecycle.d.ts.map +1 -0
- package/dist/chatScreen/useReadyLifecycle.js +138 -0
- package/dist/chatScreen/useSheetPresentation.d.ts +25 -0
- package/dist/chatScreen/useSheetPresentation.d.ts.map +1 -0
- package/dist/chatScreen/useSheetPresentation.js +98 -0
- package/dist/chatUnavailable.d.ts +23 -0
- package/dist/chatUnavailable.d.ts.map +1 -0
- package/dist/chatUnavailable.js +36 -0
- package/dist/externalLinks.d.ts +4 -0
- package/dist/externalLinks.d.ts.map +1 -0
- package/dist/externalLinks.js +48 -0
- package/dist/host/buildHostHtml.d.ts +7 -0
- package/dist/host/buildHostHtml.d.ts.map +1 -0
- package/dist/host/buildHostHtml.js +101 -0
- package/dist/host/hostPageKey.d.ts +7 -0
- package/dist/host/hostPageKey.d.ts.map +1 -0
- package/dist/host/hostPageKey.js +18 -0
- package/dist/inAppBanner.d.ts +19 -0
- package/dist/inAppBanner.d.ts.map +1 -0
- package/dist/inAppBanner.js +42 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/launcher.d.ts +25 -0
- package/dist/launcher.d.ts.map +1 -0
- package/dist/launcher.js +55 -0
- package/dist/launcherGlyph.d.ts +2 -0
- package/dist/launcherGlyph.d.ts.map +1 -0
- package/dist/launcherGlyph.js +5 -0
- package/dist/openChatScreen.d.ts +13 -0
- package/dist/openChatScreen.d.ts.map +1 -0
- package/dist/openChatScreen.js +63 -0
- package/dist/push.d.ts +59 -0
- package/dist/push.d.ts.map +1 -0
- package/dist/push.js +309 -0
- package/dist/pushIntegration.d.ts +76 -0
- package/dist/pushIntegration.d.ts.map +1 -0
- package/dist/pushIntegration.js +244 -0
- package/dist/pushLogout.d.ts +57 -0
- package/dist/pushLogout.d.ts.map +1 -0
- package/dist/pushLogout.js +225 -0
- package/dist/types.d.ts +42 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +10 -0
- package/ios/CobbaiPush.m +96 -0
- package/ios/CobbaiPushRelay.h +59 -0
- package/ios/CobbaiPushRelay.m +364 -0
- package/package.json +69 -0
- package/src/ChatPlaceholder.tsx +132 -0
- package/src/CobbaiChatScreen.tsx +348 -0
- package/src/CobbaiInAppBanner.tsx +237 -0
- package/src/CobbaiLauncher.tsx +223 -0
- package/src/CobbaiWebView.tsx +242 -0
- package/src/adapters/expoAdapter.ts +227 -0
- package/src/adapters/firebaseAdapter.ts +201 -0
- package/src/adapters/iosRelayAdapter.ts +137 -0
- package/src/androidKeyboardFrame.ts +56 -0
- package/src/bridge/messages.ts +24 -0
- package/src/bridge/nativeEvent.ts +12 -0
- package/src/bridge/parser.ts +159 -0
- package/src/chatPresentation.ts +73 -0
- package/src/chatScreen/useInAppBannerQueue.ts +91 -0
- package/src/chatScreen/useKeyboardFrame.ts +89 -0
- package/src/chatScreen/useLauncherPresentation.ts +121 -0
- package/src/chatScreen/useNativeToWebSync.ts +54 -0
- package/src/chatScreen/usePushIntegration.ts +191 -0
- package/src/chatScreen/useReadyLifecycle.ts +186 -0
- package/src/chatScreen/useSheetPresentation.ts +147 -0
- package/src/chatUnavailable.ts +58 -0
- package/src/externalLinks.ts +56 -0
- package/src/host/buildHostHtml.ts +117 -0
- package/src/host/hostPageKey.ts +17 -0
- package/src/inAppBanner.ts +58 -0
- package/src/index.ts +53 -0
- package/src/launcher.ts +79 -0
- package/src/launcherGlyph.ts +3 -0
- package/src/openChatScreen.ts +78 -0
- package/src/push.ts +424 -0
- package/src/pushIntegration.ts +338 -0
- package/src/pushLogout.ts +277 -0
- package/src/types.ts +46 -0
- package/src/version.ts +8 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { PermissionsAndroid, Platform } from 'react-native';
|
|
2
|
+
import type {
|
|
3
|
+
CobbaiPushAdapter,
|
|
4
|
+
CobbaiPushAdapterHandlers,
|
|
5
|
+
CobbaiPushStatus,
|
|
6
|
+
} from '../pushIntegration';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The part of `@react-native-firebase/messaging` (modular API, v19+) the adapter uses. The app
|
|
10
|
+
* passes the module itself, so the SDK does not depend on Firebase:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import * as messaging from '@react-native-firebase/messaging';
|
|
14
|
+
* configureCobbaiPush({ adapter: firebaseAdapter(messaging) });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Methods (not function properties) on purpose: the library's own signatures take more precise
|
|
18
|
+
* types and optional extra arguments, and must stay assignable.
|
|
19
|
+
*/
|
|
20
|
+
export type FirebaseMessagingModule<TMessaging = unknown> = {
|
|
21
|
+
getMessaging(): TMessaging;
|
|
22
|
+
getToken(messaging: TMessaging): Promise<string>;
|
|
23
|
+
onMessage(
|
|
24
|
+
messaging: TMessaging,
|
|
25
|
+
listener: (message: FirebaseRemoteMessage) => unknown,
|
|
26
|
+
): () => void;
|
|
27
|
+
onNotificationOpenedApp(
|
|
28
|
+
messaging: TMessaging,
|
|
29
|
+
listener: (message: FirebaseRemoteMessage) => unknown,
|
|
30
|
+
): () => void;
|
|
31
|
+
onTokenRefresh(messaging: TMessaging, listener: (token: string) => unknown): () => void;
|
|
32
|
+
getInitialNotification(messaging: TMessaging): Promise<FirebaseRemoteMessage | null>;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** The fields of a Firebase `RemoteMessage` the adapter reads. */
|
|
36
|
+
export type FirebaseRemoteMessage = {
|
|
37
|
+
data?: { [key: string]: string | object };
|
|
38
|
+
notification?: { title?: string; body?: string };
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const POST_NOTIFICATIONS_API_LEVEL = 33;
|
|
42
|
+
|
|
43
|
+
function androidApiLevel(): number {
|
|
44
|
+
const version = Platform.Version;
|
|
45
|
+
return typeof version === 'number' ? version : Number.parseInt(String(version), 10);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function needsRuntimePermission(): boolean {
|
|
49
|
+
const apiLevel = androidApiLevel();
|
|
50
|
+
return Number.isFinite(apiLevel) && apiLevel >= POST_NOTIFICATIONS_API_LEVEL;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function errorMessage(error: unknown): string {
|
|
54
|
+
if (error instanceof Error) return error.message;
|
|
55
|
+
return typeof error === 'string' ? error : 'unknown error';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Firebase throws these when `google-services.json` is missing. */
|
|
59
|
+
function isFirebaseNotConfigured(error: unknown): boolean {
|
|
60
|
+
const message = errorMessage(error).toLowerCase();
|
|
61
|
+
return (
|
|
62
|
+
message.includes('firebase') &&
|
|
63
|
+
(message.includes('not configured') ||
|
|
64
|
+
message.includes('default app has not been created') ||
|
|
65
|
+
message.includes('default firebaseapp is not initialized') ||
|
|
66
|
+
message.includes('no firebase app'))
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function warn(message: string): void {
|
|
71
|
+
if (__DEV__) {
|
|
72
|
+
console.warn(`[cobbai][push][firebase] ${message}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Push adapter for `@react-native-firebase/messaging`, **Android only**. On iPhone, Cobbai pushes go
|
|
78
|
+
* to APNs directly and Firebase ignores them: the SDK's native relay handles them,
|
|
79
|
+
* and this adapter does nothing there.
|
|
80
|
+
*
|
|
81
|
+
* It never sets Firebase's background message handler: that one belongs to the app, which returns
|
|
82
|
+
* early on `isCobbaiPush(message.data)`.
|
|
83
|
+
*/
|
|
84
|
+
export function firebaseAdapter<TMessaging>(
|
|
85
|
+
firebase: FirebaseMessagingModule<TMessaging>,
|
|
86
|
+
): CobbaiPushAdapter {
|
|
87
|
+
let handlers: CobbaiPushAdapterHandlers | null = null;
|
|
88
|
+
let messagingInstance: TMessaging | null = null;
|
|
89
|
+
|
|
90
|
+
/** Returns false when Firebase turned out not to be configured. */
|
|
91
|
+
const reportToken = async (): Promise<boolean> => {
|
|
92
|
+
if (!handlers || messagingInstance === null) return true;
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
const token = await firebase.getToken(messagingInstance);
|
|
96
|
+
if (token && handlers) {
|
|
97
|
+
handlers.token({ token, provider: 'fcm' });
|
|
98
|
+
}
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (isFirebaseNotConfigured(error)) {
|
|
101
|
+
warn('Firebase is not configured (android/app/google-services.json missing)');
|
|
102
|
+
handlers?.status('unavailable');
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
warn(`token request failed: ${errorMessage(error)}`);
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const readStatus = async (): Promise<CobbaiPushStatus> => {
|
|
111
|
+
if (!needsRuntimePermission()) return 'granted';
|
|
112
|
+
|
|
113
|
+
const granted = await PermissionsAndroid.check(
|
|
114
|
+
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
|
|
115
|
+
);
|
|
116
|
+
// Android tells "granted" or not; a refusal looks like "not asked" until the next request.
|
|
117
|
+
return granted ? 'granted' : 'not-asked';
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
name: 'firebase',
|
|
122
|
+
|
|
123
|
+
start(nextHandlers) {
|
|
124
|
+
if (Platform.OS !== 'android') {
|
|
125
|
+
return () => {};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
handlers = nextHandlers;
|
|
129
|
+
const unsubscribers: Array<() => void> = [];
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
const messaging = firebase.getMessaging();
|
|
133
|
+
messagingInstance = messaging;
|
|
134
|
+
|
|
135
|
+
unsubscribers.push(
|
|
136
|
+
firebase.onMessage(messaging, (message) => {
|
|
137
|
+
handlers?.foreground({
|
|
138
|
+
data: message.data,
|
|
139
|
+
title: message.notification?.title,
|
|
140
|
+
body: message.notification?.body,
|
|
141
|
+
});
|
|
142
|
+
}),
|
|
143
|
+
firebase.onNotificationOpenedApp(messaging, (message) => {
|
|
144
|
+
handlers?.tap(message.data);
|
|
145
|
+
}),
|
|
146
|
+
firebase.onTokenRefresh(messaging, (token) => {
|
|
147
|
+
handlers?.token({ token, provider: 'fcm' });
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
firebase
|
|
152
|
+
.getInitialNotification(messaging)
|
|
153
|
+
.then((message) => {
|
|
154
|
+
if (message?.data) handlers?.tap(message.data);
|
|
155
|
+
})
|
|
156
|
+
.catch((error: unknown) => warn(`initial notification failed: ${errorMessage(error)}`));
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (isFirebaseNotConfigured(error)) {
|
|
159
|
+
warn('Firebase is not configured (android/app/google-services.json missing)');
|
|
160
|
+
nextHandlers.status('unavailable');
|
|
161
|
+
return () => {};
|
|
162
|
+
}
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
readStatus()
|
|
167
|
+
.then((status) => {
|
|
168
|
+
handlers?.status(status);
|
|
169
|
+
if (status === 'granted') return reportToken();
|
|
170
|
+
return true;
|
|
171
|
+
})
|
|
172
|
+
.catch((error: unknown) => warn(`permission check failed: ${errorMessage(error)}`));
|
|
173
|
+
|
|
174
|
+
return () => {
|
|
175
|
+
unsubscribers.forEach((unsubscribe) => unsubscribe());
|
|
176
|
+
handlers = null;
|
|
177
|
+
messagingInstance = null;
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
|
|
181
|
+
async requestPermission() {
|
|
182
|
+
if (Platform.OS !== 'android') {
|
|
183
|
+
return 'unavailable';
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let status: CobbaiPushStatus = 'granted';
|
|
187
|
+
if (needsRuntimePermission()) {
|
|
188
|
+
const result = await PermissionsAndroid.request(
|
|
189
|
+
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
|
|
190
|
+
);
|
|
191
|
+
status = result === PermissionsAndroid.RESULTS.GRANTED ? 'granted' : 'denied';
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (status === 'granted' && !(await reportToken())) {
|
|
195
|
+
return 'unavailable';
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return status;
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { AppState, NativeEventEmitter, NativeModules, Platform } from 'react-native';
|
|
2
|
+
import {
|
|
3
|
+
getForegroundPresentationState,
|
|
4
|
+
subscribePushStore,
|
|
5
|
+
type ForegroundPresentationState,
|
|
6
|
+
} from '../push';
|
|
7
|
+
import type { CobbaiPushAdapter, CobbaiPushStatus } from '../pushIntegration';
|
|
8
|
+
|
|
9
|
+
/** The native module of `ios/CobbaiPush.m`. */
|
|
10
|
+
export type NativeCobbaiPush = {
|
|
11
|
+
start(): Promise<{
|
|
12
|
+
token: string | null;
|
|
13
|
+
apnsEnvironment: 'sandbox' | 'production';
|
|
14
|
+
pendingTaps: unknown[];
|
|
15
|
+
inPlace: boolean;
|
|
16
|
+
status: CobbaiPushStatus;
|
|
17
|
+
}>;
|
|
18
|
+
setPresentationState(state: ForegroundPresentationState): void;
|
|
19
|
+
getPermissionStatus(): Promise<CobbaiPushStatus>;
|
|
20
|
+
requestPermission(): Promise<CobbaiPushStatus>;
|
|
21
|
+
reinstallRelay(): Promise<boolean>;
|
|
22
|
+
addListener(eventName: string): void;
|
|
23
|
+
removeListeners(count: number): void;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type TokenEvent = { token: string; apnsEnvironment: 'sandbox' | 'production' };
|
|
27
|
+
type TapEvent = { data: unknown };
|
|
28
|
+
type ForegroundEvent = { data: unknown; title?: string; body?: string };
|
|
29
|
+
|
|
30
|
+
/** The iPhone relay's native module, or null (Android, or the pod not installed). */
|
|
31
|
+
export function getNativeCobbaiPush(): NativeCobbaiPush | null {
|
|
32
|
+
if (Platform.OS !== 'ios') return null;
|
|
33
|
+
return (NativeModules.CobbaiPush as NativeCobbaiPush | undefined) ?? null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function warn(message: string): void {
|
|
37
|
+
if (__DEV__) {
|
|
38
|
+
console.warn(`[cobbai][push][ios] ${message}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function errorMessage(error: unknown): string {
|
|
43
|
+
return error instanceof Error ? error.message : String(error);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function sameState(
|
|
47
|
+
left: ForegroundPresentationState | null,
|
|
48
|
+
right: ForegroundPresentationState,
|
|
49
|
+
): boolean {
|
|
50
|
+
return (
|
|
51
|
+
left !== null &&
|
|
52
|
+
left.mountedChatId === right.mountedChatId &&
|
|
53
|
+
left.connected === right.connected &&
|
|
54
|
+
left.bannerEnabled === right.bannerEnabled
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The SDK's own adapter on iPhone: token, taps (the launching one included) and
|
|
60
|
+
* foreground pushes come from the native relay, with no code in the app.
|
|
61
|
+
*/
|
|
62
|
+
export function iosRelayAdapter(native: NativeCobbaiPush): CobbaiPushAdapter {
|
|
63
|
+
return {
|
|
64
|
+
name: 'ios-relay',
|
|
65
|
+
|
|
66
|
+
start(handlers) {
|
|
67
|
+
const emitter = new NativeEventEmitter(native);
|
|
68
|
+
const subscriptions = [
|
|
69
|
+
emitter.addListener('CobbaiPushToken', (event: TokenEvent) => {
|
|
70
|
+
handlers.token({
|
|
71
|
+
token: event.token,
|
|
72
|
+
provider: 'apns',
|
|
73
|
+
apnsEnvironment: event.apnsEnvironment,
|
|
74
|
+
});
|
|
75
|
+
}),
|
|
76
|
+
emitter.addListener('CobbaiPushTap', (event: TapEvent) => {
|
|
77
|
+
handlers.tap(event.data);
|
|
78
|
+
}),
|
|
79
|
+
emitter.addListener('CobbaiPushForeground', (event: ForegroundEvent) => {
|
|
80
|
+
handlers.foreground({ data: event.data, title: event.title, body: event.body });
|
|
81
|
+
}),
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
// Keep the relay told of the foreground state, so that it answers iOS at once.
|
|
85
|
+
let sentState: ForegroundPresentationState | null = null;
|
|
86
|
+
const syncPresentationState = (): void => {
|
|
87
|
+
const state = getForegroundPresentationState();
|
|
88
|
+
if (sameState(sentState, state)) return;
|
|
89
|
+
sentState = state;
|
|
90
|
+
native.setPresentationState(state);
|
|
91
|
+
};
|
|
92
|
+
syncPresentationState();
|
|
93
|
+
const unsubscribeStore = subscribePushStore(syncPresentationState);
|
|
94
|
+
|
|
95
|
+
// The user can change the permission in Settings while the app is in the background.
|
|
96
|
+
const appStateSubscription = AppState.addEventListener('change', (nextState) => {
|
|
97
|
+
if (nextState !== 'active') return;
|
|
98
|
+
native
|
|
99
|
+
.getPermissionStatus()
|
|
100
|
+
.then((status) => handlers.status(status))
|
|
101
|
+
.catch((error: unknown) => warn(`permission check failed: ${errorMessage(error)}`));
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
native
|
|
105
|
+
.start()
|
|
106
|
+
.then((initial) => {
|
|
107
|
+
handlers.status(initial.status);
|
|
108
|
+
if (initial.token) {
|
|
109
|
+
handlers.token({
|
|
110
|
+
token: initial.token,
|
|
111
|
+
provider: 'apns',
|
|
112
|
+
apnsEnvironment: initial.apnsEnvironment,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
initial.pendingTaps.forEach((data) => handlers.tap(data));
|
|
116
|
+
if (!initial.inPlace) {
|
|
117
|
+
warn(
|
|
118
|
+
'the notification relay is not installed: another library took the notification-centre ' +
|
|
119
|
+
'delegate without chaining, or CobbaiPushAutoInstall is NO. Call reinstallCobbaiPushRelay() ' +
|
|
120
|
+
'after that library has started.',
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
.catch((error: unknown) => warn(`relay start failed: ${errorMessage(error)}`));
|
|
125
|
+
|
|
126
|
+
return () => {
|
|
127
|
+
subscriptions.forEach((subscription) => subscription.remove());
|
|
128
|
+
unsubscribeStore();
|
|
129
|
+
appStateSubscription.remove();
|
|
130
|
+
};
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
requestPermission() {
|
|
134
|
+
return native.requestPermission();
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { CobbaiSafeAreaInsets } from './types';
|
|
2
|
+
|
|
3
|
+
export type KeyboardFrameInput = {
|
|
4
|
+
chatVisible: boolean;
|
|
5
|
+
keyboardHeight: number;
|
|
6
|
+
keyboardScreenY: number;
|
|
7
|
+
windowHeight: number;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export type KeyboardFrame = {
|
|
11
|
+
isApplied: boolean;
|
|
12
|
+
overlayBottomInset: number;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function normalizeInset(value: number): number {
|
|
16
|
+
if (!Number.isFinite(value)) return 0;
|
|
17
|
+
return Math.max(0, Math.round(value));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function deriveKeyboardInsetFromHeight(keyboardHeight: number): number {
|
|
21
|
+
return normalizeInset(keyboardHeight);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function deriveKeyboardInsetFromScreenY(
|
|
25
|
+
windowHeight: number,
|
|
26
|
+
keyboardScreenY: number,
|
|
27
|
+
): number {
|
|
28
|
+
return normalizeInset(windowHeight - keyboardScreenY);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function deriveKeyboardFrame(input: KeyboardFrameInput): KeyboardFrame {
|
|
32
|
+
if (!input.chatVisible) {
|
|
33
|
+
return { isApplied: false, overlayBottomInset: 0 };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const insetFromHeight = deriveKeyboardInsetFromHeight(input.keyboardHeight);
|
|
37
|
+
const insetFromScreenY = deriveKeyboardInsetFromScreenY(
|
|
38
|
+
input.windowHeight,
|
|
39
|
+
input.keyboardScreenY,
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
// A keyboard is considered visible only when both metrics agree it is shown.
|
|
43
|
+
if (insetFromHeight <= 0 || insetFromScreenY <= 0) {
|
|
44
|
+
return { isApplied: false, overlayBottomInset: 0 };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return { isApplied: true, overlayBottomInset: insetFromScreenY };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function withKeyboardSafeAreaBottom(
|
|
51
|
+
safeArea: CobbaiSafeAreaInsets,
|
|
52
|
+
keyboardFrameApplied: boolean,
|
|
53
|
+
): CobbaiSafeAreaInsets {
|
|
54
|
+
if (!keyboardFrameApplied) return safeArea;
|
|
55
|
+
return { ...safeArea, bottom: 0 };
|
|
56
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const WEB_TO_NATIVE_MESSAGES = {
|
|
2
|
+
READY: 'cobbai:ready',
|
|
3
|
+
CLOSE: 'cobbai:close',
|
|
4
|
+
NEW_MESSAGE: 'cobbai:new-message',
|
|
5
|
+
UNREAD: 'cobbai:unread',
|
|
6
|
+
LAUNCHER: 'cobbai:launcher',
|
|
7
|
+
ERROR: 'cobbai:error',
|
|
8
|
+
PUSH_TOKEN_REGISTERED: 'cobbai:push-token-registered',
|
|
9
|
+
} as const;
|
|
10
|
+
|
|
11
|
+
export const NATIVE_TO_WEB_MESSAGES = {
|
|
12
|
+
APP_STATE: 'cobbai:app-state',
|
|
13
|
+
NETWORK: 'cobbai:network',
|
|
14
|
+
OPEN_CONVERSATION: 'cobbai:open-conversation',
|
|
15
|
+
PUSH_TOKEN: 'cobbai:push-token',
|
|
16
|
+
SAFE_AREA: 'cobbai:safe-area',
|
|
17
|
+
VISIBILITY: 'cobbai:visibility',
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export type WebToNativeMessageType =
|
|
21
|
+
(typeof WEB_TO_NATIVE_MESSAGES)[keyof typeof WEB_TO_NATIVE_MESSAGES];
|
|
22
|
+
|
|
23
|
+
export type NativeToWebMessageType =
|
|
24
|
+
(typeof NATIVE_TO_WEB_MESSAGES)[keyof typeof NATIVE_TO_WEB_MESSAGES];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the script injected into the host page to deliver a native → web message.
|
|
3
|
+
*
|
|
4
|
+
* The envelope is serialized twice on purpose: the inner `JSON.stringify` builds the wire string
|
|
5
|
+
* (`MessageEvent.data`, parsed by the page with `JSON.parse`), the outer one turns that string into a
|
|
6
|
+
* valid JavaScript string literal. Escaping by hand (quotes only) corrupted `"`, `\` and line
|
|
7
|
+
* breaks, and A dropped the message silently.
|
|
8
|
+
*/
|
|
9
|
+
export function serializeNativeEvent(type: string, payload: Record<string, unknown>): string {
|
|
10
|
+
const data = JSON.stringify({ type, payload });
|
|
11
|
+
return `window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify(data)} })); true;`;
|
|
12
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { WEB_TO_NATIVE_MESSAGES, type WebToNativeMessageType } from './messages';
|
|
2
|
+
import type { LauncherAppearance } from '../launcher';
|
|
3
|
+
|
|
4
|
+
export type BridgePayload = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
export type ParsedBridgeMessage = {
|
|
7
|
+
type: WebToNativeMessageType;
|
|
8
|
+
payload: BridgePayload;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type ValidatedNewMessagePayload = {
|
|
12
|
+
conversationId: number;
|
|
13
|
+
messageId: number;
|
|
14
|
+
speaker: 'agent' | 'auto';
|
|
15
|
+
senderName?: string;
|
|
16
|
+
preview?: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type ValidatedUnreadPayload = {
|
|
20
|
+
total: number;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type ValidatedPushTokenRegisteredPayload = {
|
|
24
|
+
token: string;
|
|
25
|
+
provider: 'apns' | 'fcm';
|
|
26
|
+
unregisterSecret: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const PUSH_TOKEN_PATTERN = /^[A-Za-z0-9:_\-.]{1,4096}$/;
|
|
30
|
+
const UNREGISTER_SECRET_PATTERN = /^[0-9a-f]{64}$/;
|
|
31
|
+
|
|
32
|
+
const HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
|
33
|
+
|
|
34
|
+
const VALID_TYPES = new Set<string>(Object.values(WEB_TO_NATIVE_MESSAGES));
|
|
35
|
+
|
|
36
|
+
function parsePositiveInteger(value: unknown): number | null {
|
|
37
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseOptionalTrimmedString(value: unknown, maxLength: number): string | undefined {
|
|
45
|
+
if (typeof value !== 'string') {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const trimmed = value.trim();
|
|
50
|
+
if (trimmed.length === 0) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (Array.from(trimmed).length > maxLength) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return trimmed;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function validateNewMessagePayload(
|
|
62
|
+
payload: BridgePayload,
|
|
63
|
+
): ValidatedNewMessagePayload | null {
|
|
64
|
+
const conversationId = parsePositiveInteger(payload.conversation_id);
|
|
65
|
+
const messageId = parsePositiveInteger(payload.message_id);
|
|
66
|
+
const speaker = payload.speaker;
|
|
67
|
+
const senderName = parseOptionalTrimmedString(payload.sender_name, 80);
|
|
68
|
+
const preview = parseOptionalTrimmedString(payload.preview, 160);
|
|
69
|
+
|
|
70
|
+
if (conversationId == null || messageId == null) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (speaker !== 'agent' && speaker !== 'auto') {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
conversationId,
|
|
80
|
+
messageId,
|
|
81
|
+
speaker,
|
|
82
|
+
...(senderName ? { senderName } : {}),
|
|
83
|
+
...(preview ? { preview } : {}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function validateUnreadPayload(payload: BridgePayload): ValidatedUnreadPayload | null {
|
|
88
|
+
const total = payload.total;
|
|
89
|
+
|
|
90
|
+
if (typeof total !== 'number' || !Number.isInteger(total) || total < 0) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return { total };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The secret that unregisters the token at logout. */
|
|
98
|
+
export function validatePushTokenRegisteredPayload(
|
|
99
|
+
payload: BridgePayload,
|
|
100
|
+
): ValidatedPushTokenRegisteredPayload | null {
|
|
101
|
+
const { token, provider, unregister_secret: unregisterSecret } = payload;
|
|
102
|
+
|
|
103
|
+
if (typeof token !== 'string' || !PUSH_TOKEN_PATTERN.test(token)) return null;
|
|
104
|
+
if (provider !== 'apns' && provider !== 'fcm') return null;
|
|
105
|
+
if (typeof unregisterSecret !== 'string' || !UNREGISTER_SECRET_PATTERN.test(unregisterSecret)) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return { token, provider, unregisterSecret };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function validateLauncherPayload(payload: BridgePayload): LauncherAppearance | null {
|
|
113
|
+
const backgroundColor = payload.background_color;
|
|
114
|
+
const textColor = payload.text_color;
|
|
115
|
+
|
|
116
|
+
if (
|
|
117
|
+
typeof backgroundColor !== 'string' ||
|
|
118
|
+
typeof textColor !== 'string' ||
|
|
119
|
+
!HEX_COLOR_PATTERN.test(backgroundColor) ||
|
|
120
|
+
!HEX_COLOR_PATTERN.test(textColor)
|
|
121
|
+
) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
backgroundColor,
|
|
127
|
+
textColor,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function parseBridgeMessage(raw: string): ParsedBridgeMessage | null {
|
|
132
|
+
let parsed: unknown;
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
parsed = JSON.parse(raw);
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const type = (parsed as Record<string, unknown>).type;
|
|
145
|
+
const payload = (parsed as Record<string, unknown>).payload;
|
|
146
|
+
|
|
147
|
+
if (typeof type !== 'string' || !VALID_TYPES.has(type)) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (payload != null && typeof payload !== 'object') {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
type: type as WebToNativeMessageType,
|
|
157
|
+
payload: (payload as BridgePayload) ?? {},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { CobbaiSafeAreaInsets } from './types';
|
|
2
|
+
|
|
3
|
+
export const SHEET_TRANSITION_DURATION_MS = 200;
|
|
4
|
+
export const LOADER_FADE_OUT_DURATION_MS = 150;
|
|
5
|
+
export const PROCESS_GONE_RETRY_LIMIT = 3;
|
|
6
|
+
export const PROCESS_GONE_RETRY_WINDOW_MS = 60_000;
|
|
7
|
+
|
|
8
|
+
export type ProcessGoneRecoveryDecision = {
|
|
9
|
+
shouldRemount: boolean;
|
|
10
|
+
nextOccurrenceTimestampsMs: number[];
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function getOffscreenTranslateY(windowHeight: number): number {
|
|
14
|
+
if (!Number.isFinite(windowHeight) || windowHeight <= 0) {
|
|
15
|
+
return 1;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return Math.ceil(windowHeight) + 1;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function getBackdropOpacityInterpolationRanges(offscreenTranslateY: number): {
|
|
22
|
+
inputRange: [number, number];
|
|
23
|
+
outputRange: [number, number];
|
|
24
|
+
} {
|
|
25
|
+
const clampedOffscreenTranslateY =
|
|
26
|
+
Number.isFinite(offscreenTranslateY) && offscreenTranslateY > 0 ? offscreenTranslateY : 1;
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
inputRange: [0, clampedOffscreenTranslateY],
|
|
30
|
+
outputRange: [1, 0],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function toSheetSafeAreaInsetsForWeb(safeArea: CobbaiSafeAreaInsets): CobbaiSafeAreaInsets {
|
|
35
|
+
return {
|
|
36
|
+
top: 0,
|
|
37
|
+
right: safeArea.right,
|
|
38
|
+
bottom: safeArea.bottom,
|
|
39
|
+
left: safeArea.left,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function shouldRenderChatSurface(
|
|
44
|
+
prewarm: boolean,
|
|
45
|
+
visible: boolean,
|
|
46
|
+
presented: boolean,
|
|
47
|
+
): boolean {
|
|
48
|
+
return prewarm || visible || presented;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function isChatSurfaceOnScreen(visible: boolean, presented: boolean): boolean {
|
|
52
|
+
return visible || presented;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function getProcessGoneRecoveryDecision(
|
|
56
|
+
occurrenceTimestampsMs: number[],
|
|
57
|
+
nowMs: number,
|
|
58
|
+
): ProcessGoneRecoveryDecision {
|
|
59
|
+
const recentOccurrences = occurrenceTimestampsMs.filter(
|
|
60
|
+
(timestampMs) =>
|
|
61
|
+
Number.isFinite(timestampMs) &&
|
|
62
|
+
timestampMs <= nowMs &&
|
|
63
|
+
nowMs - timestampMs <= PROCESS_GONE_RETRY_WINDOW_MS,
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
const nextOccurrenceTimestampsMs = [...recentOccurrences, nowMs];
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
// Stop auto-remounting on the 3rd process death within the rolling 60-second window.
|
|
70
|
+
shouldRemount: nextOccurrenceTimestampsMs.length < PROCESS_GONE_RETRY_LIMIT,
|
|
71
|
+
nextOccurrenceTimestampsMs,
|
|
72
|
+
};
|
|
73
|
+
}
|