@pushpilotai/react-native 0.0.0-stage → 2.2.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/src/index.tsx ADDED
@@ -0,0 +1,208 @@
1
+ import type { RefObject } from 'react';
2
+ import {
3
+ NativeEventEmitter,
4
+ Platform,
5
+ findNodeHandle,
6
+ type EmitterSubscription,
7
+ } from 'react-native';
8
+ import Native, { type Spec } from './NativePushPilot';
9
+
10
+ /** A custom attribute value; `null` removes the attribute. Pass dates as RFC 3339 strings. */
11
+ export type AttributeValue = string | number | boolean | null;
12
+
13
+ /** A tapped PushPilot push that opened the app. */
14
+ export interface TappedNotification {
15
+ /** PushPilot's id for the notification, the same one its events carry. */
16
+ notificationId: string;
17
+ /** The push's custom data; empty when it had none. */
18
+ data: Record<string, string>;
19
+ }
20
+
21
+ /** Options for `PushPilot.init`. */
22
+ export interface InitOptions {
23
+ /** Your own server, for self-hosted PushPilot. Defaults to https://pushpilot.ai. */
24
+ baseUrl?: string;
25
+ /**
26
+ * iOS: the App Group shared with your Widget Extension, so images in live activity layouts can be
27
+ * shown. Pass the same id to `PushPilotLiveActivityWidget(appGroup:)`. Ignored on Android.
28
+ */
29
+ appGroup?: string;
30
+ }
31
+
32
+ // Runs one native call, logging instead of throwing so the SDK can never crash the app.
33
+ function call(name: string, run: (native: Spec) => void): void {
34
+ try {
35
+ if (Native) {
36
+ run(Native);
37
+ } else {
38
+ console.warn(
39
+ `[PushPilot] ${name} ignored: the native module is not linked. Rebuild the app (Expo Go is not supported).`
40
+ );
41
+ }
42
+ } catch (e) {
43
+ console.warn(`[PushPilot] ${name} failed: ${String(e)}`);
44
+ }
45
+ }
46
+
47
+ // An APNs device token as hex: what iOS needs since 2.0. FCM tokens and FIDs contain other characters.
48
+ const APNS_HEX = /^(?:[0-9a-fA-F]{2})+$/;
49
+
50
+ type Events = { PushPilotLink: [string]; PushPilotTap: [TappedNotification] };
51
+
52
+ // JavaScript's current link and tap handlers, if any.
53
+ const subscriptions: { [E in keyof Events]?: EmitterSubscription } = {};
54
+
55
+ // Replaces the handler for one event and tells native whether one is set now.
56
+ function setHandler<E extends keyof Events>(
57
+ event: E,
58
+ handler: ((...args: Events[E]) => void) | null,
59
+ enable: (native: Spec, enabled: boolean) => void
60
+ ): void {
61
+ call(event === 'PushPilotLink' ? 'setLinkHandler' : 'setTapHandler', (n) => {
62
+ subscriptions[event]?.remove();
63
+ subscriptions[event] = handler
64
+ ? new NativeEventEmitter<Events>(n).addListener(event, handler)
65
+ : undefined;
66
+ enable(n, handler !== null);
67
+ });
68
+ }
69
+
70
+ const PushPilot = {
71
+ /** Starts the SDK with the app's public SDK key. Later calls are ignored; earlier calls are queued. */
72
+ init(sdkKey: string, options?: InitOptions): void {
73
+ const baseUrl = options?.baseUrl ?? null;
74
+ const appGroup = options?.appGroup;
75
+ call('init', (n) =>
76
+ appGroup
77
+ ? n.initializeWithAppGroup(sdkKey, baseUrl, appGroup)
78
+ : n.initialize(sdkKey, baseUrl)
79
+ );
80
+ },
81
+
82
+ /**
83
+ * Pass every URL your app is opened with (React Native's `Linking`). For a tap on an iOS live
84
+ * activity it records the click once and resolves to the activity's own link without PushPilot's
85
+ * marker, or `null` when the activity has none (just show the app). Any other URL, and every URL on
86
+ * Android, resolves unchanged. Never rejects: on a failure it resolves to the URL as given.
87
+ */
88
+ async handleLiveActivityURL(url: string): Promise<string | null> {
89
+ try {
90
+ if (Native) return await Native.handleLiveActivityURL(url);
91
+ console.warn(
92
+ '[PushPilot] handleLiveActivityURL ignored: the native module is not linked. Rebuild the app (Expo Go is not supported).'
93
+ );
94
+ } catch (e) {
95
+ console.warn(`[PushPilot] handleLiveActivityURL failed: ${String(e)}`);
96
+ }
97
+ return url;
98
+ },
99
+
100
+ /**
101
+ * Passes the push identifier; `null` clears it.
102
+ * - Android: the Firebase Installation ID from `register` / `onRegistered` where your Firebase
103
+ * library has it, otherwise the FCM token from `getToken` / `onTokenRefresh`. Pass only one kind.
104
+ * (Not PushPilot's own installation id.)
105
+ * - iOS: the APNs device token as hex, e.g. from expo-notifications' `getDevicePushTokenAsync()` or
106
+ * React Native Firebase's `getAPNSToken()`. Not needed when your AppDelegate forwards the token
107
+ * natively. Anything else (an FCM token or FID, the 1.x iOS path) is ignored with a warning.
108
+ */
109
+ setPushToken(token: string | null): void {
110
+ if (Platform.OS === 'ios' && token !== null && !APNS_HEX.test(token)) {
111
+ console.warn(
112
+ '[PushPilot] setPushToken ignored: on iOS pass the APNs device token as hex, not an FCM token or Firebase Installation ID.'
113
+ );
114
+ return;
115
+ }
116
+ call('setPushToken', (n) => n.setPushToken(token));
117
+ },
118
+
119
+ /** Links this installation to your own user id after login; `null` clears it. */
120
+ setExternalUserId(id: string | null): void {
121
+ call('setExternalUserId', (n) => n.setExternalUserId(id));
122
+ },
123
+
124
+ /** Merges custom attributes declared in the dashboard. */
125
+ setAttributes(attributes: Record<string, AttributeValue>): void {
126
+ call('setAttributes', (n) => n.setAttributes(attributes));
127
+ },
128
+
129
+ /** Replaces this installation's topic list. */
130
+ setTopics(topics: string[]): void {
131
+ call('setTopics', (n) => n.setTopics(topics));
132
+ },
133
+
134
+ /** Clears the external user id; the device stays registered and keeps receiving pushes. */
135
+ logout(): void {
136
+ call('logout', (n) => n.logout());
137
+ },
138
+
139
+ /** Deletes this installation from PushPilot and clears all local SDK state. */
140
+ forget(): void {
141
+ call('forget', (n) => n.forget());
142
+ },
143
+
144
+ /**
145
+ * Receives the link of each tapped PushPilot push (the button's link, or the push's own) instead of
146
+ * the system opening it, like the native SDKs' `setLinkHandler`; `null` lets the system open links
147
+ * again. Set it before `init` to also get the tap that launched the app; each link arrives once.
148
+ */
149
+ setLinkHandler(handler: ((url: string) => void) | null): void {
150
+ setHandler('PushPilotLink', handler, (n, on) =>
151
+ n.setLinkHandlerEnabled(on)
152
+ );
153
+ },
154
+
155
+ /**
156
+ * Receives the id and custom data of each tapped PushPilot push that opens the app; `null` stops it.
157
+ * Set it before `init` to also get the tap that launched the app; each tap arrives once.
158
+ */
159
+ setTapHandler(handler: ((tap: TappedNotification) => void) | null): void {
160
+ setHandler('PushPilotTap', handler, (n, on) => n.setTapHandlerEnabled(on));
161
+ },
162
+
163
+ /**
164
+ * Shows the first eligible cached in-app message whose trigger name is `name` and resolves to whether
165
+ * one is now on screen: `false` when none is cached and eligible, another message is showing, or the
166
+ * SDK has not started. No network call. Never rejects: on a failure it resolves to `false`.
167
+ */
168
+ async showInApp(name: string): Promise<boolean> {
169
+ try {
170
+ if (Native) return await Native.showInApp(name);
171
+ console.warn(
172
+ '[PushPilot] showInApp ignored: the native module is not linked. Rebuild the app (Expo Go is not supported).'
173
+ );
174
+ } catch (e) {
175
+ console.warn(`[PushPilot] showInApp failed: ${String(e)}`);
176
+ }
177
+ return false;
178
+ },
179
+
180
+ /**
181
+ * Names a mounted view for coach-mark messages whose target is `name`: pass its `ref` (or a view tag
182
+ * from `findNodeHandle`). Give a plain `<View>` `collapsable={false}` so it has a native view. The SDK
183
+ * holds the view weakly; a later view with the same name replaces it.
184
+ */
185
+ // `any`: refs of every host component type (View, Pressable, TextInput...) are accepted.
186
+ markView(ref: RefObject<any> | number, name: string): void {
187
+ const tag = typeof ref === 'number' ? ref : findNodeHandle(ref.current);
188
+ if (tag == null) {
189
+ console.warn(
190
+ '[PushPilot] markView ignored: the ref has no mounted native view yet.'
191
+ );
192
+ return;
193
+ }
194
+ call('markView', (n) => n.markView(tag, name));
195
+ },
196
+
197
+ /** Forgets the view marked with `name`. */
198
+ unmarkView(name: string): void {
199
+ call('unmarkView', (n) => n.unmarkView(name));
200
+ },
201
+
202
+ /** True when a received push's data came from PushPilot. Same rule as the native SDKs; no native call. */
203
+ handleMessage(data: { [key: string]: unknown } | null | undefined): boolean {
204
+ return data?.source === 'pushpilot';
205
+ },
206
+ };
207
+
208
+ export default PushPilot;