insert-affiliate-react-native-sdk 1.6.3 → 1.6.5

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.
@@ -1,13 +1,19 @@
1
- import React, { createContext, useEffect, useState } from 'react';
2
- import { Platform, Linking } from 'react-native';
1
+ import React, { createContext, useEffect, useState, useRef } from 'react';
2
+ import { Platform, Linking, Dimensions, PixelRatio } from 'react-native';
3
3
  import axios from 'axios';
4
4
  import AsyncStorage from '@react-native-async-storage/async-storage';
5
+ import Clipboard from '@react-native-clipboard/clipboard';
6
+ import NetInfo from '@react-native-community/netinfo';
7
+ import DeviceInfo from 'react-native-device-info';
8
+ import { PlayInstallReferrer, PlayInstallReferrerInfo } from 'react-native-play-install-referrer';
5
9
 
6
10
  // TYPES USED IN THIS PROVIDER
7
11
  type T_DEEPLINK_IAP_PROVIDER = {
8
12
  children: React.ReactNode;
9
13
  };
10
14
 
15
+ export type InsertAffiliateIdentifierChangeCallback = (identifier: string | null) => void;
16
+
11
17
  type CustomPurchase = {
12
18
  [key: string]: any; // Accept any fields to allow it to work wtih multiple IAP libraries
13
19
  };
@@ -32,7 +38,9 @@ type T_DEEPLINK_IAP_CONTEXT = {
32
38
  setInsertAffiliateIdentifier: (
33
39
  referringLink: string
34
40
  ) => Promise<void | string>;
35
- initialize: (code: string | null, verboseLogging?: boolean) => Promise<void>;
41
+ setInsertAffiliateIdentifierChangeCallback: (callback: InsertAffiliateIdentifierChangeCallback | null) => void;
42
+ handleInsertLinks: (url: string) => Promise<boolean>;
43
+ initialize: (code: string | null, verboseLogging?: boolean, insertLinksEnabled?: boolean, insertLinksClipboardEnabled?: boolean) => Promise<void>;
36
44
  isInitialized: boolean;
37
45
  };
38
46
 
@@ -78,23 +86,30 @@ export const DeepLinkIapContext = createContext<T_DEEPLINK_IAP_CONTEXT>({
78
86
  trackEvent: async (eventName: string) => {},
79
87
  setShortCode: async (shortCode: string) => {},
80
88
  setInsertAffiliateIdentifier: async (referringLink: string) => {},
81
- initialize: async (code: string | null, verboseLogging?: boolean) => {},
89
+ setInsertAffiliateIdentifierChangeCallback: (callback: InsertAffiliateIdentifierChangeCallback | null) => {},
90
+ handleInsertLinks: async (url: string) => false,
91
+ initialize: async (code: string | null, verboseLogging?: boolean, insertLinksEnabled?: boolean, insertLinksClipboardEnabled?: boolean) => {},
82
92
  isInitialized: false,
83
93
  });
84
94
 
85
95
  const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
86
96
  children,
87
- }) => {
97
+ }) => {
88
98
  const [referrerLink, setReferrerLink] = useState<string>('');
89
99
  const [userId, setUserId] = useState<string>('');
90
100
  const [companyCode, setCompanyCode] = useState<string | null>(null);
91
101
  const [isInitialized, setIsInitialized] = useState<boolean>(false);
92
102
  const [verboseLogging, setVerboseLogging] = useState<boolean>(false);
103
+ const [insertLinksEnabled, setInsertLinksEnabled] = useState<boolean>(false);
104
+ const [insertLinksClipboardEnabled, setInsertLinksClipboardEnabled] = useState<boolean>(false);
93
105
  const [OfferCode, setOfferCode] = useState<string | null>(null);
106
+ const insertAffiliateIdentifierChangeCallbackRef = useRef<InsertAffiliateIdentifierChangeCallback | null>(null);
94
107
 
95
108
  // MARK: Initialize the SDK
96
- const initialize = async (companyCode: string | null, verboseLogging: boolean = false): Promise<void> => {
109
+ const initialize = async (companyCode: string | null, verboseLogging: boolean = false, insertLinksEnabled: boolean = false, insertLinksClipboardEnabled: boolean = false): Promise<void> => {
97
110
  setVerboseLogging(verboseLogging);
111
+ setInsertLinksEnabled(insertLinksEnabled);
112
+ setInsertLinksClipboardEnabled(insertLinksClipboardEnabled);
98
113
 
99
114
  if (verboseLogging) {
100
115
  console.log('[Insert Affiliate] [VERBOSE] Starting SDK initialization...');
@@ -127,6 +142,15 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
127
142
  console.log('[Insert Affiliate] [VERBOSE] No company code provided, SDK initialized in limited mode');
128
143
  }
129
144
  }
145
+
146
+ if (insertLinksEnabled && Platform.OS === 'ios') {
147
+ try {
148
+ const enhancedSystemInfo = await getEnhancedSystemInfo();
149
+ await sendSystemInfoToBackend(enhancedSystemInfo);
150
+ } catch (error) {
151
+ verboseLog(`Error sending system info for clipboard check: ${error}`);
152
+ }
153
+ }
130
154
  };
131
155
 
132
156
  // EFFECT TO FETCH USER ID AND REF LINK
@@ -169,6 +193,95 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
169
193
  fetchAsyncEssentials();
170
194
  }, []);
171
195
 
196
+ // Cleanup callback on unmount
197
+ useEffect(() => {
198
+ return () => {
199
+ insertAffiliateIdentifierChangeCallbackRef.current = null;
200
+ };
201
+ }, []);
202
+
203
+ // Deep link event listeners - equivalent to iOS AppDelegate methods
204
+ useEffect(() => {
205
+ if (!isInitialized) return;
206
+
207
+ // Handle app launch with URL (equivalent to didFinishLaunchingWithOptions)
208
+ const handleInitialURL = async () => {
209
+ try {
210
+ const initialUrl = await Linking.getInitialURL();
211
+ if (initialUrl) {
212
+ verboseLog(`App launched with URL: ${initialUrl}`);
213
+ const handled = await handleDeepLink(initialUrl);
214
+ if (handled) {
215
+ verboseLog('URL was handled by Insert Affiliate SDK');
216
+ } else {
217
+ verboseLog('URL was not handled by Insert Affiliate SDK');
218
+ }
219
+ }
220
+ } catch (error) {
221
+ console.error('[Insert Affiliate] Error getting initial URL:', error);
222
+ }
223
+ };
224
+
225
+ // Handle URL opening while app is running (equivalent to open url)
226
+ const handleUrlChange = async (event: { url: string }) => {
227
+ try {
228
+ verboseLog(`URL opened while app running: ${event.url}`);
229
+ const handled = await handleDeepLink(event.url);
230
+ if (handled) {
231
+ verboseLog('URL was handled by Insert Affiliate SDK');
232
+ } else {
233
+ verboseLog('URL was not handled by Insert Affiliate SDK');
234
+ }
235
+ } catch (error) {
236
+ console.error('[Insert Affiliate] Error handling URL change:', error);
237
+ }
238
+ };
239
+
240
+ // Platform-specific deep link handler
241
+ const handleDeepLink = async (url: string): Promise<boolean> => {
242
+ try {
243
+ verboseLog(`Platform detection: Platform.OS = ${Platform.OS}`);
244
+ if (Platform.OS === 'ios') {
245
+ verboseLog('Routing to iOS handler (handleInsertLinks)');
246
+ return await handleInsertLinks(url);
247
+ } else if (Platform.OS === 'android') {
248
+ verboseLog('Routing to Android handler (handleInsertLinkAndroid)');
249
+ return await handleInsertLinkAndroid(url);
250
+ }
251
+ verboseLog(`Unrecognized platform: ${Platform.OS}`);
252
+ return false;
253
+ } catch (error) {
254
+ verboseLog(`Error handling deep link: ${error}`);
255
+ return false;
256
+ }
257
+ };
258
+
259
+ // Set up listeners
260
+ const urlListener = Linking.addEventListener('url', handleUrlChange);
261
+
262
+ // Handle initial URL
263
+ handleInitialURL();
264
+
265
+ // Cleanup
266
+ return () => {
267
+ urlListener?.remove();
268
+ };
269
+ }, [isInitialized]);
270
+
271
+ // EFFECT TO HANDLE INSTALL REFERRER ON ANDROID
272
+ useEffect(() => {
273
+
274
+ if (Platform.OS === 'android' && isInitialized && insertLinksEnabled) { verboseLog('Install referrer effect - Platform.OS is android, isInitialized is true, and insertLinksEnabled is true');
275
+ // Ensure user ID is generated before processing install referrer
276
+ const initializeAndCapture = async () => {
277
+ await generateThenSetUserID();
278
+ verboseLog('Install referrer effect - Generating user ID and capturing install referrer');
279
+ captureInstallReferrer();
280
+ };
281
+ initializeAndCapture();
282
+ }
283
+ }, [isInitialized, insertLinksEnabled]);
284
+
172
285
  async function generateThenSetUserID() {
173
286
  verboseLog('Getting or generating user ID...');
174
287
  let userId = await getValueFromAsync(ASYNC_KEYS.USER_ID);
@@ -204,6 +317,349 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
204
317
  console.log('[Insert Affiliate] SDK has been reset.');
205
318
  };
206
319
 
320
+ // MARK: Callback Management
321
+ // Sets a callback that will be triggered whenever storeInsertAffiliateIdentifier is called
322
+ // The callback receives the current affiliate identifier (returnInsertAffiliateIdentifier result)
323
+ const setInsertAffiliateIdentifierChangeCallbackHandler = (callback: InsertAffiliateIdentifierChangeCallback | null): void => {
324
+ insertAffiliateIdentifierChangeCallbackRef.current = callback;
325
+ };
326
+
327
+ // MARK: Deep Link Handling
328
+ // Helper function to parse URLs in React Native compatible way
329
+ const parseURL = (url: string) => {
330
+ try {
331
+ // Extract protocol
332
+ const protocolMatch = url.match(/^([^:]+):/);
333
+ const protocol = protocolMatch ? protocolMatch[1] + ':' : '';
334
+
335
+ // Extract hostname for https URLs
336
+ let hostname = '';
337
+ if (protocol === 'https:' || protocol === 'http:') {
338
+ const hostnameMatch = url.match(/^https?:\/\/([^\/]+)/);
339
+ hostname = hostnameMatch ? hostnameMatch[1] : '';
340
+ }
341
+
342
+ return {
343
+ protocol,
344
+ hostname,
345
+ href: url
346
+ };
347
+ } catch (error) {
348
+ return {
349
+ protocol: '',
350
+ hostname: '',
351
+ href: url
352
+ };
353
+ }
354
+ };
355
+
356
+ // Handles Android deep links with insertAffiliate parameter
357
+ const handleInsertLinkAndroid = async (url: string): Promise<boolean> => {
358
+ try {
359
+ // Check if deep links are enabled
360
+ if (!insertLinksEnabled) {
361
+ verboseLog('Deep links are disabled, not handling Android URL');
362
+ return false;
363
+ }
364
+
365
+ verboseLog(`Processing Android deep link: ${url}`);
366
+
367
+ if (!url || typeof url !== 'string') {
368
+ verboseLog('Invalid URL provided to handleInsertLinkAndroid');
369
+ return false;
370
+ }
371
+
372
+ // Parse the URL to extract query parameters
373
+ const urlObj = new URL(url);
374
+ const insertAffiliate = urlObj.searchParams.get('insertAffiliate');
375
+
376
+ if (insertAffiliate && insertAffiliate.length > 0) {
377
+ verboseLog(`Found insertAffiliate parameter: ${insertAffiliate}`);
378
+
379
+ await storeInsertAffiliateIdentifier({ link: insertAffiliate });
380
+
381
+ return true;
382
+ } else {
383
+ verboseLog('No insertAffiliate parameter found in Android deep link');
384
+ return false;
385
+ }
386
+ } catch (error) {
387
+ verboseLog(`Error handling Android deep link: ${error}`);
388
+ return false;
389
+ }
390
+ };
391
+
392
+ // MARK: Play Install Referrer
393
+ /**
394
+ * Captures install referrer data from Google Play Store
395
+ * This method automatically extracts referral parameters and processes them
396
+ */
397
+ const captureInstallReferrer = async (retryCount: number = 0): Promise<boolean> => {
398
+ try {
399
+ // Check if deep links are enabled
400
+ if (!insertLinksEnabled) {
401
+ verboseLog('Deep links are disabled, not processing install referrer');
402
+ return false;
403
+ }
404
+
405
+ // Check if we're on Android
406
+ if (Platform.OS !== 'android') {
407
+ verboseLog('Install referrer is only available on Android');
408
+ return false;
409
+ }
410
+
411
+ verboseLog(`Starting install referrer capture... (attempt ${retryCount + 1})`);
412
+
413
+ // Convert callback-based API to Promise with timeout
414
+ const referrerData = await new Promise<PlayInstallReferrerInfo | null>((resolve, reject) => {
415
+ const timeout = setTimeout(() => {
416
+ reject(new Error('Install referrer request timed out'));
417
+ }, 10000); // 10 second timeout
418
+
419
+ PlayInstallReferrer.getInstallReferrerInfo((info, error) => {
420
+ clearTimeout(timeout);
421
+ if (error) {
422
+ reject(error);
423
+ } else {
424
+ resolve(info);
425
+ }
426
+ });
427
+ });
428
+
429
+ if (referrerData && referrerData.installReferrer) {
430
+ verboseLog(`Raw install referrer data: ${referrerData.installReferrer}`);
431
+
432
+ const success = await processInstallReferrerData(referrerData.installReferrer);
433
+
434
+ if (success) {
435
+ verboseLog('Install referrer processed successfully');
436
+ return true;
437
+ } else {
438
+ verboseLog('No insertAffiliate parameter found in install referrer');
439
+ return false;
440
+ }
441
+ } else {
442
+ verboseLog('No install referrer data found');
443
+ return false;
444
+ }
445
+
446
+ } catch (error) {
447
+ const errorMessage = error instanceof Error ? error.message : String(error);
448
+ verboseLog(`Error capturing install referrer (attempt ${retryCount + 1}): ${errorMessage}`);
449
+
450
+ // Check if this is a retryable error and we haven't exceeded max retries
451
+ const isRetryableError = errorMessage.includes('SERVICE_UNAVAILABLE') ||
452
+ errorMessage.includes('DEVELOPER_ERROR') ||
453
+ errorMessage.includes('timed out') ||
454
+ errorMessage.includes('SERVICE_DISCONNECTED');
455
+
456
+ const maxRetries = 3;
457
+ const retryDelay = Math.min(1000 * Math.pow(2, retryCount), 10000); // Exponential backoff, max 10s
458
+
459
+ if (isRetryableError && retryCount < maxRetries) {
460
+ verboseLog(`Retrying install referrer capture in ${retryDelay}ms...`);
461
+
462
+ // Schedule retry
463
+ setTimeout(() => {
464
+ captureInstallReferrer(retryCount + 1);
465
+ }, retryDelay);
466
+
467
+ return false;
468
+ } else {
469
+ verboseLog(`Install referrer capture failed after ${retryCount + 1} attempts`);
470
+ return false;
471
+ }
472
+ }
473
+ };
474
+
475
+ /**
476
+ * Processes the raw install referrer data and extracts insertAffiliate parameter
477
+ * @param rawReferrer The raw referrer string from Play Store
478
+ */
479
+ const processInstallReferrerData = async (rawReferrer: string): Promise<boolean> => {
480
+ try {
481
+ verboseLog('Processing install referrer data...');
482
+
483
+ if (!rawReferrer || rawReferrer.length === 0) {
484
+ verboseLog('No referrer data provided');
485
+ return false;
486
+ }
487
+
488
+ verboseLog(`Raw referrer data: ${rawReferrer}`);
489
+
490
+ // Parse the referrer string directly for insertAffiliate parameter
491
+ let insertAffiliate: string | null = null;
492
+
493
+ if (rawReferrer.includes('insertAffiliate=')) {
494
+ const params = rawReferrer.split('&');
495
+ for (const param of params) {
496
+ if (param.startsWith('insertAffiliate=')) {
497
+ insertAffiliate = param.substring('insertAffiliate='.length);
498
+ break;
499
+ }
500
+ }
501
+ }
502
+
503
+ verboseLog(`Extracted insertAffiliate parameter: ${insertAffiliate}`);
504
+
505
+ // If we have insertAffiliate parameter, use it as the affiliate identifier
506
+ if (insertAffiliate && insertAffiliate.length > 0) {
507
+ verboseLog(`Found insertAffiliate parameter, setting as affiliate identifier: ${insertAffiliate}`);
508
+ await storeInsertAffiliateIdentifier({ link: insertAffiliate });
509
+
510
+ return true;
511
+ } else {
512
+ verboseLog('No insertAffiliate parameter found in referrer data');
513
+ return false;
514
+ }
515
+
516
+ } catch (error) {
517
+ verboseLog(`Error processing install referrer data: ${error}`);
518
+ return false;
519
+ }
520
+ };
521
+
522
+ // Handles Insert Links deep linking - equivalent to iOS handleInsertLinks
523
+ const handleInsertLinks = async (url: string): Promise<boolean> => {
524
+ try {
525
+ console.log(`[Insert Affiliate] Attempting to handle URL: ${url}`);
526
+
527
+ if (!url || typeof url !== 'string') {
528
+ console.log('[Insert Affiliate] Invalid URL provided to handleInsertLinks');
529
+ return false;
530
+ }
531
+
532
+ // Check if deep links are enabled synchronously
533
+ if (!insertLinksEnabled) {
534
+ console.log('[Insert Affiliate] Deep links are disabled, not handling URL');
535
+ return false;
536
+ }
537
+
538
+ const urlObj = parseURL(url);
539
+
540
+ // Handle custom URL schemes (ia-companycode://shortcode)
541
+ if (urlObj.protocol && urlObj.protocol.startsWith('ia-')) {
542
+ return await handleCustomURLScheme(url, urlObj.protocol);
543
+ }
544
+
545
+ // Handle universal links (https://insertaffiliate.link/V1/companycode/shortcode)
546
+ // if (urlObj.protocol === 'https:' && urlObj.hostname?.includes('insertaffiliate.link')) {
547
+ // return await handleUniversalLink(urlObj);
548
+ // }
549
+
550
+ return false;
551
+ } catch (error) {
552
+ console.error('[Insert Affiliate] Error handling Insert Link:', error);
553
+ verboseLog(`Error in handleInsertLinks: ${error}`);
554
+ return false;
555
+ }
556
+ };
557
+
558
+ // Handle custom URL schemes like ia-companycode://shortcode
559
+ const handleCustomURLScheme = async (url: string, protocol: string): Promise<boolean> => {
560
+ try {
561
+ const scheme = protocol.replace(':', '');
562
+
563
+ if (!scheme.startsWith('ia-')) {
564
+ return false;
565
+ }
566
+
567
+ // Extract company code from scheme (remove "ia-" prefix)
568
+ const companyCode = scheme.substring(3);
569
+
570
+ const shortCode = parseShortCodeFromURLString(url);
571
+ if (!shortCode) {
572
+ console.log(`[Insert Affiliate] Failed to parse short code from deep link: ${url}`);
573
+ return false;
574
+ }
575
+
576
+ console.log(`[Insert Affiliate] Custom URL scheme detected - Company: ${companyCode}, Short code: ${shortCode}`);
577
+
578
+ // Validate company code matches initialized one
579
+ const activeCompanyCode = await getActiveCompanyCode();
580
+ if (activeCompanyCode && companyCode.toLowerCase() !== activeCompanyCode.toLowerCase()) {
581
+ console.log(`[Insert Affiliate] Warning: URL company code (${companyCode}) doesn't match initialized company code (${activeCompanyCode})`);
582
+ }
583
+
584
+ // If URL scheme is used, we can straight away store the short code as the referring link
585
+ await storeInsertAffiliateIdentifier({ link: shortCode });
586
+
587
+ // Collect and send enhanced system info to backend
588
+ try {
589
+ const enhancedSystemInfo = await getEnhancedSystemInfo();
590
+ await sendSystemInfoToBackend(enhancedSystemInfo);
591
+ } catch (error) {
592
+ verboseLog(`Error sending system info for deep link: ${error}`);
593
+ }
594
+
595
+ return true;
596
+ } catch (error) {
597
+ console.error('[Insert Affiliate] Error handling custom URL scheme:', error);
598
+ return false;
599
+ }
600
+ };
601
+
602
+ // Handle universal links like https://insertaffiliate.link/V1/companycode/shortcode
603
+ // const handleUniversalLink = async (url: URL): Promise<boolean> => {
604
+ // try {
605
+ // const pathComponents = url.pathname.split('/').filter(segment => segment.length > 0);
606
+
607
+ // // Expected format: /V1/companycode/shortcode
608
+ // if (pathComponents.length < 3 || pathComponents[0] !== 'V1') {
609
+ // console.log(`[Insert Affiliate] Invalid universal link format: ${url.href}`);
610
+ // return false;
611
+ // }
612
+
613
+ // const companyCode = pathComponents[1];
614
+ // const shortCode = pathComponents[2];
615
+
616
+ // console.log(`[Insert Affiliate] Universal link detected - Company: ${companyCode}, Short code: ${shortCode}`);
617
+
618
+ // // Validate company code matches initialized one
619
+ // const activeCompanyCode = await getActiveCompanyCode();
620
+ // if (activeCompanyCode && companyCode.toLowerCase() !== activeCompanyCode.toLowerCase()) {
621
+ // console.log(`[Insert Affiliate] Warning: URL company code (${companyCode}) doesn't match initialized company code (${activeCompanyCode})`);
622
+ // }
623
+
624
+ // // Process the affiliate attribution
625
+ // await storeInsertAffiliateIdentifier({ link: shortCode });
626
+
627
+
628
+ // return true;
629
+ // } catch (error) {
630
+ // console.error('[Insert Affiliate] Error handling universal link:', error);
631
+ // return false;
632
+ // }
633
+ // };
634
+
635
+ // Parse short code from URL
636
+ const parseShortCodeFromURL = (url: URL): string | null => {
637
+ try {
638
+ // For custom schemes like ia-companycode://shortcode, everything after :// is the short code
639
+ // Remove leading slash from pathname
640
+ return url.pathname.startsWith('/') ? url.pathname.substring(1) : url.pathname;
641
+ } catch (error) {
642
+ verboseLog(`Error parsing short code from URL: ${error}`);
643
+ return null;
644
+ }
645
+ };
646
+
647
+ const parseShortCodeFromURLString = (url: string): string | null => {
648
+ try {
649
+ // For custom schemes like ia-companycode://shortcode, everything after :// is the short code
650
+ const match = url.match(/^[^:]+:\/\/(.+)$/);
651
+ if (match) {
652
+ const shortCode = match[1];
653
+ // Remove leading slash if present
654
+ return shortCode.startsWith('/') ? shortCode.substring(1) : shortCode;
655
+ }
656
+ return null;
657
+ } catch (error) {
658
+ verboseLog(`Error parsing short code from URL string: ${error}`);
659
+ return null;
660
+ }
661
+ };
662
+
207
663
  // Helper funciton Storage / Retrieval
208
664
  const saveValueInAsync = async (key: string, value: string) => {
209
665
  await AsyncStorage.setItem(key, value);
@@ -260,6 +716,445 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
260
716
  }
261
717
  };
262
718
 
719
+ // MARK: - Deep Linking Utilities
720
+
721
+ // Retrieves and validates clipboard content for UUID format
722
+ const getClipboardUUID = async (): Promise<string | null> => {
723
+ // Check if clipboard access is enabled
724
+ if (!insertLinksClipboardEnabled) {
725
+ return null;
726
+ }
727
+
728
+ verboseLog('Getting clipboard UUID');
729
+
730
+ try {
731
+ const clipboardString = await Clipboard.getString();
732
+
733
+ if (!clipboardString) {
734
+ verboseLog('No clipboard string found or access denied');
735
+ return null;
736
+ }
737
+
738
+ const trimmedString = clipboardString.trim();
739
+
740
+ if (isValidUUID(trimmedString)) {
741
+ verboseLog(`Valid clipboard UUID found: ${trimmedString}`);
742
+ return trimmedString;
743
+ }
744
+
745
+ verboseLog(`Invalid clipboard UUID found: ${trimmedString}`);
746
+ return null;
747
+ } catch (error) {
748
+ verboseLog(`Clipboard access error: ${error}`);
749
+ return null;
750
+ }
751
+ };
752
+
753
+ // Validates if a string is a properly formatted UUID (36 characters)
754
+ const isValidUUID = (string: string): boolean => {
755
+ if (string.length !== 36) return false;
756
+
757
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
758
+ return uuidRegex.test(string);
759
+ };
760
+
761
+ // MARK: - System Info Collection
762
+
763
+ // Gets network connection type and interface information
764
+ const getNetworkInfo = async (): Promise<{[key: string]: any}> => {
765
+ try {
766
+ const connectionInfo = {
767
+ connectionType: 'unknown',
768
+ interfaceTypes: [] as string[],
769
+ isExpensive: false,
770
+ isConstrained: false,
771
+ status: 'disconnected',
772
+ availableInterfaces: [] as string[]
773
+ };
774
+
775
+ try {
776
+ // Use NetInfo to get accurate network information
777
+ const netInfo = await NetInfo.fetch();
778
+
779
+ connectionInfo.status = netInfo.isConnected ? 'connected' : 'disconnected';
780
+ connectionInfo.connectionType = netInfo.type || 'unknown';
781
+ connectionInfo.isExpensive = netInfo.isInternetReachable === false ? true : false;
782
+ connectionInfo.isConstrained = false; // NetInfo doesn't provide this directly
783
+
784
+ // Map NetInfo types to our interface format
785
+ if (netInfo.type) {
786
+ connectionInfo.interfaceTypes = [netInfo.type];
787
+ connectionInfo.availableInterfaces = [netInfo.type];
788
+ }
789
+
790
+ // Additional details if available
791
+ if (netInfo.details && 'isConnectionExpensive' in netInfo.details) {
792
+ connectionInfo.isExpensive = netInfo.details.isConnectionExpensive || false;
793
+ }
794
+
795
+ } catch (error) {
796
+ verboseLog(`Network info fetch failed: ${error}`);
797
+ // Fallback to basic connectivity test
798
+ try {
799
+ const response = await fetch('https://www.google.com/favicon.ico', {
800
+ method: 'HEAD'
801
+ });
802
+ if (response.ok) {
803
+ connectionInfo.status = 'connected';
804
+ }
805
+ } catch (fetchError) {
806
+ verboseLog(`Fallback connectivity test failed: ${fetchError}`);
807
+ }
808
+ }
809
+
810
+ return connectionInfo;
811
+ } catch (error) {
812
+ verboseLog(`Error getting network info: ${error}`);
813
+ return {
814
+ connectionType: 'unknown',
815
+ interfaceTypes: [],
816
+ isExpensive: false,
817
+ isConstrained: false,
818
+ status: 'disconnected',
819
+ availableInterfaces: []
820
+ };
821
+ }
822
+ };
823
+
824
+
825
+ const getNetworkPathInfo = async (): Promise<{[key: string]: any}> => {
826
+ try {
827
+ const netInfo = await NetInfo.fetch();
828
+
829
+ // Default values - only set to true when proven
830
+ let supportsIPv4 = false;
831
+ let supportsIPv6 = false;
832
+ let supportsDNS = false;
833
+ let hasUnsatisfiedGateway = false;
834
+ let gatewayCount = 0;
835
+ let gateways: string[] = [];
836
+ let interfaceDetails: Array<{[key: string]: any}> = [];
837
+
838
+ if (netInfo.details && netInfo.isConnected) {
839
+ supportsIPv4 = true;
840
+
841
+ // IPv6 support based on interface type (following Swift logic)
842
+ if (netInfo.type === 'wifi' || netInfo.type === 'cellular' || netInfo.type === 'ethernet') {
843
+ supportsIPv6 = true;
844
+ } else {
845
+ supportsIPv6 = false;
846
+ }
847
+
848
+ supportsDNS = netInfo.isInternetReachable === true;
849
+
850
+ // Get interface details from NetInfo
851
+ if (netInfo.details && 'isConnectionExpensive' in netInfo.details) {
852
+ // This is a cellular connection
853
+ interfaceDetails.push({
854
+ name: 'cellular',
855
+ index: 0,
856
+ type: 'cellular'
857
+ });
858
+ } else if (netInfo.type === 'wifi') {
859
+ interfaceDetails.push({
860
+ name: 'en0',
861
+ index: 0,
862
+ type: 'wifi'
863
+ });
864
+ } else if (netInfo.type === 'ethernet') {
865
+ interfaceDetails.push({
866
+ name: 'en0',
867
+ index: 0,
868
+ type: 'wiredEthernet'
869
+ });
870
+ }
871
+
872
+ gatewayCount = interfaceDetails.length;
873
+ hasUnsatisfiedGateway = gatewayCount === 0;
874
+
875
+ // For React Native, we can't easily get actual gateway IPs
876
+ // but we can indicate if we have network connectivity
877
+ if (netInfo.isConnected) {
878
+ gateways = ['default']; // Placeholder since we can't get actual gateway IPs
879
+ }
880
+ }
881
+
882
+ // Fallback if NetInfo doesn't provide enough details
883
+ if (interfaceDetails.length === 0) {
884
+ interfaceDetails = [{
885
+ name: 'en0',
886
+ index: 0,
887
+ type: netInfo.type || 'unknown'
888
+ }];
889
+ gatewayCount = 1;
890
+ hasUnsatisfiedGateway = false;
891
+ gateways = ['default'];
892
+ }
893
+
894
+ return {
895
+ supportsIPv4,
896
+ supportsIPv6,
897
+ supportsDNS,
898
+ hasUnsatisfiedGateway,
899
+ gatewayCount,
900
+ gateways,
901
+ interfaceDetails
902
+ };
903
+
904
+ } catch (error) {
905
+ verboseLog(`Error getting network path info: ${error}`);
906
+
907
+ // Fallback to basic defaults if NetInfo fails
908
+ return {
909
+ supportsIPv4: true,
910
+ supportsIPv6: false,
911
+ supportsDNS: true,
912
+ hasUnsatisfiedGateway: false,
913
+ gatewayCount: 1,
914
+ gateways: ['default'],
915
+ interfaceDetails: [{
916
+ name: 'en0',
917
+ index: 0,
918
+ type: 'unknown'
919
+ }]
920
+ };
921
+ }
922
+ };
923
+
924
+ // Collects basic system information for deep linking (non-identifying data only)
925
+ const getSystemInfo = async (): Promise<{[key: string]: any}> => {
926
+ const systemInfo: {[key: string]: any} = {};
927
+
928
+ try {
929
+ systemInfo.systemName = await DeviceInfo.getSystemName();
930
+ systemInfo.systemVersion = await DeviceInfo.getSystemVersion();
931
+ systemInfo.model = await DeviceInfo.getModel();
932
+ systemInfo.localizedModel = await DeviceInfo.getModel();
933
+ systemInfo.isPhysicalDevice = !(await DeviceInfo.isEmulator());
934
+ systemInfo.bundleId = await DeviceInfo.getBundleId();
935
+
936
+ // Map device type to more readable format
937
+ const deviceType = await DeviceInfo.getDeviceType();
938
+ systemInfo.deviceType = deviceType === 'Handset' ? 'mobile' : deviceType;
939
+ } catch (error) {
940
+ verboseLog(`Error getting device info: ${error}`);
941
+ // Fallback to basic platform detection
942
+ systemInfo.systemName = 'iOS';
943
+ systemInfo.systemVersion = Platform.Version.toString();
944
+ systemInfo.model = 'iPhone';
945
+ systemInfo.localizedModel = systemInfo.model;
946
+ systemInfo.isPhysicalDevice = true; // Assume physical device if we can't detect
947
+ systemInfo.bundleId = 'null'; // Fallback if we can't get bundle ID
948
+ systemInfo.deviceType = 'unknown';
949
+ }
950
+
951
+ if (verboseLogging) {
952
+ console.log('[Insert Affiliate] system info:', systemInfo);
953
+ }
954
+
955
+ return systemInfo;
956
+ };
957
+
958
+ const getEnhancedSystemInfo = async (): Promise<{[key: string]: any}> => {
959
+ verboseLog('Collecting enhanced system information...');
960
+
961
+ let systemInfo = await getSystemInfo();
962
+
963
+ verboseLog(`System info: ${JSON.stringify(systemInfo)}`);
964
+
965
+ try {
966
+ // Add timestamp
967
+ const now = new Date();
968
+ systemInfo.requestTime = now.toISOString();
969
+ systemInfo.requestTimestamp = Math.floor(now.getTime());
970
+
971
+ // Add user agent style information
972
+ const systemName = systemInfo.systemName;
973
+ const systemVersion = systemInfo.systemVersion;
974
+ const model = systemInfo.model;
975
+
976
+ systemInfo.userAgent = `${model}; ${systemName} ${systemVersion}`;
977
+
978
+ // Add screen dimensions and device pixel ratio (matching exact field names)
979
+ const { width, height } = Dimensions.get('window');
980
+ const pixelRatio = PixelRatio.get();
981
+
982
+ systemInfo.screenWidth = Math.floor(width);
983
+ systemInfo.screenHeight = Math.floor(height);
984
+ systemInfo.screenAvailWidth = Math.floor(width);
985
+ systemInfo.screenAvailHeight = Math.floor(height);
986
+ systemInfo.devicePixelRatio = pixelRatio;
987
+ systemInfo.screenColorDepth = 24;
988
+ systemInfo.screenPixelDepth = 24;
989
+
990
+
991
+ try {
992
+ systemInfo.hardwareConcurrency = await DeviceInfo.getTotalMemory() / (1024 * 1024 * 1024); // Convert to GB
993
+ } catch (error) {
994
+ systemInfo.hardwareConcurrency = 4; // Fallback assumption
995
+ }
996
+ systemInfo.maxTouchPoints = 5; // Default for mobile devices
997
+
998
+ // Add screen dimensions (native mobile naming)
999
+ systemInfo.screenInnerWidth = Math.floor(width);
1000
+ systemInfo.screenInnerHeight = Math.floor(height);
1001
+ systemInfo.screenOuterWidth = Math.floor(width);
1002
+ systemInfo.screenOuterHeight = Math.floor(height);
1003
+
1004
+ // Add clipboard UUID if available
1005
+ const clipboardUUID = await getClipboardUUID();
1006
+ if (clipboardUUID) {
1007
+ systemInfo.clipboardID = clipboardUUID;
1008
+ verboseLog(`Found valid clipboard UUID: ${clipboardUUID}`);
1009
+ } else {
1010
+ if (insertLinksClipboardEnabled) {
1011
+ verboseLog('Clipboard UUID not available - it may require NSPasteboardGeneralUseDescription in Info.plist');
1012
+ } else {
1013
+ verboseLog('Clipboard access is disabled - it may require NSPasteboardGeneralUseDescription in Info.plist');
1014
+ }
1015
+ }
1016
+
1017
+ // Add language information using Intl API
1018
+ try {
1019
+ // Get locale with region information
1020
+ const locale = Intl.DateTimeFormat().resolvedOptions().locale;
1021
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1022
+
1023
+ // Try to get more specific locale information
1024
+ let bestLocale = locale;
1025
+
1026
+ // If the locale doesn't have region info, try to infer from timezone
1027
+ if (!locale.includes('-') && timeZone) {
1028
+ try {
1029
+ // Create a locale-specific date formatter to get region
1030
+ const regionLocale = new Intl.DateTimeFormat(undefined, {
1031
+ timeZone: timeZone
1032
+ }).resolvedOptions().locale;
1033
+
1034
+ if (regionLocale && regionLocale.includes('-')) {
1035
+ bestLocale = regionLocale;
1036
+ }
1037
+ } catch (e) {
1038
+ // Fallback to original locale
1039
+ }
1040
+ }
1041
+
1042
+ // Try navigator.language as fallback for better region detection
1043
+ if (!bestLocale.includes('-') && typeof navigator !== 'undefined' && navigator.language) {
1044
+ bestLocale = navigator.language;
1045
+ }
1046
+
1047
+ const parts = bestLocale.split('-');
1048
+ systemInfo.language = parts[0] || 'en';
1049
+ systemInfo.country = parts[1] || null; // Set to null instead of defaulting to 'US'
1050
+ systemInfo.languages = [bestLocale, parts[0] || 'en'];
1051
+ } catch (error) {
1052
+ verboseLog(`Error getting device locale: ${error}`);
1053
+ // Fallback to defaults
1054
+ systemInfo.language = 'en';
1055
+ systemInfo.country = null; // Set to null instead of defaulting to 'US'
1056
+ systemInfo.languages = ['en'];
1057
+ }
1058
+
1059
+ // Add timezone info (matching exact field names)
1060
+ const timezoneOffset = new Date().getTimezoneOffset();
1061
+ systemInfo.timezoneOffset = -timezoneOffset;
1062
+ systemInfo.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1063
+
1064
+ // Add browser and platform info (matching exact field names)
1065
+ systemInfo.browserVersion = systemInfo.systemVersion;
1066
+ systemInfo.platform = systemInfo.systemName;
1067
+ systemInfo.os = systemInfo.systemName;
1068
+ systemInfo.osVersion = systemInfo.systemVersion;
1069
+
1070
+ // Add network connection info
1071
+ verboseLog('Getting network info');
1072
+
1073
+ const networkInfo = await getNetworkInfo();
1074
+ const pathInfo = await getNetworkPathInfo();
1075
+
1076
+ verboseLog(`Network info: ${JSON.stringify(networkInfo)}`);
1077
+ verboseLog(`Network path info: ${JSON.stringify(pathInfo)}`);
1078
+
1079
+ systemInfo.networkInfo = networkInfo;
1080
+ systemInfo.networkPath = pathInfo;
1081
+
1082
+ // Update connection info with real data
1083
+ const connection: {[key: string]: any} = {};
1084
+ connection.type = networkInfo.connectionType || 'unknown';
1085
+ connection.isExpensive = networkInfo.isExpensive || false;
1086
+ connection.isConstrained = networkInfo.isConstrained || false;
1087
+ connection.status = networkInfo.status || 'unknown';
1088
+ connection.interfaces = networkInfo.availableInterfaces || [];
1089
+ connection.supportsIPv4 = pathInfo.supportsIPv4 || true;
1090
+ connection.supportsIPv6 = pathInfo.supportsIPv6 || false;
1091
+ connection.supportsDNS = pathInfo.supportsDNS || true;
1092
+
1093
+ // Keep legacy fields for compatibility
1094
+ connection.downlink = networkInfo.connectionType === 'wifi' ? 100 : 10;
1095
+ connection.effectiveType = networkInfo.connectionType === 'wifi' ? '4g' : '3g';
1096
+ connection.rtt = networkInfo.connectionType === 'wifi' ? 20 : 100;
1097
+ connection.saveData = networkInfo.isConstrained || false;
1098
+
1099
+ systemInfo.connection = connection;
1100
+
1101
+ verboseLog(`Enhanced system info collected: ${JSON.stringify(systemInfo)}`);
1102
+
1103
+ return systemInfo;
1104
+ } catch (error) {
1105
+ verboseLog(`Error collecting enhanced system info: ${error}`);
1106
+ return systemInfo;
1107
+ }
1108
+ };
1109
+
1110
+ // Sends enhanced system info to the backend API for deep link event tracking
1111
+ const sendSystemInfoToBackend = async (systemInfo: {[key: string]: any}): Promise<void> => {
1112
+ if (verboseLogging) {
1113
+ console.log('[Insert Affiliate] Sending system info to backend...');
1114
+ }
1115
+
1116
+ try {
1117
+ const apiUrlString = 'https://insertaffiliate.link/V1/appDeepLinkEvents';
1118
+
1119
+ verboseLog(`Sending request to: ${apiUrlString}`);
1120
+
1121
+ const response = await axios.post(apiUrlString, systemInfo, {
1122
+ headers: {
1123
+ 'Content-Type': 'application/json',
1124
+ },
1125
+ });
1126
+
1127
+ verboseLog(`System info response status: ${response.status}`);
1128
+ if (response.data) {
1129
+ verboseLog(`System info response: ${JSON.stringify(response.data)}`);
1130
+ }
1131
+
1132
+ // Try to parse backend response and persist matched short code if present
1133
+ if (response.data && typeof response.data === 'object') {
1134
+ const matchFound = response.data.matchFound || false;
1135
+ if (matchFound && response.data.matched_affiliate_shortCode && response.data.matched_affiliate_shortCode.length > 0) {
1136
+ const matchedShortCode = response.data.matched_affiliate_shortCode;
1137
+ verboseLog(`Storing Matched short code from backend: ${matchedShortCode}`);
1138
+
1139
+ await storeInsertAffiliateIdentifier({ link: matchedShortCode });
1140
+ }
1141
+ }
1142
+
1143
+ // Check for a successful response
1144
+ if (response.status >= 200 && response.status <= 299) {
1145
+ verboseLog('System info sent successfully');
1146
+ } else {
1147
+ verboseLog(`Failed to send system info with status code: ${response.status}`);
1148
+ if (response.data) {
1149
+ verboseLog(`Error response: ${JSON.stringify(response.data)}`);
1150
+ }
1151
+ }
1152
+ } catch (error) {
1153
+ verboseLog(`Error sending system info: ${error}`);
1154
+ verboseLog(`Network error sending system info: ${error}`);
1155
+ }
1156
+ };
1157
+
263
1158
  // MARK: Short Codes
264
1159
  const isShortCode = (referringLink: string): boolean => {
265
1160
  // Short codes are 3-25 characters and can include underscores
@@ -332,10 +1227,17 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
332
1227
 
333
1228
  // Fallback to async storage if React state is empty
334
1229
  const storedLink = await getValueFromAsync(ASYNC_KEYS.REFERRER_LINK);
335
- const storedUserId = await getValueFromAsync(ASYNC_KEYS.USER_ID);
1230
+ let storedUserId = await getValueFromAsync(ASYNC_KEYS.USER_ID);
336
1231
 
337
1232
  verboseLog(`AsyncStorage - storedLink: ${storedLink || 'empty'}, storedUserId: ${storedUserId || 'empty'}`);
338
1233
 
1234
+ // If we have a stored link but no user ID, generate one now
1235
+ if (storedLink && !storedUserId) {
1236
+ verboseLog('Found stored link but no user ID, generating user ID now...');
1237
+ storedUserId = await generateThenSetUserID();
1238
+ verboseLog(`Generated user ID: ${storedUserId}`);
1239
+ }
1240
+
339
1241
  if (storedLink && storedUserId) {
340
1242
  const identifier = `${storedLink}-${storedUserId}`;
341
1243
  verboseLog(`Found identifier in AsyncStorage: ${identifier}`);
@@ -456,6 +1358,13 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
456
1358
  // Automatically fetch and store offer code for any affiliate identifier
457
1359
  verboseLog('Attempting to fetch offer code for stored affiliate identifier...');
458
1360
  await retrieveAndStoreOfferCode(link);
1361
+
1362
+ // Trigger callback with the current affiliate identifier
1363
+ if (insertAffiliateIdentifierChangeCallbackRef.current) {
1364
+ const currentIdentifier = await returnInsertAffiliateIdentifier();
1365
+ verboseLog(`Triggering callback with identifier: ${currentIdentifier}`);
1366
+ insertAffiliateIdentifierChangeCallbackRef.current(currentIdentifier);
1367
+ }
459
1368
  }
460
1369
 
461
1370
  const validatePurchaseWithIapticAPI = async (
@@ -754,6 +1663,8 @@ const DeepLinkIapProvider: React.FC<T_DEEPLINK_IAP_PROVIDER> = ({
754
1663
  validatePurchaseWithIapticAPI,
755
1664
  trackEvent,
756
1665
  setInsertAffiliateIdentifier,
1666
+ setInsertAffiliateIdentifierChangeCallback: setInsertAffiliateIdentifierChangeCallbackHandler,
1667
+ handleInsertLinks,
757
1668
  initialize,
758
1669
  isInitialized,
759
1670
  }}