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

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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/lib/commonjs/config.js +17 -9
  4. package/lib/commonjs/config.js.map +1 -1
  5. package/lib/commonjs/index.js +2 -2
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/plugins/identity.js +1 -1
  8. package/lib/commonjs/plugins/identity.js.map +1 -1
  9. package/lib/commonjs/react-native-client.js +10 -2
  10. package/lib/commonjs/react-native-client.js.map +1 -1
  11. package/lib/commonjs/version.js +1 -1
  12. package/lib/commonjs/version.js.map +1 -1
  13. package/lib/module/config.js +17 -9
  14. package/lib/module/config.js.map +1 -1
  15. package/lib/module/index.js +5 -3
  16. package/lib/module/index.js.map +1 -1
  17. package/lib/module/plugins/identity.js +1 -1
  18. package/lib/module/plugins/identity.js.map +1 -1
  19. package/lib/module/react-native-client.js +10 -2
  20. package/lib/module/react-native-client.js.map +1 -1
  21. package/lib/module/version.js +1 -1
  22. package/lib/module/version.js.map +1 -1
  23. package/lib/typescript/attribution/campaign-tracker.d.ts +0 -1
  24. package/lib/typescript/attribution/campaign-tracker.d.ts.map +1 -1
  25. package/lib/typescript/config.d.ts +1 -1
  26. package/lib/typescript/config.d.ts.map +1 -1
  27. package/lib/typescript/index.d.ts +2 -1
  28. package/lib/typescript/index.d.ts.map +1 -1
  29. package/lib/typescript/react-native-client.d.ts.map +1 -1
  30. package/lib/typescript/version.d.ts +1 -1
  31. package/lib/typescript/version.d.ts.map +1 -1
  32. package/package.json +11 -9
  33. package/src/attribution/campaign-parser.ts +78 -0
  34. package/src/attribution/campaign-tracker.ts +112 -0
  35. package/src/attribution/constants.ts +32 -0
  36. package/src/config.ts +236 -0
  37. package/src/cookie-migration/index.ts +54 -0
  38. package/src/index.ts +24 -0
  39. package/src/plugins/context.ts +106 -0
  40. package/src/plugins/identity.ts +21 -0
  41. package/src/react-native-client.ts +339 -0
  42. package/src/session-manager.ts +81 -0
  43. package/src/storage/cookie.ts +97 -0
  44. package/src/storage/local-storage.ts +67 -0
  45. package/src/storage/utm-cookie.ts +27 -0
  46. package/src/transports/fetch.ts +23 -0
  47. package/src/typings/browser-snippet.d.ts +7 -0
  48. package/src/typings/ua-parser.d.ts +4 -0
  49. package/src/utils/analytics-connector.ts +5 -0
  50. package/src/utils/cookie-name.ts +9 -0
  51. package/src/utils/language.ts +7 -0
  52. package/src/utils/platform.ts +9 -0
  53. package/src/utils/query-params.ts +18 -0
  54. package/src/version.ts +1 -0
@@ -0,0 +1,339 @@
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(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: Set timeline ready for processing events
61
+ // Send existing events, which might be collected by track before init
62
+ this.timeline.isReady = true;
63
+ if (!this.config.optOut) {
64
+ this.timeline.scheduleApply(0);
65
+ }
66
+
67
+ // Step 6: Track attributions
68
+ await this.runAttributionStrategy(options?.attribution, isNewSession);
69
+ }
70
+
71
+ async runAttributionStrategy(attributionConfig?: AttributionReactNativeOptions, isNewSession = false) {
72
+ if (isNative()) {
73
+ return;
74
+ }
75
+ const track = this.track.bind(this);
76
+ const onNewCampaign = this.setSessionId.bind(this, Date.now());
77
+
78
+ const storage = await createFlexibleStorage<Campaign>(this.config);
79
+ const campaignTracker = new CampaignTracker(this.config.apiKey, {
80
+ ...attributionConfig,
81
+ storage,
82
+ track,
83
+ onNewCampaign,
84
+ });
85
+
86
+ await campaignTracker.send(isNewSession);
87
+ }
88
+
89
+ getUserId() {
90
+ return this.config.userId;
91
+ }
92
+
93
+ setUserId(userId: string | undefined) {
94
+ this.config.userId = userId;
95
+ getAnalyticsConnector()
96
+ .identityStore.editIdentity()
97
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
98
+ // @ts-ignore
99
+ .setUserId(userId)
100
+ .commit();
101
+ }
102
+
103
+ getDeviceId() {
104
+ return this.config.deviceId;
105
+ }
106
+
107
+ setDeviceId(deviceId: string) {
108
+ this.config.deviceId = deviceId;
109
+ getAnalyticsConnector()
110
+ .identityStore.editIdentity()
111
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
112
+ // @ts-ignore
113
+ .setDeviceId(deviceId)
114
+ .commit();
115
+ }
116
+
117
+ regenerateDeviceId() {
118
+ const deviceId = createDeviceId();
119
+ this.setDeviceId(deviceId);
120
+ }
121
+
122
+ getSessionId() {
123
+ return this.config.sessionId;
124
+ }
125
+
126
+ setSessionId(sessionId: number) {
127
+ this.config.sessionId = sessionId;
128
+ }
129
+
130
+ setOptOut(optOut: boolean) {
131
+ this.config.optOut = optOut;
132
+ }
133
+ }
134
+
135
+ const client = new AmplitudeReactNative();
136
+
137
+ /**
138
+ * Initializes the Amplitude SDK with your apiKey, userId and optional configurations.
139
+ * This method must be called before any other operations.
140
+ *
141
+ * ```typescript
142
+ * await init(API_KEY, USER_ID, options).promise;
143
+ * ```
144
+ */
145
+ export const init = returnWrapper(client.init.bind(client));
146
+
147
+ /**
148
+ * Adds a new plugin.
149
+ *
150
+ * ```typescript
151
+ * const plugin = {...};
152
+ * amplitude.add(plugin);
153
+ * ```
154
+ */
155
+ export const add = returnWrapper(client.add.bind(client));
156
+
157
+ /**
158
+ * Removes a plugin.
159
+ *
160
+ * ```typescript
161
+ * amplitude.remove('myPlugin');
162
+ * ```
163
+ */
164
+ export const remove = returnWrapper(client.remove.bind(client));
165
+
166
+ /**
167
+ * Tracks user-defined event, with specified type, optional event properties and optional overwrites.
168
+ *
169
+ * ```typescript
170
+ * // event tracking with event type only
171
+ * track('Page Load');
172
+ *
173
+ * // event tracking with event type and additional event properties
174
+ * track('Page Load', { loadTime: 1000 });
175
+ *
176
+ * // event tracking with event type, additional event properties, and overwritten event options
177
+ * track('Page Load', { loadTime: 1000 }, { sessionId: -1 });
178
+ *
179
+ * // alternatively, this tracking method is awaitable
180
+ * const result = await track('Page Load').promise;
181
+ * console.log(result.event); // {...}
182
+ * console.log(result.code); // 200
183
+ * console.log(result.message); // "Event tracked successfully"
184
+ * ```
185
+ */
186
+ export const track = returnWrapper(client.track.bind(client));
187
+
188
+ /**
189
+ * Alias for track()
190
+ */
191
+ export const logEvent = returnWrapper(client.logEvent.bind(client));
192
+
193
+ /**
194
+ * Sends an identify event containing user property operations
195
+ *
196
+ * ```typescript
197
+ * const id = new Identify();
198
+ * id.set('colors', ['rose', 'gold']);
199
+ * identify(id);
200
+ *
201
+ * // alternatively, this tracking method is awaitable
202
+ * const result = await identify(id).promise;
203
+ * console.log(result.event); // {...}
204
+ * console.log(result.code); // 200
205
+ * console.log(result.message); // "Event tracked successfully"
206
+ * ```
207
+ */
208
+ export const identify = returnWrapper(client.identify.bind(client));
209
+
210
+ /**
211
+ * Sends a group identify event containing group property operations.
212
+ *
213
+ * ```typescript
214
+ * const id = new Identify();
215
+ * id.set('skills', ['js', 'ts']);
216
+ * const groupType = 'org';
217
+ * const groupName = 'engineering';
218
+ * groupIdentify(groupType, groupName, id);
219
+ *
220
+ * // alternatively, this tracking method is awaitable
221
+ * const result = await groupIdentify(groupType, groupName, id).promise;
222
+ * console.log(result.event); // {...}
223
+ * console.log(result.code); // 200
224
+ * console.log(result.message); // "Event tracked successfully"
225
+ * ```
226
+ */
227
+ export const groupIdentify = returnWrapper(client.groupIdentify.bind(client));
228
+ export const setGroup = returnWrapper(client.setGroup.bind(client));
229
+
230
+ /**
231
+ * Sends a revenue event containing revenue property operations.
232
+ *
233
+ * ```typescript
234
+ * const rev = new Revenue();
235
+ * rev.setRevenue(100);
236
+ * revenue(rev);
237
+ *
238
+ * // alternatively, this tracking method is awaitable
239
+ * const result = await revenue(rev).promise;
240
+ * console.log(result.event); // {...}
241
+ * console.log(result.code); // 200
242
+ * console.log(result.message); // "Event tracked successfully"
243
+ * ```
244
+ */
245
+ export const revenue = returnWrapper(client.revenue.bind(client));
246
+
247
+ /**
248
+ * Returns current user ID.
249
+ *
250
+ * ```typescript
251
+ * const userId = getUserId();
252
+ * ```
253
+ */
254
+ export const getUserId = client.getUserId.bind(client);
255
+
256
+ /**
257
+ * Sets a new user ID.
258
+ *
259
+ * ```typescript
260
+ * setUserId('userId');
261
+ * ```
262
+ */
263
+ export const setUserId = client.setUserId.bind(client);
264
+
265
+ /**
266
+ * Returns current device ID.
267
+ *
268
+ * ```typescript
269
+ * const deviceId = getDeviceId();
270
+ * ```
271
+ */
272
+ export const getDeviceId = client.getDeviceId.bind(client);
273
+
274
+ /**
275
+ * Sets a new device ID.
276
+ * When setting a custom device ID, make sure the value is sufficiently unique.
277
+ * A uuid is recommended.
278
+ *
279
+ * ```typescript
280
+ * setDeviceId('deviceId');
281
+ * ```
282
+ */
283
+ export const setDeviceId = client.setDeviceId.bind(client);
284
+
285
+ /**
286
+ * Regenerates a new random deviceId for current user. Note: this is not recommended unless you know what you
287
+ * are doing. This can be used in conjunction with `setUserId(undefined)` to anonymize users after they log out.
288
+ * With an `unefined` userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.
289
+ *
290
+ * ```typescript
291
+ * regenerateDeviceId();
292
+ * ```
293
+ */
294
+ export const regenerateDeviceId = client.regenerateDeviceId.bind(client);
295
+
296
+ /**
297
+ * Returns current session ID.
298
+ *
299
+ * ```typescript
300
+ * const sessionId = getSessionId();
301
+ * ```
302
+ */
303
+ export const getSessionId = client.getSessionId.bind(client);
304
+
305
+ /**
306
+ * Sets a new session ID.
307
+ * When settign a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp).
308
+ *
309
+ * ```typescript
310
+ * setSessionId(Date.now());
311
+ * ```
312
+ */
313
+ export const setSessionId = client.setSessionId.bind(client);
314
+
315
+ /**
316
+ * Sets a new optOut config value. This toggles event tracking on/off.
317
+ *
318
+ *```typescript
319
+ * // Stops tracking
320
+ * setOptOut(true);
321
+ *
322
+ * // Starts/resumes tracking
323
+ * setOptOut(false);
324
+ * ```
325
+ */
326
+ export const setOptOut = client.setOptOut.bind(client);
327
+
328
+ /**
329
+ * Flush and send all the events which haven't been sent.
330
+ *
331
+ *```typescript
332
+ * // Send all the unsent events
333
+ * flush();
334
+ *
335
+ * // alternatively, this tracking method is awaitable
336
+ * await flush().promise;
337
+ * ```
338
+ */
339
+ 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
+ };