@amplitude/analytics-react-native 0.0.1-dev.8 → 0.0.1-dev.9

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.
@@ -0,0 +1,21 @@
1
+ import { BeforePlugin, PluginType, Event, Config } from '@amplitude/analytics-types';
2
+ import { getAnalyticsConnector } from '../utils/analytics-connector';
3
+
4
+ export class IdentityEventSender implements BeforePlugin {
5
+ name = 'identity';
6
+ type = PluginType.BEFORE as const;
7
+
8
+ identityStore = getAnalyticsConnector().identityStore;
9
+
10
+ async execute(context: Event): Promise<Event> {
11
+ const userProperties = context.user_properties as Record<string, any>;
12
+ if (userProperties) {
13
+ this.identityStore.editIdentity().setUserProperties(userProperties).commit();
14
+ }
15
+ return context;
16
+ }
17
+
18
+ setup(_: Config): Promise<undefined> {
19
+ return Promise.resolve(undefined);
20
+ }
21
+ }
@@ -0,0 +1,332 @@
1
+ import { AmplitudeCore, Destination, returnWrapper } from '@amplitude/analytics-core';
2
+ import {
3
+ ReactNativeConfig,
4
+ Campaign,
5
+ ReactNativeOptions,
6
+ AdditionalReactNativeOptions,
7
+ AttributionReactNativeOptions,
8
+ } from '@amplitude/analytics-types';
9
+ import { Context } from './plugins/context';
10
+ import { useReactNativeConfig, createDeviceId, createFlexibleStorage } from './config';
11
+ import { parseOldCookies } from './cookie-migration';
12
+ import { CampaignTracker } from './attribution/campaign-tracker';
13
+ import { isNative } from './utils/platform';
14
+ import { IdentityEventSender } from './plugins/identity';
15
+ import { getAnalyticsConnector } from './utils/analytics-connector';
16
+
17
+ export class AmplitudeReactNative extends AmplitudeCore<ReactNativeConfig> {
18
+ async init(apiKey: string, userId?: string, options?: ReactNativeOptions & AdditionalReactNativeOptions) {
19
+ // Step 1: Read cookies stored by old SDK
20
+ const oldCookies = await parseOldCookies(apiKey, options);
21
+
22
+ // Step 2: Create react native config
23
+ const reactNativeOptions = await useReactNativeConfig(apiKey, userId || oldCookies.userId, {
24
+ ...options,
25
+ deviceId: oldCookies.deviceId ?? options?.deviceId,
26
+ sessionId: oldCookies.sessionId ?? options?.sessionId,
27
+ optOut: options?.optOut ?? oldCookies.optOut,
28
+ lastEventTime: oldCookies.lastEventTime,
29
+ });
30
+ await super.init(undefined, undefined, reactNativeOptions);
31
+
32
+ // Step 3: Manage session
33
+ let isNewSession = false;
34
+ if (
35
+ !this.config.sessionId ||
36
+ (this.config.lastEventTime && Date.now() - this.config.lastEventTime > this.config.sessionTimeout)
37
+ ) {
38
+ // Either
39
+ // 1) No previous session; or
40
+ // 2) Previous session expired
41
+ this.config.sessionId = Date.now();
42
+ isNewSession = true;
43
+ }
44
+
45
+ const connector = getAnalyticsConnector();
46
+ connector.eventBridge.setEventReceiver((event) => {
47
+ void this.track(event.eventType, event.eventProperties);
48
+ });
49
+ connector.identityStore.setIdentity({
50
+ userId: this.config.userId,
51
+ deviceId: this.config.deviceId,
52
+ });
53
+
54
+ // Step 4: Install plugins
55
+ // Do not track any events before this
56
+ await this.add(new Context());
57
+ await this.add(new IdentityEventSender());
58
+ await this.add(new Destination());
59
+
60
+ // Step 5: Track attributions
61
+ await this.runAttributionStrategy(options?.attribution, isNewSession);
62
+ }
63
+
64
+ async runAttributionStrategy(attributionConfig?: AttributionReactNativeOptions, isNewSession = false) {
65
+ if (isNative()) {
66
+ return;
67
+ }
68
+ const track = this.track.bind(this);
69
+ const onNewCampaign = this.setSessionId.bind(this, Date.now());
70
+
71
+ const storage = await createFlexibleStorage<Campaign>(this.config);
72
+ const campaignTracker = new CampaignTracker(this.config.apiKey, {
73
+ ...attributionConfig,
74
+ storage,
75
+ track,
76
+ onNewCampaign,
77
+ });
78
+
79
+ await campaignTracker.send(isNewSession);
80
+ }
81
+
82
+ getUserId() {
83
+ return this.config.userId;
84
+ }
85
+
86
+ setUserId(userId: string | undefined) {
87
+ this.config.userId = userId;
88
+ getAnalyticsConnector()
89
+ .identityStore.editIdentity()
90
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
91
+ // @ts-ignore
92
+ .setUserId(userId)
93
+ .commit();
94
+ }
95
+
96
+ getDeviceId() {
97
+ return this.config.deviceId;
98
+ }
99
+
100
+ setDeviceId(deviceId: string) {
101
+ this.config.deviceId = deviceId;
102
+ getAnalyticsConnector()
103
+ .identityStore.editIdentity()
104
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
105
+ // @ts-ignore
106
+ .setDeviceId(deviceId)
107
+ .commit();
108
+ }
109
+
110
+ regenerateDeviceId() {
111
+ const deviceId = createDeviceId();
112
+ this.setDeviceId(deviceId);
113
+ }
114
+
115
+ getSessionId() {
116
+ return this.config.sessionId;
117
+ }
118
+
119
+ setSessionId(sessionId: number) {
120
+ this.config.sessionId = sessionId;
121
+ }
122
+
123
+ setOptOut(optOut: boolean) {
124
+ this.config.optOut = optOut;
125
+ }
126
+ }
127
+
128
+ const client = new AmplitudeReactNative();
129
+
130
+ /**
131
+ * Initializes the Amplitude SDK with your apiKey, userId and optional configurations.
132
+ * This method must be called before any other operations.
133
+ *
134
+ * ```typescript
135
+ * await init(API_KEY, USER_ID, options).promise;
136
+ * ```
137
+ */
138
+ export const init = returnWrapper(client.init.bind(client));
139
+
140
+ /**
141
+ * Adds a new plugin.
142
+ *
143
+ * ```typescript
144
+ * const plugin = {...};
145
+ * amplitude.add(plugin);
146
+ * ```
147
+ */
148
+ export const add = returnWrapper(client.add.bind(client));
149
+
150
+ /**
151
+ * Removes a plugin.
152
+ *
153
+ * ```typescript
154
+ * amplitude.remove('myPlugin');
155
+ * ```
156
+ */
157
+ export const remove = returnWrapper(client.remove.bind(client));
158
+
159
+ /**
160
+ * Tracks user-defined event, with specified type, optional event properties and optional overwrites.
161
+ *
162
+ * ```typescript
163
+ * // event tracking with event type only
164
+ * track('Page Load');
165
+ *
166
+ * // event tracking with event type and additional event properties
167
+ * track('Page Load', { loadTime: 1000 });
168
+ *
169
+ * // event tracking with event type, additional event properties, and overwritten event options
170
+ * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });
171
+ *
172
+ * // alternatively, this tracking method is awaitable
173
+ * const result = await track('Page Load').promise;
174
+ * console.log(result.event); // {...}
175
+ * console.log(result.code); // 200
176
+ * console.log(result.message); // "Event tracked successfully"
177
+ * ```
178
+ */
179
+ export const track = returnWrapper(client.track.bind(client));
180
+
181
+ /**
182
+ * Alias for track()
183
+ */
184
+ export const logEvent = returnWrapper(client.logEvent.bind(client));
185
+
186
+ /**
187
+ * Sends an identify event containing user property operations
188
+ *
189
+ * ```typescript
190
+ * const id = new Identify();
191
+ * id.set('colors', ['rose', 'gold']);
192
+ * identify(id);
193
+ *
194
+ * // alternatively, this tracking method is awaitable
195
+ * const result = await identify(id).promise;
196
+ * console.log(result.event); // {...}
197
+ * console.log(result.code); // 200
198
+ * console.log(result.message); // "Event tracked successfully"
199
+ * ```
200
+ */
201
+ export const identify = returnWrapper(client.identify.bind(client));
202
+
203
+ /**
204
+ * Sends a group identify event containing group property operations.
205
+ *
206
+ * ```typescript
207
+ * const id = new Identify();
208
+ * id.set('skills', ['js', 'ts']);
209
+ * const groupType = 'org';
210
+ * const groupName = 'engineering';
211
+ * groupIdentify(groupType, groupName, id);
212
+ *
213
+ * // alternatively, this tracking method is awaitable
214
+ * const result = await groupIdentify(groupType, groupName, id).promise;
215
+ * console.log(result.event); // {...}
216
+ * console.log(result.code); // 200
217
+ * console.log(result.message); // "Event tracked successfully"
218
+ * ```
219
+ */
220
+ export const groupIdentify = returnWrapper(client.groupIdentify.bind(client));
221
+ export const setGroup = returnWrapper(client.setGroup.bind(client));
222
+
223
+ /**
224
+ * Sends a revenue event containing revenue property operations.
225
+ *
226
+ * ```typescript
227
+ * const rev = new Revenue();
228
+ * rev.setRevenue(100);
229
+ * revenue(rev);
230
+ *
231
+ * // alternatively, this tracking method is awaitable
232
+ * const result = await revenue(rev).promise;
233
+ * console.log(result.event); // {...}
234
+ * console.log(result.code); // 200
235
+ * console.log(result.message); // "Event tracked successfully"
236
+ * ```
237
+ */
238
+ export const revenue = returnWrapper(client.revenue.bind(client));
239
+
240
+ /**
241
+ * Returns current user ID.
242
+ *
243
+ * ```typescript
244
+ * const userId = getUserId();
245
+ * ```
246
+ */
247
+ export const getUserId = client.getUserId.bind(client);
248
+
249
+ /**
250
+ * Sets a new user ID.
251
+ *
252
+ * ```typescript
253
+ * setUserId('userId');
254
+ * ```
255
+ */
256
+ export const setUserId = client.setUserId.bind(client);
257
+
258
+ /**
259
+ * Returns current device ID.
260
+ *
261
+ * ```typescript
262
+ * const deviceId = getDeviceId();
263
+ * ```
264
+ */
265
+ export const getDeviceId = client.getDeviceId.bind(client);
266
+
267
+ /**
268
+ * Sets a new device ID.
269
+ * When setting a custom device ID, make sure the value is sufficiently unique.
270
+ * A uuid is recommended.
271
+ *
272
+ * ```typescript
273
+ * setDeviceId('deviceId');
274
+ * ```
275
+ */
276
+ export const setDeviceId = client.setDeviceId.bind(client);
277
+
278
+ /**
279
+ * Regenerates a new random deviceId for current user. Note: this is not recommended unless you know what you
280
+ * are doing. This can be used in conjunction with `setUserId(undefined)` to anonymize users after they log out.
281
+ * With an `unefined` userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.
282
+ *
283
+ * ```typescript
284
+ * regenerateDeviceId();
285
+ * ```
286
+ */
287
+ export const regenerateDeviceId = client.regenerateDeviceId.bind(client);
288
+
289
+ /**
290
+ * Returns current session ID.
291
+ *
292
+ * ```typescript
293
+ * const sessionId = getSessionId();
294
+ * ```
295
+ */
296
+ export const getSessionId = client.getSessionId.bind(client);
297
+
298
+ /**
299
+ * Sets a new session ID.
300
+ * When settign a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp).
301
+ *
302
+ * ```typescript
303
+ * setSessionId(Date.now());
304
+ * ```
305
+ */
306
+ export const setSessionId = client.setSessionId.bind(client);
307
+
308
+ /**
309
+ * Sets a new optOut config value. This toggles event tracking on/off.
310
+ *
311
+ *```typescript
312
+ * // Stops tracking
313
+ * setOptOut(true);
314
+ *
315
+ * // Starts/resumes tracking
316
+ * setOptOut(false);
317
+ * ```
318
+ */
319
+ export const setOptOut = client.setOptOut.bind(client);
320
+
321
+ /**
322
+ * Flush and send all the events which haven't been sent.
323
+ *
324
+ *```typescript
325
+ * // Send all the unsent events
326
+ * flush();
327
+ *
328
+ * // alternatively, this tracking method is awaitable
329
+ * await flush().promise;
330
+ * ```
331
+ */
332
+ export const flush = returnWrapper(client.flush.bind(client));
@@ -0,0 +1,81 @@
1
+ import { UserSession, Storage, SessionManager as ISessionManager } from '@amplitude/analytics-types';
2
+ import { getCookieName as getStorageKey } from './utils/cookie-name';
3
+
4
+ export class SessionManager implements ISessionManager {
5
+ storageKey: string;
6
+ cache: UserSession;
7
+ isSessionCacheValid = true;
8
+
9
+ constructor(private storage: Storage<UserSession>, apiKey: string) {
10
+ this.storageKey = getStorageKey(apiKey);
11
+ this.cache = { optOut: false };
12
+ }
13
+
14
+ /**
15
+ * load() must be called immediately after instantation
16
+ *
17
+ * ```ts
18
+ * await new SessionManager(...).load();
19
+ * ```
20
+ */
21
+ async load() {
22
+ this.cache = (await this.storage.get(this.storageKey)) ?? {
23
+ optOut: false,
24
+ };
25
+ return this;
26
+ }
27
+
28
+ setSession(session: Partial<UserSession>) {
29
+ this.cache = { ...this.cache, ...session };
30
+ void this.storage.set(this.storageKey, this.cache);
31
+ }
32
+
33
+ getSessionId() {
34
+ this.isSessionCacheValid = true;
35
+ void this.storage.get(this.storageKey).then((userSession) => {
36
+ // Checks if session id has been set since the last get
37
+ if (this.isSessionCacheValid) {
38
+ this.cache.sessionId = userSession?.sessionId;
39
+ }
40
+ });
41
+ return this.cache.sessionId;
42
+ }
43
+
44
+ setSessionId(sessionId: number) {
45
+ // Flags session id has been set
46
+ this.isSessionCacheValid = false;
47
+ this.setSession({ sessionId });
48
+ }
49
+
50
+ getDeviceId(): string | undefined {
51
+ return this.cache.deviceId;
52
+ }
53
+
54
+ setDeviceId(deviceId: string): void {
55
+ this.setSession({ deviceId });
56
+ }
57
+
58
+ getUserId(): string | undefined {
59
+ return this.cache.userId;
60
+ }
61
+
62
+ setUserId(userId: string): void {
63
+ this.setSession({ userId });
64
+ }
65
+
66
+ getLastEventTime() {
67
+ return this.cache.lastEventTime;
68
+ }
69
+
70
+ setLastEventTime(lastEventTime: number) {
71
+ this.setSession({ lastEventTime });
72
+ }
73
+
74
+ getOptOut(): boolean {
75
+ return this.cache.optOut;
76
+ }
77
+
78
+ setOptOut(optOut: boolean): void {
79
+ this.setSession({ optOut });
80
+ }
81
+ }
@@ -0,0 +1,97 @@
1
+ import { Storage, CookieStorageOptions } from '@amplitude/analytics-types';
2
+ import { isNative } from '../utils/platform';
3
+
4
+ export class CookieStorage<T> implements Storage<T> {
5
+ options: CookieStorageOptions;
6
+
7
+ constructor(options?: CookieStorageOptions) {
8
+ this.options = { ...options };
9
+ }
10
+
11
+ async isEnabled(): Promise<boolean> {
12
+ /* istanbul ignore if */
13
+ if (isNative() || typeof window === 'undefined') {
14
+ return false;
15
+ }
16
+
17
+ const random = String(Date.now());
18
+ const testStrorage = new CookieStorage<string>();
19
+ const testKey = 'AMP_TEST';
20
+ try {
21
+ await testStrorage.set(testKey, random);
22
+ const value = await testStrorage.get(testKey);
23
+ return value === random;
24
+ } catch {
25
+ /* istanbul ignore next */
26
+ return false;
27
+ } finally {
28
+ await testStrorage.remove(testKey);
29
+ }
30
+ }
31
+
32
+ async get(key: string): Promise<T | undefined> {
33
+ let value = await this.getRaw(key);
34
+ if (!value) {
35
+ return undefined;
36
+ }
37
+ try {
38
+ try {
39
+ value = decodeURIComponent(atob(value));
40
+ } catch {
41
+ // value not encoded
42
+ }
43
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
44
+ return JSON.parse(value);
45
+ } catch {
46
+ /* istanbul ignore next */
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ async getRaw(key: string): Promise<string | undefined> {
52
+ const cookie = window.document.cookie.split('; ');
53
+ const match = cookie.find((c) => c.indexOf(key + '=') === 0);
54
+ if (!match) {
55
+ return undefined;
56
+ }
57
+ return match.substring(key.length + 1);
58
+ }
59
+
60
+ async set(key: string, value: T | null): Promise<void> {
61
+ try {
62
+ const expirationDays = this.options.expirationDays ?? 0;
63
+ const expires = value !== null ? expirationDays : -1;
64
+ let expireDate: Date | undefined = undefined;
65
+ if (expires) {
66
+ const date = new Date();
67
+ date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
68
+ expireDate = date;
69
+ }
70
+ let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;
71
+ if (expireDate) {
72
+ str += `; expires=${expireDate.toUTCString()}`;
73
+ }
74
+ str += '; path=/';
75
+ if (this.options.domain) {
76
+ str += `; domain=${this.options.domain}`;
77
+ }
78
+ if (this.options.secure) {
79
+ str += '; Secure';
80
+ }
81
+ if (this.options.sameSite) {
82
+ str += `; SameSite=${this.options.sameSite}`;
83
+ }
84
+ window.document.cookie = str;
85
+ } catch {
86
+ //
87
+ }
88
+ }
89
+
90
+ async remove(key: string): Promise<void> {
91
+ await this.set(key, null);
92
+ }
93
+
94
+ async reset(): Promise<void> {
95
+ return;
96
+ }
97
+ }
@@ -0,0 +1,67 @@
1
+ import { Storage } from '@amplitude/analytics-types';
2
+ import AsyncStorage from '@react-native-async-storage/async-storage';
3
+
4
+ export class LocalStorage<T> implements Storage<T> {
5
+ async isEnabled(): Promise<boolean> {
6
+ /* istanbul ignore if */
7
+ if (typeof window === 'undefined') {
8
+ return false;
9
+ }
10
+
11
+ const random = String(Date.now());
12
+ const testStorage = new LocalStorage<string>();
13
+ const testKey = 'AMP_TEST';
14
+ try {
15
+ await testStorage.set(testKey, random);
16
+ const value = await testStorage.get(testKey);
17
+ return value === random;
18
+ } catch {
19
+ /* istanbul ignore next */
20
+ return false;
21
+ } finally {
22
+ await testStorage.remove(testKey);
23
+ }
24
+ }
25
+
26
+ async get(key: string): Promise<T | undefined> {
27
+ try {
28
+ const value = await this.getRaw(key);
29
+ if (!value) {
30
+ return undefined;
31
+ }
32
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
33
+ return JSON.parse(value);
34
+ } catch {
35
+ /* istanbul ignore next */
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ async getRaw(key: string): Promise<string | undefined> {
41
+ return (await AsyncStorage.getItem(key)) || undefined;
42
+ }
43
+
44
+ async set(key: string, value: T): Promise<void> {
45
+ try {
46
+ await AsyncStorage.setItem(key, JSON.stringify(value));
47
+ } catch {
48
+ //
49
+ }
50
+ }
51
+
52
+ async remove(key: string): Promise<void> {
53
+ try {
54
+ await AsyncStorage.removeItem(key);
55
+ } catch {
56
+ //
57
+ }
58
+ }
59
+
60
+ async reset(): Promise<void> {
61
+ try {
62
+ await AsyncStorage.clear();
63
+ } catch {
64
+ //
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,27 @@
1
+ import { CookieStorage } from './cookie';
2
+
3
+ export class UTMCookie extends CookieStorage<Record<string, string | undefined>> {
4
+ async get(key: string): Promise<Record<string, string | undefined> | undefined> {
5
+ try {
6
+ const value = await this.getRaw(key);
7
+ if (!value) {
8
+ return undefined;
9
+ }
10
+ const entries = value.split('.').splice(-1)[0].split('|');
11
+ return entries.reduce<Record<string, string | undefined>>((acc, curr) => {
12
+ const [key, value = ''] = curr.split('=', 2);
13
+ if (!value) {
14
+ return acc;
15
+ }
16
+ acc[key] = decodeURIComponent(value);
17
+ return acc;
18
+ }, {});
19
+ } catch {
20
+ return undefined;
21
+ }
22
+ }
23
+
24
+ async set(): Promise<void> {
25
+ return undefined;
26
+ }
27
+ }
@@ -0,0 +1,23 @@
1
+ import { BaseTransport } from '@amplitude/analytics-core';
2
+ import { Payload, Response, Transport } from '@amplitude/analytics-types';
3
+
4
+ export class FetchTransport extends BaseTransport implements Transport {
5
+ async send(serverUrl: string, payload: Payload): Promise<Response | null> {
6
+ /* istanbul ignore if */
7
+ if (typeof fetch === 'undefined') {
8
+ throw new Error('FetchTransport is not supported');
9
+ }
10
+ const options: RequestInit = {
11
+ headers: {
12
+ 'Content-Type': 'application/json',
13
+ Accept: '*/*',
14
+ },
15
+ body: JSON.stringify(payload),
16
+ method: 'POST',
17
+ };
18
+ const response = await fetch(serverUrl, options);
19
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
20
+ const responsePayload: Record<string, any> = await response.json();
21
+ return this.buildResponse(responsePayload);
22
+ }
23
+ }
@@ -0,0 +1,7 @@
1
+ import { InstanceProxy } from '@amplitude/analytics-types';
2
+
3
+ declare global {
4
+ // globalThis only includes `var` declarations
5
+ // eslint-disable-next-line no-var
6
+ var amplitude: InstanceProxy & { invoked: boolean };
7
+ }
@@ -0,0 +1,4 @@
1
+ declare module '@amplitude/ua-parser-js' {
2
+ import UAParser from 'ua-parser-js';
3
+ export = UAParser;
4
+ }
@@ -0,0 +1,5 @@
1
+ import { AnalyticsConnector } from '@amplitude/analytics-connector';
2
+
3
+ export const getAnalyticsConnector = (): AnalyticsConnector => {
4
+ return AnalyticsConnector.getInstance('$default_instance');
5
+ };
@@ -0,0 +1,9 @@
1
+ import { AMPLITUDE_PREFIX } from '@amplitude/analytics-core';
2
+
3
+ export const getCookieName = (apiKey: string, postKey = '', limit = 10) => {
4
+ return [AMPLITUDE_PREFIX, postKey, apiKey.substring(0, limit)].filter(Boolean).join('_');
5
+ };
6
+
7
+ export const getOldCookieName = (apiKey: string) => {
8
+ return `${AMPLITUDE_PREFIX.toLowerCase()}_${apiKey.substring(0, 6)}`;
9
+ };
@@ -0,0 +1,7 @@
1
+ export const getLanguage = (): string => {
2
+ if (typeof navigator === 'undefined') return '';
3
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
4
+ const userLanguage = (navigator as any).userLanguage as string | undefined;
5
+
6
+ return navigator.languages?.[0] ?? navigator.language ?? userLanguage ?? '';
7
+ };
@@ -0,0 +1,9 @@
1
+ import { Platform } from 'react-native';
2
+
3
+ export const isWeb = (): boolean => {
4
+ return Platform.OS === 'web';
5
+ };
6
+
7
+ export const isNative = (): boolean => {
8
+ return !isWeb();
9
+ };