@amplitude/analytics-react-native 1.6.6 → 1.6.8

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 (56) hide show
  1. package/android/src/main/java/com/amplitude/reactnative/AmplitudeReactNativeModule.kt +1 -0
  2. package/android/src/main/java/com/amplitude/reactnative/AndroidContextProvider.kt +19 -0
  3. package/ios/AmplitudeReactNative.swift +1 -0
  4. package/ios/AppleContextProvider.swift +5 -0
  5. package/lib/commonjs/amp-capture.js +42 -0
  6. package/lib/commonjs/amp-capture.js.map +1 -0
  7. package/lib/commonjs/config/joined-config.js +76 -0
  8. package/lib/commonjs/config/joined-config.js.map +1 -0
  9. package/lib/commonjs/config.js +48 -2
  10. package/lib/commonjs/config.js.map +1 -1
  11. package/lib/commonjs/constants.js +13 -1
  12. package/lib/commonjs/constants.js.map +1 -1
  13. package/lib/commonjs/index.js +7 -0
  14. package/lib/commonjs/index.js.map +1 -1
  15. package/lib/commonjs/plugins/context.js.map +1 -1
  16. package/lib/commonjs/react-native-client.js +175 -13
  17. package/lib/commonjs/react-native-client.js.map +1 -1
  18. package/lib/commonjs/version.js +1 -1
  19. package/lib/module/amp-capture.js +35 -0
  20. package/lib/module/amp-capture.js.map +1 -0
  21. package/lib/module/config/joined-config.js +71 -0
  22. package/lib/module/config/joined-config.js.map +1 -0
  23. package/lib/module/config.js +46 -1
  24. package/lib/module/config.js.map +1 -1
  25. package/lib/module/constants.js +12 -0
  26. package/lib/module/constants.js.map +1 -1
  27. package/lib/module/index.js +1 -0
  28. package/lib/module/index.js.map +1 -1
  29. package/lib/module/plugins/context.js.map +1 -1
  30. package/lib/module/react-native-client.js +178 -17
  31. package/lib/module/react-native-client.js.map +1 -1
  32. package/lib/module/version.js +1 -1
  33. package/lib/typescript/amp-capture.d.ts +10 -0
  34. package/lib/typescript/amp-capture.d.ts.map +1 -0
  35. package/lib/typescript/config/joined-config.d.ts +14 -0
  36. package/lib/typescript/config/joined-config.d.ts.map +1 -0
  37. package/lib/typescript/config.d.ts +19 -2
  38. package/lib/typescript/config.d.ts.map +1 -1
  39. package/lib/typescript/constants.d.ts +12 -0
  40. package/lib/typescript/constants.d.ts.map +1 -1
  41. package/lib/typescript/index.d.ts +1 -0
  42. package/lib/typescript/index.d.ts.map +1 -1
  43. package/lib/typescript/plugins/context.d.ts +1 -0
  44. package/lib/typescript/plugins/context.d.ts.map +1 -1
  45. package/lib/typescript/react-native-client.d.ts +7 -0
  46. package/lib/typescript/react-native-client.d.ts.map +1 -1
  47. package/lib/typescript/version.d.ts +1 -1
  48. package/package.json +3 -2
  49. package/src/amp-capture.ts +48 -0
  50. package/src/config/joined-config.ts +101 -0
  51. package/src/config.ts +48 -4
  52. package/src/constants.ts +12 -0
  53. package/src/index.ts +2 -0
  54. package/src/plugins/context.ts +1 -0
  55. package/src/react-native-client.ts +222 -4
  56. package/src/version.ts +1 -1
@@ -1,4 +1,4 @@
1
- import { AppState, AppStateStatus, NativeEventSubscription } from 'react-native';
1
+ import { AppState, AppStateStatus, NativeEventSubscription, NativeModules, Platform } from 'react-native';
2
2
  import {
3
3
  AmplitudeCore,
4
4
  Destination,
@@ -23,23 +23,46 @@ import {
23
23
  SpecialEventType,
24
24
  AnalyticsClient,
25
25
  OfflineDisabled,
26
+ Logger,
27
+ LogLevel,
28
+ IRemoteConfigClient,
29
+ RemoteConfigClient,
30
+ RemoteConfig,
31
+ Source,
26
32
  ReactNativeAutocaptureOptions,
27
- ReactNativeConfigAutocaptureBeta,
28
33
  NavigationState,
34
+ NetworkTrackingOptions,
35
+ normalizeNetworkCaptureRules,
36
+ safeJsonStringify,
29
37
  } from '@amplitude/analytics-core';
38
+ import { plugin as networkCapturePlugin } from '@amplitude/plugin-network-capture-browser';
30
39
  import { CampaignTracker } from './campaign/campaign-tracker';
31
40
  import { Context } from './plugins/context';
32
41
  import { networkConnectivityCheckerPlugin } from './plugins/network-connectivity-checker';
33
- import { useReactNativeConfig, createCookieStorage } from './config';
42
+ import { useReactNativeConfig, createCookieStorage, shouldFetchRemoteConfig } from './config';
43
+ import { updateReactNativeConfigWithRemoteConfig } from './config/joined-config';
34
44
  import { parseOldCookies } from './cookie-migration';
35
45
  import { isNative } from './utils/platform';
46
+ import * as Capture from './amp-capture';
36
47
  import {
48
+ APP_BUILD,
49
+ APP_VERSION,
37
50
  DEFAULT_APPLICATION_BACKGROUNDED_EVENT,
51
+ DEFAULT_APPLICATION_INSTALLED_EVENT,
38
52
  DEFAULT_APPLICATION_OPENED_EVENT,
53
+ DEFAULT_ELEMENT_INTERACTED_EVENT,
54
+ DEFAULT_APPLICATION_UPDATED_EVENT,
39
55
  DEFAULT_SCREEN_VIEWED_EVENT,
40
56
  DEFAULT_SESSION_END_EVENT,
41
57
  DEFAULT_SESSION_START_EVENT,
58
+ PREVIOUS_BUILD,
59
+ PREVIOUS_VERSION,
42
60
  SCREEN_NAME,
61
+ TARGET_ACCESSIBILITY_LABEL,
62
+ TARGET_ACTION,
63
+ TARGET_COMPONENT,
64
+ TARGET_ELEMENT,
65
+ TARGET_TEST_ID,
43
66
  } from './constants';
44
67
 
45
68
  /**
@@ -62,6 +85,19 @@ const getActiveRouteName = (navigationState: NavigationState): string | undefine
62
85
  return routeName;
63
86
  };
64
87
 
88
+ // TODO: Remove IS_DIAGNOSTICS_CAPTURED when we're ready for diagnostics capture
89
+ const IS_DIAGNOSTICS_CAPTURED = false;
90
+ const getNetworkTrackingConfig = (config: ReactNativeConfig): NetworkTrackingOptions | undefined => {
91
+ let networkTrackingConfig;
92
+ if (typeof config.autocapture === 'object' && typeof config.autocapture.networkTracking === 'object') {
93
+ networkTrackingConfig = config.autocapture.networkTracking;
94
+ }
95
+ return {
96
+ ...networkTrackingConfig,
97
+ captureRules: normalizeNetworkCaptureRules(networkTrackingConfig?.captureRules, config.loggerProvider),
98
+ };
99
+ };
100
+
65
101
  export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeClient, AnalyticsClient {
66
102
  appState: AppStateStatus = 'background';
67
103
  /**
@@ -77,12 +113,14 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
77
113
  */
78
114
  private lastNavigationScreenName: string | undefined;
79
115
  private appStateChangeHandler: NativeEventSubscription | undefined;
116
+ private currentScreenName: string | undefined;
80
117
  explicitSessionId: number | undefined;
81
118
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
82
119
  // @ts-ignore
83
120
  config: ReactNativeConfig;
84
121
  userProperties: { [key: string]: any } | undefined;
85
122
  autocapture: ReactNativeAutocaptureOptions | null = null;
123
+ captureUnsubscribe: (() => void) | undefined;
86
124
 
87
125
  init(apiKey = '', userId?: string, options?: ReactNativeOptions) {
88
126
  return returnWrapper(this._init({ ...options, userId, apiKey }));
@@ -95,26 +133,121 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
95
133
  this.initializing = true;
96
134
  this.explicitSessionId = options.sessionId;
97
135
 
136
+ // Step 0.1: Get remote config dependencies ready
137
+ const fetchRemoteConfig = shouldFetchRemoteConfig(options);
138
+ const loggerProvider = options.loggerProvider ?? new Logger();
139
+ if (!options.loggerProvider) {
140
+ loggerProvider.enable(options.logLevel ?? LogLevel.Warn);
141
+ }
142
+ const serverZone = options.serverZone ?? 'US';
143
+ let remoteConfigClient: IRemoteConfigClient | undefined;
144
+
145
+ // Step 0.2: Fetch diagnostics config
146
+ // let diagnosticsSampleRate: number;
147
+ // let enableDiagnostics: boolean = false;
148
+ if (fetchRemoteConfig) {
149
+ remoteConfigClient = new RemoteConfigClient(
150
+ options.apiKey,
151
+ loggerProvider,
152
+ serverZone,
153
+ /* istanbul ignore next */ options.remoteConfig?.serverUrl,
154
+ );
155
+ // Diagnostics capture is intentionally disabled for React Native until ready.
156
+ /* istanbul ignore if */
157
+ if (IS_DIAGNOSTICS_CAPTURED) {
158
+ await new Promise<void>((resolve) => {
159
+ remoteConfigClient?.subscribe(
160
+ 'configs.diagnostics.reactNativeSDK',
161
+ 'all',
162
+ (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => {
163
+ loggerProvider.debug(
164
+ 'Diagnostics remote configuration received:',
165
+ safeJsonStringify(
166
+ {
167
+ remoteConfig,
168
+ source,
169
+ lastFetch,
170
+ },
171
+ null,
172
+ 2,
173
+ ),
174
+ );
175
+ if (remoteConfig) {
176
+ // Validate and set sampleRate (must be a valid number)
177
+ // const sampleRate = remoteConfig.sampleRate as number;
178
+ // if (typeof sampleRate === 'number' && !isNaN(sampleRate)) {
179
+ // diagnosticsSampleRate = sampleRate;
180
+ // }
181
+ // // Validate and set enabled (must be a boolean)
182
+ // const enabled = remoteConfig.enabled as boolean;
183
+ // if (typeof enabled === 'boolean') {
184
+ // enableDiagnostics = enabled;
185
+ // }
186
+ }
187
+ resolve();
188
+ },
189
+ );
190
+ });
191
+ }
192
+ }
193
+
98
194
  // Step 1: Read cookies stored by old SDK
99
195
  const oldCookies = await parseOldCookies(options.apiKey, options);
100
196
 
101
197
  // Step 2: Create react native config
198
+ // Pass early loggerProvider/serverZone so RemoteConfigClient and final config share the same instances
199
+ // (mirrors browser earlyConfig).
102
200
  const reactNativeOptions = await useReactNativeConfig(options.apiKey, {
103
201
  ...options,
202
+ loggerProvider,
203
+ serverZone,
104
204
  deviceId: options.deviceId ?? oldCookies.deviceId,
105
205
  sessionId: oldCookies.sessionId,
106
206
  optOut: options.optOut ?? oldCookies.optOut,
107
207
  lastEventTime: oldCookies.lastEventTime,
108
208
  userId: options.userId ?? oldCookies.userId,
109
209
  });
210
+
211
+ // Step 2.1: Fetch remote config
212
+ if (fetchRemoteConfig && remoteConfigClient) {
213
+ await new Promise<void>((resolve) => {
214
+ remoteConfigClient?.subscribe(
215
+ 'configs.analyticsSDK.reactNativeSDK',
216
+ 'all',
217
+ (remoteConfig: RemoteConfig | null, source: Source, lastFetch: Date) => {
218
+ loggerProvider.debug(
219
+ 'Remote configuration received:',
220
+ safeJsonStringify(
221
+ {
222
+ remoteConfig,
223
+ source,
224
+ lastFetch,
225
+ },
226
+ null,
227
+ 2,
228
+ ),
229
+ );
230
+ if (remoteConfig) {
231
+ updateReactNativeConfigWithRemoteConfig(remoteConfig, reactNativeOptions);
232
+ }
233
+ resolve();
234
+ },
235
+ );
236
+ });
237
+ }
238
+
110
239
  await super._init(reactNativeOptions);
240
+ this.config.remoteConfigClient = remoteConfigClient;
111
241
 
112
242
  // Step 2.1: parse autocapture config (always reset so re-init clears prior flags)
113
- const autocaptureConfig = (this.config as ReactNativeConfigAutocaptureBeta).autocapture;
243
+ const autocaptureConfig = this.config.autocapture;
114
244
  if (autocaptureConfig === true) {
115
245
  this.autocapture = {
116
246
  appLifecycles: true,
117
247
  sessions: true,
248
+ screenViews: true,
249
+ elementInteractions: true,
250
+ networkTracking: true,
118
251
  };
119
252
  } else if (autocaptureConfig && typeof autocaptureConfig === 'object') {
120
253
  this.autocapture = autocaptureConfig;
@@ -125,6 +258,12 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
125
258
  this.wasBackgrounded = false;
126
259
  // Allow the first navigation screen view after re-init.
127
260
  this.lastNavigationScreenName = undefined;
261
+ this.currentScreenName = undefined;
262
+
263
+ if (typeof this.captureUnsubscribe === 'function') {
264
+ this.captureUnsubscribe();
265
+ this.captureUnsubscribe = undefined;
266
+ }
128
267
 
129
268
  // Set up the analytics connector to integrate with the experiment SDK.
130
269
  // Send events from the experiment SDK and forward identifies to the
@@ -146,6 +285,25 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
146
285
  await this.add(new Context()).promise;
147
286
  await this.add(new IdentityEventSender()).promise;
148
287
 
288
+ if (this.autocapture?.networkTracking) {
289
+ this.config.loggerProvider.debug('Adding network tracking plugin');
290
+ await this.add(networkCapturePlugin(getNetworkTrackingConfig(this.config))).promise;
291
+ }
292
+
293
+ if (this.autocapture?.elementInteractions === true) {
294
+ this.captureUnsubscribe = Capture.subscribe((properties) => {
295
+ const analyticsProps = {
296
+ [SCREEN_NAME]: this.currentScreenName,
297
+ [TARGET_ACCESSIBILITY_LABEL]: properties.accessibilityLabel,
298
+ [TARGET_ACTION]: properties.action,
299
+ [TARGET_COMPONENT]: properties.component,
300
+ [TARGET_ELEMENT]: properties.element,
301
+ [TARGET_TEST_ID]: properties.testID,
302
+ };
303
+ this.track(DEFAULT_ELEMENT_INTERACTED_EVENT, analyticsProps);
304
+ });
305
+ }
306
+
149
307
  // Step 4: Manage session
150
308
  this.appState = AppState.currentState;
151
309
  const isNewSession = this.startNewSessionIfNeeded(this.currentTimeMillis());
@@ -154,6 +312,9 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
154
312
  this.getSessionId() ?? 'undefined'
155
313
  }`,
156
314
  );
315
+ if (this.appStateChangeHandler) {
316
+ this.appStateChangeHandler.remove?.();
317
+ }
157
318
  this.appStateChangeHandler = AppState.addEventListener('change', this.handleAppStateChange);
158
319
 
159
320
  this.initializing = false;
@@ -166,6 +327,8 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
166
327
  this.track('[Amplitude] Application Opened');
167
328
  }
168
329
 
330
+ await this.trackAppInstallOrUpdate();
331
+
169
332
  // Step 5.2: run attribution strategy
170
333
  await this.runAttributionStrategy(options.attribution, isNewSession);
171
334
 
@@ -180,6 +343,7 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
180
343
 
181
344
  shutdown() {
182
345
  this.appStateChangeHandler?.remove();
346
+ this.captureUnsubscribe?.();
183
347
  }
184
348
 
185
349
  async runAttributionStrategy(attributionConfig?: AttributionOptions, isNewSession = false) {
@@ -241,6 +405,7 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
241
405
  this.setDeviceId(UUID());
242
406
  // Allow the current focused route to emit again for the new identity.
243
407
  this.lastNavigationScreenName = undefined;
408
+ this.currentScreenName = undefined;
244
409
  }
245
410
 
246
411
  getSessionId() {
@@ -282,6 +447,7 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
282
447
  if (isScreenViewTrackingDisabled) {
283
448
  return returnWrapper(Promise.resolve(undefined));
284
449
  }
450
+ this.currentScreenName = screenName;
285
451
  return this.track(
286
452
  DEFAULT_SCREEN_VIEWED_EVENT,
287
453
  {
@@ -432,6 +598,58 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
432
598
  }
433
599
  };
434
600
 
601
+ /**
602
+ * Tracks Application Installed / Updated from persisted version + build on UserSession.
603
+ * Only runs on iOS/Android; skips web and when the native module is unavailable.
604
+ */
605
+ private async trackAppInstallOrUpdate() {
606
+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {
607
+ return;
608
+ }
609
+
610
+ const nativeModule = NativeModules.AmplitudeReactNative as
611
+ | { getApplicationContext: (options: unknown) => Promise<Record<string, string> | undefined> }
612
+ | undefined;
613
+ if (this.autocapture?.appLifecycles !== true || !nativeModule?.getApplicationContext) {
614
+ return;
615
+ }
616
+
617
+ const nativeContext = await nativeModule.getApplicationContext(this.config.trackingOptions);
618
+ const version = nativeContext?.version;
619
+ const build = nativeContext?.build;
620
+ const previousVersion = this.config.persistedAppVersion;
621
+ const previousBuild = this.config.persistedAppBuild;
622
+ // iOS (Amplitude-Swift): missing previous version or build => install; either changing => update.
623
+ // Android (Amplitude-Kotlin): build-only — missing previous build => install; build change => update.
624
+ const isIOS = Platform.OS === 'ios';
625
+ const isInstall = isIOS
626
+ ? previousBuild === undefined || previousVersion === undefined
627
+ : previousBuild === undefined;
628
+ const isUpdate = isIOS
629
+ ? (build !== undefined && previousBuild !== build) || (version !== undefined && previousVersion !== version)
630
+ : build !== undefined && previousBuild !== build;
631
+
632
+ if (isInstall) {
633
+ this.track(DEFAULT_APPLICATION_INSTALLED_EVENT, {
634
+ [APP_VERSION]: version,
635
+ [APP_BUILD]: build,
636
+ });
637
+ } else if (isUpdate) {
638
+ this.track(DEFAULT_APPLICATION_UPDATED_EVENT, {
639
+ [APP_VERSION]: version,
640
+ [APP_BUILD]: build,
641
+ [PREVIOUS_VERSION]: previousVersion,
642
+ [PREVIOUS_BUILD]: previousBuild,
643
+ });
644
+ }
645
+ if (version !== undefined) {
646
+ this.config.persistedAppVersion = version;
647
+ }
648
+ if (build !== undefined) {
649
+ this.config.persistedAppBuild = build;
650
+ }
651
+ }
652
+
435
653
  private enterForeground(timestamp: number) {
436
654
  this.config.loggerProvider?.log('App Activated');
437
655
  // Only emit Application Opened after a real background (not inactive→active).
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '1.6.6';
1
+ export const VERSION = '1.6.8';