@adshift/react-native-plugin 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/AdShiftReactNativePlugin.podspec +11 -7
  2. package/CHANGELOG.md +138 -0
  3. package/README.md +513 -542
  4. package/android/build.gradle +17 -3
  5. package/android/consumer-rules.pro +21 -0
  6. package/android/src/main/java/com/adshift/reactnativeplugin/AdShiftReactNativePluginModule.kt +786 -229
  7. package/android/src/test/java/com/adshift/reactnativeplugin/ConsentSnapshotTest.kt +180 -0
  8. package/android/src/test/java/com/adshift/reactnativeplugin/DeepLinkDeliveryTest.kt +146 -0
  9. package/android/src/test/java/com/adshift/reactnativeplugin/InitializeOrderingTest.kt +111 -0
  10. package/android/src/test/java/com/adshift/reactnativeplugin/IntentLinkDedupTest.kt +168 -0
  11. package/android/src/test/java/com/adshift/reactnativeplugin/LaunchIntentForwardingTest.kt +106 -0
  12. package/android/src/test/java/com/adshift/reactnativeplugin/ModuleTestSupport.kt +167 -0
  13. package/android/src/test/java/com/adshift/reactnativeplugin/StartVerdictTest.kt +164 -0
  14. package/ios/AdShiftReactNativePlugin.h +7 -7
  15. package/ios/AdShiftReactNativePlugin.mm +200 -181
  16. package/ios/AdShiftReactNativePluginHelper.swift +584 -286
  17. package/ios/Core/BridgeRules.swift +82 -0
  18. package/lib/commonjs/Adshift.js +1138 -0
  19. package/lib/commonjs/Adshift.js.map +1 -0
  20. package/lib/commonjs/NativeAdShiftReactNativePlugin.js +22 -0
  21. package/lib/commonjs/NativeAdShiftReactNativePlugin.js.map +1 -0
  22. package/lib/commonjs/index.js +94 -0
  23. package/lib/commonjs/index.js.map +1 -0
  24. package/lib/commonjs/jest/index.js +164 -0
  25. package/lib/commonjs/jest/index.js.map +1 -0
  26. package/lib/commonjs/nativeSdkVersions.js +17 -0
  27. package/lib/commonjs/nativeSdkVersions.js.map +1 -0
  28. package/lib/commonjs/package.json +1 -0
  29. package/lib/commonjs/types/AdshiftAdRevenue.js +47 -0
  30. package/lib/commonjs/types/AdshiftAdRevenue.js.map +1 -0
  31. package/lib/commonjs/types/AdshiftConfig.js +45 -0
  32. package/lib/commonjs/types/AdshiftConfig.js.map +1 -0
  33. package/lib/commonjs/types/AdshiftConsent.js +113 -0
  34. package/lib/commonjs/types/AdshiftConsent.js.map +1 -0
  35. package/lib/commonjs/types/AdshiftConsentSnapshot.js +69 -0
  36. package/lib/commonjs/types/AdshiftConsentSnapshot.js.map +1 -0
  37. package/lib/commonjs/types/AdshiftDeepLink.js +154 -0
  38. package/lib/commonjs/types/AdshiftDeepLink.js.map +1 -0
  39. package/lib/commonjs/types/AdshiftError.js +91 -0
  40. package/lib/commonjs/types/AdshiftError.js.map +1 -0
  41. package/lib/commonjs/types/AdshiftEventParam.js +140 -0
  42. package/lib/commonjs/types/AdshiftEventParam.js.map +1 -0
  43. package/lib/commonjs/types/AdshiftEventType.js +88 -0
  44. package/lib/commonjs/types/AdshiftEventType.js.map +1 -0
  45. package/lib/commonjs/types/AdshiftThirdPartySharing.js +70 -0
  46. package/lib/commonjs/types/AdshiftThirdPartySharing.js.map +1 -0
  47. package/lib/commonjs/types/index.js +123 -0
  48. package/lib/commonjs/types/index.js.map +1 -0
  49. package/lib/commonjs/version.js +9 -0
  50. package/lib/commonjs/version.js.map +1 -0
  51. package/lib/module/Adshift.js +962 -296
  52. package/lib/module/Adshift.js.map +1 -1
  53. package/lib/module/NativeAdShiftReactNativePlugin.js +10 -7
  54. package/lib/module/NativeAdShiftReactNativePlugin.js.map +1 -1
  55. package/lib/module/index.js +26 -25
  56. package/lib/module/index.js.map +1 -1
  57. package/lib/module/jest/index.js +144 -0
  58. package/lib/module/jest/index.js.map +1 -0
  59. package/lib/module/nativeSdkVersions.js +13 -0
  60. package/lib/module/nativeSdkVersions.js.map +1 -0
  61. package/lib/module/types/AdshiftAdRevenue.js +43 -0
  62. package/lib/module/types/AdshiftAdRevenue.js.map +1 -0
  63. package/lib/module/types/AdshiftConfig.js +23 -26
  64. package/lib/module/types/AdshiftConfig.js.map +1 -1
  65. package/lib/module/types/AdshiftConsent.js +57 -50
  66. package/lib/module/types/AdshiftConsent.js.map +1 -1
  67. package/lib/module/types/AdshiftConsentSnapshot.js +65 -0
  68. package/lib/module/types/AdshiftConsentSnapshot.js.map +1 -0
  69. package/lib/module/types/AdshiftDeepLink.js +97 -67
  70. package/lib/module/types/AdshiftDeepLink.js.map +1 -1
  71. package/lib/module/types/AdshiftError.js +87 -0
  72. package/lib/module/types/AdshiftError.js.map +1 -0
  73. package/lib/module/types/AdshiftEventParam.js +135 -0
  74. package/lib/module/types/AdshiftEventParam.js.map +1 -0
  75. package/lib/module/types/AdshiftEventType.js +11 -36
  76. package/lib/module/types/AdshiftEventType.js.map +1 -1
  77. package/lib/module/types/AdshiftThirdPartySharing.js +65 -0
  78. package/lib/module/types/AdshiftThirdPartySharing.js.map +1 -0
  79. package/lib/module/types/index.js +9 -7
  80. package/lib/module/types/index.js.map +1 -1
  81. package/lib/module/version.js +5 -0
  82. package/lib/module/version.js.map +1 -0
  83. package/lib/typescript/commonjs/package.json +1 -0
  84. package/lib/typescript/commonjs/src/Adshift.d.ts +314 -0
  85. package/lib/typescript/commonjs/src/Adshift.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/src/NativeAdShiftReactNativePlugin.d.ts +102 -0
  87. package/lib/typescript/commonjs/src/NativeAdShiftReactNativePlugin.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/src/index.d.ts +51 -0
  89. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  90. package/lib/typescript/commonjs/src/jest/index.d.ts +103 -0
  91. package/lib/typescript/commonjs/src/jest/index.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/src/nativeSdkVersions.d.ts +11 -0
  93. package/lib/typescript/commonjs/src/nativeSdkVersions.d.ts.map +1 -0
  94. package/lib/typescript/commonjs/src/types/AdshiftAdRevenue.d.ts +56 -0
  95. package/lib/typescript/commonjs/src/types/AdshiftAdRevenue.d.ts.map +1 -0
  96. package/lib/typescript/commonjs/src/types/AdshiftConfig.d.ts +104 -0
  97. package/lib/typescript/commonjs/src/types/AdshiftConfig.d.ts.map +1 -0
  98. package/lib/typescript/commonjs/src/types/AdshiftConsent.d.ts +76 -0
  99. package/lib/typescript/commonjs/src/types/AdshiftConsent.d.ts.map +1 -0
  100. package/lib/typescript/commonjs/src/types/AdshiftConsentSnapshot.d.ts +56 -0
  101. package/lib/typescript/commonjs/src/types/AdshiftConsentSnapshot.d.ts.map +1 -0
  102. package/lib/typescript/commonjs/src/types/AdshiftDeepLink.d.ts +89 -0
  103. package/lib/typescript/commonjs/src/types/AdshiftDeepLink.d.ts.map +1 -0
  104. package/lib/typescript/commonjs/src/types/AdshiftError.d.ts +57 -0
  105. package/lib/typescript/commonjs/src/types/AdshiftError.d.ts.map +1 -0
  106. package/lib/typescript/commonjs/src/types/AdshiftEventParam.d.ts +111 -0
  107. package/lib/typescript/commonjs/src/types/AdshiftEventParam.d.ts.map +1 -0
  108. package/lib/typescript/{src → commonjs/src}/types/AdshiftEventType.d.ts +12 -35
  109. package/lib/typescript/commonjs/src/types/AdshiftEventType.d.ts.map +1 -0
  110. package/lib/typescript/commonjs/src/types/AdshiftThirdPartySharing.d.ts +53 -0
  111. package/lib/typescript/commonjs/src/types/AdshiftThirdPartySharing.d.ts.map +1 -0
  112. package/lib/typescript/commonjs/src/types/index.d.ts +17 -0
  113. package/lib/typescript/commonjs/src/types/index.d.ts.map +1 -0
  114. package/lib/typescript/commonjs/src/version.d.ts +2 -0
  115. package/lib/typescript/commonjs/src/version.d.ts.map +1 -0
  116. package/lib/typescript/module/src/Adshift.d.ts +314 -0
  117. package/lib/typescript/module/src/Adshift.d.ts.map +1 -0
  118. package/lib/typescript/module/src/NativeAdShiftReactNativePlugin.d.ts +102 -0
  119. package/lib/typescript/module/src/NativeAdShiftReactNativePlugin.d.ts.map +1 -0
  120. package/lib/typescript/module/src/index.d.ts +51 -0
  121. package/lib/typescript/module/src/index.d.ts.map +1 -0
  122. package/lib/typescript/module/src/jest/index.d.ts +103 -0
  123. package/lib/typescript/module/src/jest/index.d.ts.map +1 -0
  124. package/lib/typescript/module/src/nativeSdkVersions.d.ts +11 -0
  125. package/lib/typescript/module/src/nativeSdkVersions.d.ts.map +1 -0
  126. package/lib/typescript/module/src/types/AdshiftAdRevenue.d.ts +56 -0
  127. package/lib/typescript/module/src/types/AdshiftAdRevenue.d.ts.map +1 -0
  128. package/lib/typescript/module/src/types/AdshiftConfig.d.ts +104 -0
  129. package/lib/typescript/module/src/types/AdshiftConfig.d.ts.map +1 -0
  130. package/lib/typescript/module/src/types/AdshiftConsent.d.ts +76 -0
  131. package/lib/typescript/module/src/types/AdshiftConsent.d.ts.map +1 -0
  132. package/lib/typescript/module/src/types/AdshiftConsentSnapshot.d.ts +56 -0
  133. package/lib/typescript/module/src/types/AdshiftConsentSnapshot.d.ts.map +1 -0
  134. package/lib/typescript/module/src/types/AdshiftDeepLink.d.ts +89 -0
  135. package/lib/typescript/module/src/types/AdshiftDeepLink.d.ts.map +1 -0
  136. package/lib/typescript/module/src/types/AdshiftError.d.ts +57 -0
  137. package/lib/typescript/module/src/types/AdshiftError.d.ts.map +1 -0
  138. package/lib/typescript/module/src/types/AdshiftEventParam.d.ts +111 -0
  139. package/lib/typescript/module/src/types/AdshiftEventParam.d.ts.map +1 -0
  140. package/lib/typescript/module/src/types/AdshiftEventType.d.ts +64 -0
  141. package/lib/typescript/module/src/types/AdshiftEventType.d.ts.map +1 -0
  142. package/lib/typescript/module/src/types/AdshiftThirdPartySharing.d.ts +53 -0
  143. package/lib/typescript/module/src/types/AdshiftThirdPartySharing.d.ts.map +1 -0
  144. package/lib/typescript/module/src/types/index.d.ts +17 -0
  145. package/lib/typescript/module/src/types/index.d.ts.map +1 -0
  146. package/lib/typescript/module/src/version.d.ts +2 -0
  147. package/lib/typescript/module/src/version.d.ts.map +1 -0
  148. package/package.json +50 -11
  149. package/src/Adshift.ts +1276 -342
  150. package/src/NativeAdShiftReactNativePlugin.ts +81 -115
  151. package/src/index.tsx +40 -25
  152. package/src/jest/index.ts +224 -0
  153. package/src/nativeSdkVersions.ts +10 -0
  154. package/src/types/AdshiftAdRevenue.ts +58 -0
  155. package/src/types/AdshiftConfig.ts +101 -53
  156. package/src/types/AdshiftConsent.ts +75 -72
  157. package/src/types/AdshiftConsentSnapshot.ts +103 -0
  158. package/src/types/AdshiftDeepLink.ts +123 -102
  159. package/src/types/AdshiftError.ts +107 -0
  160. package/src/types/AdshiftEventParam.ts +216 -0
  161. package/src/types/AdshiftEventType.ts +13 -35
  162. package/src/types/AdshiftThirdPartySharing.ts +63 -0
  163. package/src/types/index.ts +38 -6
  164. package/src/version.ts +2 -0
  165. package/lib/typescript/src/Adshift.d.ts +0 -335
  166. package/lib/typescript/src/Adshift.d.ts.map +0 -1
  167. package/lib/typescript/src/NativeAdShiftReactNativePlugin.d.ts +0 -143
  168. package/lib/typescript/src/NativeAdShiftReactNativePlugin.d.ts.map +0 -1
  169. package/lib/typescript/src/index.d.ts +0 -47
  170. package/lib/typescript/src/index.d.ts.map +0 -1
  171. package/lib/typescript/src/types/AdshiftConfig.d.ts +0 -74
  172. package/lib/typescript/src/types/AdshiftConfig.d.ts.map +0 -1
  173. package/lib/typescript/src/types/AdshiftConsent.d.ts +0 -88
  174. package/lib/typescript/src/types/AdshiftConsent.d.ts.map +0 -1
  175. package/lib/typescript/src/types/AdshiftDeepLink.d.ts +0 -93
  176. package/lib/typescript/src/types/AdshiftDeepLink.d.ts.map +0 -1
  177. package/lib/typescript/src/types/AdshiftEventType.d.ts.map +0 -1
  178. package/lib/typescript/src/types/index.d.ts +0 -5
  179. package/lib/typescript/src/types/index.d.ts.map +0 -1
  180. /package/lib/typescript/{package.json → module/package.json} +0 -0
package/src/Adshift.ts CHANGED
@@ -1,355 +1,1151 @@
1
1
  /**
2
- * AdShift SDK for React Native
3
- *
4
- * Main SDK interface providing type-safe access to native AdShift functionality.
2
+ * AdShift SDK for React Native.
5
3
  *
6
4
  * @example
7
5
  * ```typescript
8
- * import { Adshift, AdshiftEventType } from '@adshift/react-native-plugin';
6
+ * import {
7
+ * Adshift,
8
+ * AdshiftEventParam,
9
+ * AdshiftEventType,
10
+ * } from '@adshift/react-native-plugin';
9
11
  *
10
- * // 1. Initialize
11
- * Adshift.initialize({ apiKey: 'your-api-key', isDebug: true });
12
+ * // 1. Register the deep link listener (safe to do before initialize)
13
+ * const subscription = Adshift.onDeepLink((deepLink) => {
14
+ * // route on deepLink.deepLinkValue / deepLink.params
15
+ * });
12
16
  *
13
- * // 2. Start tracking
14
- * await Adshift.start();
17
+ * // 2. Initialize
18
+ * Adshift.initialize({ apiKey: 'your-api-key', isDebug: __DEV__ });
15
19
  *
16
- * // 3. Track events
17
- * await Adshift.trackEvent(AdshiftEventType.Purchase, { price: 9.99 });
20
+ * // 3. Start
21
+ * const result = await Adshift.start();
18
22
  *
19
- * // 4. Listen for deep links
20
- * const subscription = Adshift.onDeepLink((deepLink) => {
21
- * console.log('Deep link received:', deepLink);
23
+ * // 4. Track
24
+ * await Adshift.trackEvent(AdshiftEventType.Purchase, {
25
+ * [AdshiftEventParam.Revenue]: 9.99,
26
+ * [AdshiftEventParam.Currency]: 'USD',
22
27
  * });
28
+ *
23
29
  * // Later: subscription.remove();
24
30
  * ```
25
31
  */
26
32
 
27
- import { NativeEventEmitter, Platform } from 'react-native';
33
+ import { Linking, Platform } from 'react-native';
34
+ import type { EventSubscription } from 'react-native';
28
35
  import NativeAdShiftReactNativePlugin from './NativeAdShiftReactNativePlugin';
29
- import type { AdshiftConfig, AdshiftConsent, AdshiftDeepLink } from './types';
36
+ import type { NativeDeepLinkPayload } from './NativeAdShiftReactNativePlugin';
37
+ import { NATIVE_SDK_VERSIONS } from './nativeSdkVersions';
38
+ import type {
39
+ AdRevenueParams,
40
+ AdshiftConfig,
41
+ AdshiftConsent,
42
+ AdshiftDeepLink,
43
+ AdshiftError,
44
+ AdshiftEventTypeValue,
45
+ AdshiftThirdPartySharing,
46
+ ConsentSnapshot,
47
+ } from './types';
30
48
  import {
49
+ AdshiftDeepLink as AdshiftDeepLinkHelpers,
50
+ AdshiftErrorCode,
51
+ AdshiftEventParam,
52
+ AdshiftMediationNetwork,
31
53
  configToMap,
54
+ getAllEventParams,
55
+ consentSnapshotFromMap,
32
56
  consentToMap,
33
- AdshiftDeepLink as AdshiftDeepLinkHelpers,
57
+ createAdshiftError,
58
+ thirdPartySharingToMap,
59
+ toAdshiftError,
34
60
  } from './types';
61
+ import { PLUGIN_VERSION } from './version';
35
62
 
36
- // ============ Types ============
63
+ // ============ Public types ============
37
64
 
38
65
  /**
39
- * Result returned from Adshift.start()
66
+ * Result of `Adshift.start()`.
67
+ *
68
+ * `success` reports whether the SDK started locally. The API key is checked
69
+ * with the backend in the background: `apiKeyValidationStatus` is the verdict
70
+ * at the time `start()` resolved, and `config.onError` reports
71
+ * `INVALID_API_KEY` when that verdict is `invalid`. On iOS the verdict usually
72
+ * arrives after `start()` resolved and is reported by the next `start()`; on
73
+ * Android `start()` waits up to 5 s for it.
40
74
  */
41
75
  export interface StartResult {
42
- /** Whether start was successful */
43
76
  success: boolean;
44
- /** Optional message from native SDK */
45
- message?: string;
77
+ /**
78
+ * Outcome of the API key check at the time `start()` resolved; `pending`
79
+ * means the answer had not arrived yet. It changes nothing you have to do:
80
+ * events tracked meanwhile stay queued on the device by the native SDK.
81
+ */
82
+ apiKeyValidationStatus?: ApiKeyValidationStatus;
83
+ /** Platform error number behind `errorCode`, for support requests. */
84
+ nativeCode?: number | string;
85
+ /** Platform error domain behind `errorCode`. @platform ios */
86
+ nativeDomain?: string;
87
+ /** Set when `success` is false. */
88
+ errorCode?: AdshiftErrorCode;
89
+ /** Set when `success` is false. */
90
+ errorMessage?: string;
46
91
  }
47
92
 
48
- /**
49
- * Values that can be passed to trackEvent
50
- */
93
+ /** How far the API key check had got when `start()` resolved. */
94
+ export type ApiKeyValidationStatus = 'pending' | 'valid' | 'invalid';
95
+
51
96
  export type EventValues = Record<string, string | number | boolean>;
52
97
 
53
98
  /**
54
- * Parameters for trackPurchase
99
+ * Parameters for `Adshift.trackPurchase()`.
55
100
  */
56
101
  export interface PurchaseParams {
57
- /** Product identifier */
102
+ /** Product identifier. */
58
103
  productId: string;
59
- /** Purchase amount (revenue) */
104
+ /** Purchase amount in `currency`. */
60
105
  revenue: number;
61
- /** ISO currency code (e.g., "USD") */
106
+ /** ISO 4217 currency code, e.g. `USD`. */
62
107
  currency: string;
63
- /** Transaction ID / purchase receipt token */
108
+ /** Transaction id or purchase token. */
64
109
  transactionId: string;
65
110
  }
66
111
 
67
112
  /**
68
- * Subscription returned from onDeepLink
113
+ * Subscription returned by `Adshift.onDeepLink()`.
69
114
  */
70
115
  export interface DeepLinkSubscription {
71
- /** Removes the deep link listener */
116
+ /** Removes the listener. Safe to call more than once. */
72
117
  remove(): void;
73
118
  }
74
119
 
120
+ export type DeepLinkCallback = (deepLink: AdshiftDeepLink) => void;
121
+
75
122
  /**
76
- * Callback for deep link events
123
+ * Native SDK versions bundled with this plugin release.
77
124
  */
78
- export type DeepLinkCallback = (deepLink: AdshiftDeepLink) => void;
125
+ export interface NativeSdkVersions {
126
+ android: string;
127
+ ios: string;
128
+ }
79
129
 
80
- // ============ Internal State ============
130
+ /**
131
+ * Plugin information returned by `Adshift.getInfo()`.
132
+ */
133
+ export interface AdshiftInfo {
134
+ /** `Platform.OS`; the SDK only supports `ios` and `android`. */
135
+ platform: 'ios' | 'android' | (string & {});
136
+ /** Plugin version. */
137
+ version: string;
138
+ /** Native SDK versions this plugin depends on. */
139
+ nativeSdkVersions: NativeSdkVersions;
140
+ }
81
141
 
82
- let _isInitialized = false;
83
- let _eventEmitter: NativeEventEmitter | null = null;
142
+ // ============ Constants ============
84
143
 
85
- // ============ Internal Helpers ============
144
+ const DEEP_LINK_BUFFER_LIMIT = 20;
145
+ const PENDING_CALL_LIMIT = 100;
146
+ /** Bounds how long `start()` waits for the URL the app was opened with. */
147
+ const INITIAL_URL_WAIT_MS = 3000;
148
+ /** How long one URL counts as the same link, whoever passed it in first. */
149
+ const AUTO_FORWARD_DEDUP_MS = 2000;
150
+ /**
151
+ * Mirrors a limit the SDK applies, so the warning below can name it. Raising it
152
+ * there without raising it here makes the warning wrong, not the behaviour.
153
+ */
154
+ const MAX_AD_REVENUE_PER_IMPRESSION = 10;
155
+ const MEDIATION_NETWORKS: ReadonlySet<string> = new Set(
156
+ Object.values(AdshiftMediationNetwork)
157
+ );
158
+ /**
159
+ * Event names the SDK sends on its own. Sending them by hand would mix
160
+ * hand-made records into install and session counts, which cannot be undone
161
+ * once they are reported.
162
+ */
163
+ const RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([
164
+ 'app_install',
165
+ 'app_open',
166
+ ]);
167
+
168
+ type LifecycleState =
169
+ | 'uninitialized'
170
+ | 'initialized'
171
+ | 'starting'
172
+ | 'started'
173
+ | 'stopped';
174
+
175
+ interface ListenerEntry {
176
+ callback: DeepLinkCallback;
177
+ }
178
+
179
+ interface PendingCall {
180
+ run: () => Promise<unknown>;
181
+ resolve: (value: unknown) => void;
182
+ reject: (error: AdshiftError) => void;
183
+ }
184
+
185
+ /**
186
+ * Configuration received before `initialize()`. Each entry holds the latest
187
+ * value for one setter, so the memory is bounded by the number of setters.
188
+ */
189
+ interface PendingSettings {
190
+ customerUserId?: string;
191
+ debugEnabled?: boolean;
192
+ appOpenDebounceMs?: number;
193
+ brandedDomains?: string[];
194
+ metaAppId?: string;
195
+ oaid?: string;
196
+ consent?: AdshiftConsent;
197
+ tcfEnabled?: boolean;
198
+ gppEnabled?: boolean;
199
+ /**
200
+ * Absent means neither sharing call was made; `null` means the last one was
201
+ * `clearThirdPartySharing()`. Two calls share this slot, so the distinction
202
+ * has to survive here or a clear before `initialize()` would be dropped and
203
+ * the set it was meant to undo would still be applied.
204
+ */
205
+ thirdPartySharing?: AdshiftThirdPartySharing | null;
206
+ pushDeepLinkPaths: string[][];
207
+ }
208
+
209
+ // ============ Internal state ============
210
+
211
+ let state: LifecycleState = 'uninitialized';
212
+ let frozenConfig: Readonly<AdshiftConfig> | null = null;
213
+ let startInFlight: Promise<StartResult> | null = null;
214
+ /** Incremented per start attempt so a superseded attempt cannot touch the state. */
215
+ let startEpoch = 0;
216
+
217
+ let nativeSubscription: EventSubscription | null = null;
218
+ const listeners = new Set<ListenerEntry>();
219
+ const deepLinkBuffer: AdshiftDeepLink[] = [];
220
+ let replayScheduled = false;
221
+
222
+ const pendingCalls: PendingCall[] = [];
86
223
 
87
- function ensureInitialized(): void {
88
- if (!_isInitialized) {
89
- throw new Error(
90
- 'AdShift SDK not initialized. Call Adshift.initialize(config) first.'
224
+ let linkingSubscription: EventSubscription | null = null;
225
+ let initialUrlForward: Promise<void> | null = null;
226
+ const autoForwarded = new Map<string, number>();
227
+
228
+ let pendingSettings: PendingSettings = { pushDeepLinkPaths: [] };
229
+ let errorHandler: ((error: AdshiftError) => void) | null = null;
230
+ /** Kept so `start()` can answer with the reason `initialize()` was refused. */
231
+ let configError: AdshiftError | null = null;
232
+
233
+ // ============ Logging ============
234
+
235
+ function devWarn(message: string): void {
236
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
237
+ console.warn(`[AdShift] ${message}`);
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Reports a call the plugin declined to make.
243
+ *
244
+ * Public methods that return nothing have no channel to answer through, so
245
+ * they never raise: raising would unwind a stack the caller did not choose,
246
+ * and React Native treats an error escaping an event handler or a native
247
+ * callback as fatal. The call is skipped and reported here instead.
248
+ */
249
+ function reportDeclined(error: AdshiftError): void {
250
+ devWarn(`${error.message} (${error.code})`);
251
+ if (!errorHandler) return;
252
+ try {
253
+ errorHandler(error);
254
+ } catch {
255
+ devWarn('config.onError threw; ignoring it.');
256
+ }
257
+ }
258
+
259
+ // ============ Errors ============
260
+
261
+ function notInitializedError(): AdshiftError {
262
+ return createAdshiftError(
263
+ AdshiftErrorCode.NotInitialized,
264
+ 'AdShift SDK is not initialized. Call Adshift.initialize(config) first.'
265
+ );
266
+ }
267
+
268
+ function notStartedError(): AdshiftError {
269
+ return createAdshiftError(
270
+ AdshiftErrorCode.NotStarted,
271
+ 'AdShift SDK is stopped. Call Adshift.start() first.'
272
+ );
273
+ }
274
+
275
+ function invalidArgument(message: string): AdshiftError {
276
+ return createAdshiftError(AdshiftErrorCode.InvalidArgument, message);
277
+ }
278
+
279
+ function isNonEmptyString(value: unknown): value is string {
280
+ return typeof value === 'string' && value.trim().length > 0;
281
+ }
282
+
283
+ function isFiniteNumber(value: unknown): value is number {
284
+ return typeof value === 'number' && Number.isFinite(value);
285
+ }
286
+
287
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
288
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
289
+ }
290
+
291
+ function isStringArray(value: unknown): value is string[] {
292
+ return Array.isArray(value) && value.every(isNonEmptyString);
293
+ }
294
+
295
+ /**
296
+ * Plain names a caller is likely to invent, mapped onto the standard constant
297
+ * that carries the same meaning. Built from the constants so there is one list
298
+ * to keep, not two.
299
+ */
300
+ const STANDARD_PARAM_BY_PLAIN_NAME: ReadonlyMap<
301
+ string,
302
+ keyof typeof AdshiftEventParam
303
+ > = (() => {
304
+ const index = new Map<string, keyof typeof AdshiftEventParam>();
305
+ const standard = new Set<string>(getAllEventParams());
306
+ for (const [key, value] of Object.entries(AdshiftEventParam)) {
307
+ const bare = value.slice('as_'.length);
308
+ const aliases = [
309
+ bare,
310
+ bare.replace(/_([a-z0-9])/g, (_match, char: string) =>
311
+ char.toUpperCase()
312
+ ),
313
+ key.charAt(0).toLowerCase() + key.slice(1),
314
+ ];
315
+ for (const alias of aliases) {
316
+ if (!standard.has(alias) && !index.has(alias)) {
317
+ index.set(alias, key as keyof typeof AdshiftEventParam);
318
+ }
319
+ }
320
+ }
321
+ return index;
322
+ })();
323
+
324
+ const reportedPlainParamNames = new Set<string>();
325
+
326
+ /**
327
+ * Warns once per name when a value carries a plain name instead of the
328
+ * standard one. Sending it is allowed — it just stays a custom parameter.
329
+ */
330
+ function warnAboutPlainParamNames(values: EventValues | undefined): void {
331
+ if (values === undefined) return;
332
+ for (const key of Object.keys(values)) {
333
+ const standard = STANDARD_PARAM_BY_PLAIN_NAME.get(key);
334
+ if (standard === undefined || reportedPlainParamNames.has(key)) continue;
335
+ reportedPlainParamNames.add(key);
336
+ devWarn(
337
+ `"${key}" is kept as a custom parameter. Use AdshiftEventParam.${standard} ` +
338
+ `("${AdshiftEventParam[standard]}") for a value reports should count.`
91
339
  );
92
340
  }
93
341
  }
94
342
 
95
- function getEventEmitter(): NativeEventEmitter {
96
- if (!_eventEmitter) {
97
- _eventEmitter = new NativeEventEmitter(NativeAdShiftReactNativePlugin);
343
+ function validateEventValues(values: unknown, name: string): void {
344
+ if (values === undefined || values === null) return;
345
+ if (!isPlainObject(values)) {
346
+ throw invalidArgument(`AdShift SDK: ${name} must be an object`);
347
+ }
348
+ for (const [key, value] of Object.entries(values)) {
349
+ const type = typeof value;
350
+ if (type !== 'string' && type !== 'number' && type !== 'boolean') {
351
+ throw invalidArgument(
352
+ `AdShift SDK: ${name}.${key} must be a string, number or boolean`
353
+ );
354
+ }
355
+ if (type === 'number' && !Number.isFinite(value)) {
356
+ throw invalidArgument(`AdShift SDK: ${name}.${key} must be finite`);
357
+ }
98
358
  }
99
- return _eventEmitter;
100
359
  }
101
360
 
102
- // ============ Main SDK API ============
361
+ // ============ Configuration received before initialize() ============
362
+
363
+ /**
364
+ * Folds settings received before `initialize()` into the config.
365
+ *
366
+ * The config wins for anything it states, because it is the later and more
367
+ * explicit declaration. Push key paths are additive, so they are merged.
368
+ * Settings that reach the SDK through a setter only are applied by
369
+ * `applyPendingSettings()` right after the native module is initialized.
370
+ */
371
+ function withPendingSettings(config: AdshiftConfig): AdshiftConfig {
372
+ const merged: AdshiftConfig = { ...config };
373
+ const pending = pendingSettings;
374
+ if (merged.isDebug === undefined && pending.debugEnabled !== undefined) {
375
+ merged.isDebug = pending.debugEnabled;
376
+ }
377
+ if (
378
+ merged.appOpenDebounceMs === undefined &&
379
+ pending.appOpenDebounceMs !== undefined
380
+ ) {
381
+ merged.appOpenDebounceMs = pending.appOpenDebounceMs;
382
+ }
383
+ if (merged.brandedDomains === undefined && pending.brandedDomains) {
384
+ merged.brandedDomains = pending.brandedDomains;
385
+ }
386
+ if (merged.metaAppId === undefined && pending.metaAppId !== undefined) {
387
+ merged.metaAppId = pending.metaAppId;
388
+ }
389
+ if (pending.pushDeepLinkPaths.length > 0) {
390
+ merged.pushDeepLinkPaths = [
391
+ ...(merged.pushDeepLinkPaths ?? []),
392
+ ...pending.pushDeepLinkPaths,
393
+ ];
394
+ }
395
+ return merged;
396
+ }
397
+
398
+ function applyPendingSettings(): void {
399
+ const pending = pendingSettings;
400
+ pendingSettings = { pushDeepLinkPaths: [] };
401
+ if (pending.customerUserId !== undefined) {
402
+ NativeAdShiftReactNativePlugin.setCustomerUserId(pending.customerUserId);
403
+ }
404
+ if (pending.oaid !== undefined) {
405
+ NativeAdShiftReactNativePlugin.setOaidData(pending.oaid);
406
+ }
407
+ if (pending.consent !== undefined) {
408
+ NativeAdShiftReactNativePlugin.setConsentData(
409
+ consentToMap(pending.consent)
410
+ );
411
+ }
412
+ if (pending.tcfEnabled !== undefined) {
413
+ NativeAdShiftReactNativePlugin.enableTCFDataCollection(pending.tcfEnabled);
414
+ }
415
+ if (pending.gppEnabled !== undefined) {
416
+ NativeAdShiftReactNativePlugin.enableGPPDataCollection(pending.gppEnabled);
417
+ }
418
+ if (pending.thirdPartySharing !== undefined) {
419
+ if (pending.thirdPartySharing === null) {
420
+ NativeAdShiftReactNativePlugin.clearThirdPartySharing();
421
+ } else {
422
+ NativeAdShiftReactNativePlugin.setThirdPartySharing(
423
+ thirdPartySharingToMap(pending.thirdPartySharing)
424
+ );
425
+ }
426
+ }
427
+ }
428
+
429
+ // ============ Deep link delivery ============
430
+
431
+ function ensureNativeSubscription(): void {
432
+ if (nativeSubscription) return;
433
+ nativeSubscription = NativeAdShiftReactNativePlugin.onDeepLink(
434
+ (payload: NativeDeepLinkPayload) => {
435
+ dispatchDeepLink(
436
+ AdshiftDeepLinkHelpers.fromMap(payload as Record<string, unknown>)
437
+ );
438
+ }
439
+ );
440
+ }
441
+
442
+ function dispatchDeepLink(deepLink: AdshiftDeepLink): void {
443
+ // A result must never overtake one already waiting in the buffer: a deferred
444
+ // link delivered after a link tapped later would attribute the install to
445
+ // the wrong click.
446
+ if (listeners.size === 0 || deepLinkBuffer.length > 0) {
447
+ bufferDeepLink(deepLink);
448
+ scheduleReplay();
449
+ return;
450
+ }
451
+ deliver(deepLink);
452
+ }
453
+
454
+ function deliver(deepLink: AdshiftDeepLink): void {
455
+ for (const entry of Array.from(listeners)) {
456
+ if (!listeners.has(entry)) continue;
457
+ try {
458
+ entry.callback(deepLink);
459
+ } catch (error) {
460
+ devWarn(
461
+ `onDeepLink listener threw: ${
462
+ error instanceof Error ? error.message : String(error)
463
+ }`
464
+ );
465
+ }
466
+ }
467
+ }
468
+
469
+ function bufferDeepLink(deepLink: AdshiftDeepLink): void {
470
+ if (deepLinkBuffer.length >= DEEP_LINK_BUFFER_LIMIT) {
471
+ const evictable = deepLinkBuffer.findIndex((item) => !item.isDeferred);
472
+ if (evictable >= 0) {
473
+ deepLinkBuffer.splice(evictable, 1);
474
+ } else if (deepLink.isDeferred) {
475
+ deepLinkBuffer.shift();
476
+ } else {
477
+ devWarn('Deep link buffer is full; dropping a direct deep link.');
478
+ return;
479
+ }
480
+ }
481
+ deepLinkBuffer.push(deepLink);
482
+ }
483
+
484
+ function scheduleReplay(): void {
485
+ if (replayScheduled) return;
486
+ replayScheduled = true;
487
+ Promise.resolve().then(() => {
488
+ replayScheduled = false;
489
+ if (listeners.size === 0 || deepLinkBuffer.length === 0) return;
490
+ const items = deepLinkBuffer.splice(0, deepLinkBuffer.length);
491
+ for (const item of items) {
492
+ deliver(item);
493
+ }
494
+ });
495
+ }
496
+
497
+ // ============ Automatic URL forwarding (iOS) ============
498
+
499
+ function autoForwardEnabled(): boolean {
500
+ return (
501
+ Platform.OS === 'ios' &&
502
+ frozenConfig !== null &&
503
+ frozenConfig.autoHandleDeepLinks !== false
504
+ );
505
+ }
506
+
507
+ function startLinkingAutoForward(): void {
508
+ if (linkingSubscription) return;
509
+ linkingSubscription = Linking.addEventListener('url', ({ url }) => {
510
+ if (state === 'uninitialized' || !autoForwardEnabled()) return;
511
+ // An app that handles `url` itself and calls handleDeepLink() sees the same
512
+ // event here, and the two are indistinguishable from a second tap. The
513
+ // short window treats them as one link; a tap that comes later is a
514
+ // separate click and is forwarded.
515
+ if (wasAutoForwardedRecently(url)) return;
516
+ forwardUrl(url, false).catch(() => undefined);
517
+ });
518
+ // The launch URL is read on every initialize(), so it comes back after a
519
+ // JavaScript reload as well. It is marked as such, and the native side keeps
520
+ // it for the lifetime of the process, so the link is booked once.
521
+ initialUrlForward = Linking.getInitialURL()
522
+ .then((url) => (url ? forwardUrl(url, true) : undefined))
523
+ .catch(() => undefined)
524
+ .finally(() => {
525
+ initialUrlForward = null;
526
+ });
527
+ }
528
+
529
+ async function forwardUrl(url: string, fromLaunch: boolean): Promise<void> {
530
+ if (!isNonEmptyString(url)) return;
531
+ pruneAutoForwarded();
532
+ autoForwarded.set(url, Date.now());
533
+ try {
534
+ await NativeAdShiftReactNativePlugin.handleDeepLink(url, fromLaunch);
535
+ } catch (error) {
536
+ const mapped = toAdshiftError(error);
537
+ if (mapped.code !== AdshiftErrorCode.OptedOut) {
538
+ devWarn(`Automatic deep link forwarding failed: ${mapped.code}`);
539
+ }
540
+ }
541
+ }
542
+
543
+ function pruneAutoForwarded(): void {
544
+ const cutoff = Date.now() - AUTO_FORWARD_DEDUP_MS;
545
+ for (const [url, timestamp] of autoForwarded) {
546
+ if (timestamp < cutoff) {
547
+ autoForwarded.delete(url);
548
+ }
549
+ }
550
+ }
551
+
552
+ function wasAutoForwardedRecently(url: string): boolean {
553
+ pruneAutoForwarded();
554
+ return autoForwarded.has(url);
555
+ }
556
+
557
+ async function waitForInitialUrlForward(): Promise<void> {
558
+ const pending = initialUrlForward;
559
+ if (!pending) return;
560
+ let timer: ReturnType<typeof setTimeout> | undefined;
561
+ const timeout = new Promise<void>((resolve) => {
562
+ timer = setTimeout(resolve, INITIAL_URL_WAIT_MS);
563
+ });
564
+ try {
565
+ await Promise.race([pending, timeout]);
566
+ } finally {
567
+ if (timer !== undefined) clearTimeout(timer);
568
+ }
569
+ }
570
+
571
+ // ============ Start gating ============
572
+
573
+ function runWhenStarted<T>(run: () => Promise<T>): Promise<T> {
574
+ switch (state) {
575
+ case 'uninitialized':
576
+ return Promise.reject(notInitializedError());
577
+ case 'stopped':
578
+ return Promise.reject(notStartedError());
579
+ case 'started':
580
+ return run().catch((error) => {
581
+ throw toAdshiftError(error);
582
+ });
583
+ case 'initialized':
584
+ case 'starting':
585
+ if (pendingCalls.length >= PENDING_CALL_LIMIT) {
586
+ return Promise.reject(
587
+ createAdshiftError(
588
+ AdshiftErrorCode.QueueFull,
589
+ 'AdShift SDK: too many calls are waiting for start().'
590
+ )
591
+ );
592
+ }
593
+ if (startEpoch === 0 && pendingCalls.length === 0) {
594
+ devWarn(
595
+ 'Call queued until start() runs; it settles when the first start attempt finishes.'
596
+ );
597
+ }
598
+ return new Promise<T>((resolve, reject) => {
599
+ pendingCalls.push({
600
+ run,
601
+ resolve: resolve as (value: unknown) => void,
602
+ reject,
603
+ });
604
+ });
605
+ }
606
+ }
607
+
608
+ function flushPendingCalls(): void {
609
+ const calls = pendingCalls.splice(0, pendingCalls.length);
610
+ for (const call of calls) {
611
+ call
612
+ .run()
613
+ .then(call.resolve)
614
+ .catch((error) => call.reject(toAdshiftError(error)));
615
+ }
616
+ }
617
+
618
+ function rejectPendingCalls(error: AdshiftError): void {
619
+ const calls = pendingCalls.splice(0, pendingCalls.length);
620
+ for (const call of calls) {
621
+ call.reject(error);
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Warns when the native SDK on the device is not the one this release was built
627
+ * against. Only iOS reports its version, so on Android the pin is guarded by a
628
+ * build-time test instead.
629
+ */
630
+ function checkNativeSdkVersion(reported: unknown): void {
631
+ if (typeof reported !== 'string' || reported.length === 0) return;
632
+ const expected =
633
+ Platform.OS === 'ios'
634
+ ? NATIVE_SDK_VERSIONS.ios
635
+ : Platform.OS === 'android'
636
+ ? NATIVE_SDK_VERSIONS.android
637
+ : null;
638
+ if (expected !== null && reported !== expected) {
639
+ devWarn(
640
+ `Native SDK ${reported} differs from the version this plugin was built for (${expected}).`
641
+ );
642
+ }
643
+ }
644
+
645
+ function readStartResult(raw: unknown): StartResult {
646
+ const map = isPlainObject(raw) ? raw : {};
647
+ checkNativeSdkVersion(map.sdkVersion);
648
+ const result: StartResult = { success: map.success === true };
649
+ const validation = map.apiKeyValidationStatus;
650
+ if (
651
+ validation === 'pending' ||
652
+ validation === 'valid' ||
653
+ validation === 'invalid'
654
+ ) {
655
+ result.apiKeyValidationStatus = validation;
656
+ }
657
+ if (!result.success) {
658
+ const code = map.errorCode;
659
+ result.errorCode =
660
+ typeof code === 'string' &&
661
+ (Object.values(AdshiftErrorCode) as string[]).includes(code)
662
+ ? (code as AdshiftErrorCode)
663
+ : AdshiftErrorCode.Unknown;
664
+ result.errorMessage =
665
+ typeof map.errorMessage === 'string'
666
+ ? map.errorMessage
667
+ : 'AdShift SDK failed to start.';
668
+ if (
669
+ typeof map.nativeCode === 'number' ||
670
+ typeof map.nativeCode === 'string'
671
+ ) {
672
+ result.nativeCode = map.nativeCode;
673
+ }
674
+ if (typeof map.nativeDomain === 'string') {
675
+ result.nativeDomain = map.nativeDomain;
676
+ }
677
+ }
678
+ return result;
679
+ }
680
+
681
+ async function performStart(): Promise<StartResult> {
682
+ const previous = state;
683
+ const epoch = ++startEpoch;
684
+ state = 'starting';
685
+ try {
686
+ await waitForInitialUrlForward();
687
+ const result = readStartResult(
688
+ await NativeAdShiftReactNativePlugin.start()
689
+ );
690
+ if (epoch !== startEpoch) {
691
+ // A newer start() owns the lifecycle now; report what native said and
692
+ // leave the state to the newer attempt.
693
+ return result;
694
+ }
695
+ if (state !== 'starting') {
696
+ // stop() was called while start() was in flight; honour the last call.
697
+ if (result.success) {
698
+ NativeAdShiftReactNativePlugin.stop();
699
+ }
700
+ const error = notStartedError();
701
+ return {
702
+ success: false,
703
+ errorCode: error.code,
704
+ errorMessage: error.message,
705
+ };
706
+ }
707
+ if (result.success) {
708
+ state = 'started';
709
+ flushPendingCalls();
710
+ if (result.apiKeyValidationStatus === 'invalid') {
711
+ // The SDK started locally, but nothing it sends will be accepted.
712
+ reportDeclined(
713
+ createAdshiftError(
714
+ AdshiftErrorCode.InvalidApiKey,
715
+ 'AdShift SDK: the backend rejected this API key; no data will be reported.'
716
+ )
717
+ );
718
+ }
719
+ return result;
720
+ }
721
+ state = previous;
722
+ const error = createAdshiftError(
723
+ result.errorCode ?? AdshiftErrorCode.Unknown,
724
+ result.errorMessage ?? 'AdShift SDK failed to start.'
725
+ );
726
+ reportDeclined(error);
727
+ if (isTerminalStartFailure(error.code)) {
728
+ rejectPendingCalls(error);
729
+ }
730
+ return result;
731
+ } catch (error) {
732
+ const mapped = toAdshiftError(error);
733
+ if (epoch === startEpoch && state === 'starting') {
734
+ state = previous;
735
+ }
736
+ const result: StartResult = {
737
+ success: false,
738
+ errorCode: mapped.code,
739
+ errorMessage: mapped.message,
740
+ };
741
+ // What the platform said travels with the result, the same way it does
742
+ // when the native side answers with a failure instead of rejecting.
743
+ if (mapped.userInfo.nativeCode !== undefined) {
744
+ result.nativeCode = mapped.userInfo.nativeCode;
745
+ }
746
+ if (mapped.userInfo.nativeDomain !== undefined) {
747
+ result.nativeDomain = mapped.userInfo.nativeDomain;
748
+ }
749
+ return result;
750
+ }
751
+ }
103
752
 
104
753
  /**
105
- * AdShift SDK main interface.
754
+ * Whether a failed start rules out the calls waiting for it.
106
755
  *
107
- * Provides type-safe access to all SDK functionality.
756
+ * A rejected key, an excluded device and a missing configuration cannot be
757
+ * fixed by trying again, so the waiting calls are answered. Anything else can
758
+ * be, and holding the calls is worth more than answering them quickly: the
759
+ * data survives until the app starts the SDK again.
108
760
  */
761
+ function isTerminalStartFailure(code: AdshiftErrorCode): boolean {
762
+ return (
763
+ code === AdshiftErrorCode.InvalidApiKey ||
764
+ code === AdshiftErrorCode.OptedOut ||
765
+ code === AdshiftErrorCode.NotInitialized
766
+ );
767
+ }
768
+
769
+ // ============ Main SDK API ============
770
+
109
771
  export const Adshift = {
110
772
  // ============ Lifecycle ============
111
773
 
112
774
  /**
113
- * Initializes the SDK with configuration.
114
- *
115
- * Must be called before any other SDK methods.
116
- * Call this early in your app's lifecycle (e.g., in App.tsx or index.js).
775
+ * Initializes the SDK.
117
776
  *
118
- * @param config - SDK configuration
777
+ * Call once, as early as possible (e.g. at module scope of `App.tsx`).
778
+ * The configuration is fixed on the first call; later calls are ignored.
119
779
  *
120
- * @example
121
- * ```typescript
122
- * Adshift.initialize({
123
- * apiKey: 'your-api-key',
124
- * isDebug: __DEV__,
125
- * // iOS only
126
- * waitForATTBeforeStart: true,
127
- * // Android only
128
- * collectOaid: true,
129
- * });
130
- * ```
780
+ * Never raises, because it is meant to run at module scope, where an error
781
+ * would stop the bundle from evaluating. An unusable config is reported
782
+ * through `config.onError` and answered by `start()`.
131
783
  */
132
784
  initialize(config: AdshiftConfig): void {
133
- if (!config.apiKey) {
134
- throw new Error('AdShift SDK: apiKey is required in config');
785
+ if (state !== 'uninitialized') {
786
+ devWarn('initialize() called more than once; the first config is kept.');
787
+ return;
135
788
  }
789
+ errorHandler =
790
+ isPlainObject(config) && typeof config.onError === 'function'
791
+ ? config.onError
792
+ : null;
136
793
 
137
- const configMap = configToMap(config);
138
- NativeAdShiftReactNativePlugin.initialize(configMap);
139
- _isInitialized = true;
794
+ const refuse = (message: string): void => {
795
+ configError = invalidArgument(message);
796
+ reportDeclined(configError);
797
+ };
798
+ if (!isPlainObject(config) || !isNonEmptyString(config.apiKey)) {
799
+ refuse('AdShift SDK: apiKey is required in config');
800
+ return;
801
+ }
802
+ if (
803
+ config.brandedDomains !== undefined &&
804
+ !isStringArray(config.brandedDomains)
805
+ ) {
806
+ refuse(
807
+ 'AdShift SDK: brandedDomains must be an array of non-empty strings'
808
+ );
809
+ return;
810
+ }
811
+ if (
812
+ config.pushDeepLinkPaths !== undefined &&
813
+ !(
814
+ Array.isArray(config.pushDeepLinkPaths) &&
815
+ config.pushDeepLinkPaths.every(isStringArray)
816
+ )
817
+ ) {
818
+ refuse(
819
+ 'AdShift SDK: pushDeepLinkPaths must be an array of string arrays'
820
+ );
821
+ return;
822
+ }
823
+
824
+ configError = null;
825
+ frozenConfig = Object.freeze(withPendingSettings(config));
826
+ try {
827
+ ensureNativeSubscription();
828
+ NativeAdShiftReactNativePlugin.initialize(configToMap(frozenConfig));
829
+ state = 'initialized';
830
+ applyPendingSettings();
831
+ } catch (error) {
832
+ configError = toAdshiftError(error);
833
+ state = 'uninitialized';
834
+ frozenConfig = null;
835
+ reportDeclined(configError);
836
+ return;
837
+ }
838
+
839
+ if (autoForwardEnabled()) {
840
+ startLinkingAutoForward();
841
+ }
140
842
  },
141
843
 
142
844
  /**
143
845
  * Starts the SDK.
144
846
  *
145
- * Validates API key, sends install event (if first launch), and begins tracking.
146
- * Call this after initialize().
147
- *
148
- * @returns Promise resolving to start result
149
- *
150
- * @example
151
- * ```typescript
152
- * try {
153
- * const result = await Adshift.start();
154
- * console.log('SDK started:', result);
155
- * } catch (error) {
156
- * console.error('SDK start failed:', error);
157
- * }
158
- * ```
847
+ * Resolves once the SDK has started locally. Never rejects; inspect
848
+ * `result.success` and `result.errorCode`. Calls to `trackEvent`,
849
+ * `trackPurchase` and `logAdRevenue` made before this resolves are queued
850
+ * and dispatched afterwards. A start that fails with a reason retrying
851
+ * cannot fix rejects them instead; any other failure keeps them waiting for
852
+ * the next attempt.
159
853
  */
160
- async start(): Promise<StartResult> {
161
- ensureInitialized();
162
-
163
- try {
164
- const result = (await NativeAdShiftReactNativePlugin.start()) as Record<
165
- string,
166
- unknown
167
- >;
168
- return {
169
- success: true,
170
- message: result?.message as string | undefined,
171
- };
172
- } catch (error) {
173
- const message = error instanceof Error ? error.message : 'Unknown error';
174
- return {
854
+ start(): Promise<StartResult> {
855
+ if (state === 'uninitialized') {
856
+ const error = configError ?? notInitializedError();
857
+ return Promise.resolve({
175
858
  success: false,
176
- message,
177
- };
859
+ errorCode: error.code,
860
+ errorMessage: error.message,
861
+ });
862
+ }
863
+ if (state === 'started') {
864
+ return Promise.resolve({ success: true });
178
865
  }
866
+ if (startInFlight) {
867
+ return startInFlight;
868
+ }
869
+ const attempt = performStart().finally(() => {
870
+ if (startInFlight === attempt) {
871
+ startInFlight = null;
872
+ }
873
+ });
874
+ startInFlight = attempt;
875
+ return attempt;
179
876
  },
180
877
 
181
878
  /**
182
- * Stops the SDK.
879
+ * Stops the SDK. Tracking calls reject with `NOT_STARTED` until the next
880
+ * successful `start()`.
183
881
  *
184
- * Pauses all tracking. Can be restarted with start().
185
- *
186
- * @example
187
- * ```typescript
188
- * Adshift.stop();
189
- * ```
882
+ * Before `initialize()` there is nothing to stop: the call is reported and
883
+ * skipped.
190
884
  */
191
885
  stop(): void {
192
- ensureInitialized();
886
+ if (state === 'uninitialized') {
887
+ reportDeclined(notInitializedError());
888
+ return;
889
+ }
890
+ state = 'stopped';
891
+ // A later start() must not receive the promise of the attempt this stop cancels.
892
+ startInFlight = null;
893
+ rejectPendingCalls(notStartedError());
193
894
  NativeAdShiftReactNativePlugin.stop();
194
895
  },
195
896
 
196
897
  /**
197
- * Checks if SDK is currently started.
198
- *
199
- * @returns true if SDK is running
200
- *
201
- * @example
202
- * ```typescript
203
- * if (Adshift.isStarted()) {
204
- * // SDK is tracking
205
- * }
206
- * ```
898
+ * Whether `start()` has completed successfully and `stop()` has not been
899
+ * called since. Safe to call before `initialize()`.
207
900
  */
208
901
  isStarted(): boolean {
209
- ensureInitialized();
210
- return NativeAdShiftReactNativePlugin.isStarted();
902
+ return state === 'started';
211
903
  },
212
904
 
213
905
  // ============ Configuration ============
214
906
 
215
907
  /**
216
- * Sets custom user identifier for attribution.
217
- *
218
- * Associate events with your own user ID. Can be called before or after start().
219
- *
220
- * @param userId - Your user identifier
908
+ * Sets your own user identifier. Can be called before or after `start()`.
221
909
  *
222
- * @example
223
- * ```typescript
224
- * Adshift.setCustomerUserId('user_123');
225
- * ```
910
+ * Called before `initialize()`, the value is kept and applied afterwards.
911
+ * An empty identifier is reported and skipped; nothing is raised.
226
912
  */
227
913
  setCustomerUserId(userId: string): void {
228
- ensureInitialized();
229
-
230
- if (!userId || typeof userId !== 'string') {
231
- throw new Error('AdShift SDK: userId must be a non-empty string');
914
+ if (!isNonEmptyString(userId)) {
915
+ reportDeclined(
916
+ invalidArgument('AdShift SDK: userId must be a non-empty string')
917
+ );
918
+ return;
919
+ }
920
+ if (state === 'uninitialized') {
921
+ pendingSettings.customerUserId = userId;
922
+ return;
232
923
  }
233
-
234
924
  NativeAdShiftReactNativePlugin.setCustomerUserId(userId);
235
925
  },
236
926
 
237
927
  /**
238
- * Enables/disables debug logging at runtime.
239
- *
240
- * Note: Can also be set via config.isDebug during initialize().
241
- *
242
- * @param enabled - true to enable debug logs
928
+ * Enables or disables verbose SDK logging at runtime.
243
929
  *
244
- * @example
245
- * ```typescript
246
- * // Enable debug in production for troubleshooting
247
- * Adshift.setDebugEnabled(true);
248
- * ```
930
+ * Called before `initialize()`, the value is kept and applied afterwards.
249
931
  */
250
932
  setDebugEnabled(enabled: boolean): void {
251
- ensureInitialized();
252
- NativeAdShiftReactNativePlugin.setDebugEnabled(enabled);
933
+ if (state === 'uninitialized') {
934
+ pendingSettings.debugEnabled = enabled === true;
935
+ return;
936
+ }
937
+ NativeAdShiftReactNativePlugin.setDebugEnabled(enabled === true);
253
938
  },
254
939
 
255
940
  /**
256
- * Sets app open debounce time in milliseconds.
257
- *
258
- * Used to deduplicate rapid app open events.
259
- * Note: Can also be set via config.appOpenDebounceMs during initialize().
260
- *
261
- * @param ms - Debounce time in milliseconds (e.g., 5000 for 5 seconds)
941
+ * Sets the debounce interval for automatic `app_open` events.
262
942
  *
263
- * @example
264
- * ```typescript
265
- * Adshift.setAppOpenDebounceMs(5000);
266
- * ```
943
+ * Called before `initialize()`, the value is kept and applied afterwards.
944
+ * A negative interval is reported and skipped; nothing is raised.
267
945
  */
268
946
  setAppOpenDebounceMs(ms: number): void {
269
- ensureInitialized();
947
+ if (!isFiniteNumber(ms) || ms < 0) {
948
+ reportDeclined(
949
+ invalidArgument('AdShift SDK: ms must be a non-negative number')
950
+ );
951
+ return;
952
+ }
953
+ if (state === 'uninitialized') {
954
+ pendingSettings.appOpenDebounceMs = ms;
955
+ return;
956
+ }
957
+ NativeAdShiftReactNativePlugin.setAppOpenDebounceMs(ms);
958
+ },
959
+
960
+ /**
961
+ * Sets branded attribution domains. Must be called before `start()`.
962
+ *
963
+ * Called before `initialize()`, the domains are kept and applied with the
964
+ * config, so they are in place before the first link is processed.
965
+ */
966
+ setBrandedDomains(domains: string[]): void {
967
+ if (!isStringArray(domains)) {
968
+ reportDeclined(
969
+ invalidArgument(
970
+ 'AdShift SDK: domains must be an array of non-empty strings'
971
+ )
972
+ );
973
+ return;
974
+ }
975
+ if (state === 'uninitialized') {
976
+ pendingSettings.brandedDomains = [...domains];
977
+ return;
978
+ }
979
+ NativeAdShiftReactNativePlugin.setBrandedDomains(domains);
980
+ },
270
981
 
271
- if (typeof ms !== 'number' || ms < 0) {
272
- throw new Error('AdShift SDK: ms must be a non-negative number');
982
+ /**
983
+ * Sets the Meta app id used to parse Meta App Links. No-op on iOS.
984
+ *
985
+ * Called before `initialize()`, the value is kept and applied afterwards.
986
+ */
987
+ setMetaAppId(appId: string): void {
988
+ if (!isNonEmptyString(appId)) {
989
+ reportDeclined(
990
+ invalidArgument('AdShift SDK: appId must be a non-empty string')
991
+ );
992
+ return;
273
993
  }
994
+ if (state === 'uninitialized') {
995
+ pendingSettings.metaAppId = appId;
996
+ return;
997
+ }
998
+ NativeAdShiftReactNativePlugin.setMetaAppId(appId);
999
+ },
274
1000
 
275
- NativeAdShiftReactNativePlugin.setAppOpenDebounceMs(ms);
1001
+ /**
1002
+ * Hands over an OAID the app obtained itself, for Android devices without
1003
+ * Google Play services. Set `collectOaid: false` when you supply it this
1004
+ * way. No-op on iOS.
1005
+ *
1006
+ * Called before `initialize()`, the value is kept and applied afterwards.
1007
+ */
1008
+ setOaidData(oaid: string): void {
1009
+ if (!isNonEmptyString(oaid)) {
1010
+ reportDeclined(
1011
+ invalidArgument('AdShift SDK: oaid must be a non-empty string')
1012
+ );
1013
+ return;
1014
+ }
1015
+ if (state === 'uninitialized') {
1016
+ pendingSettings.oaid = oaid;
1017
+ return;
1018
+ }
1019
+ NativeAdShiftReactNativePlugin.setOaidData(oaid);
276
1020
  },
277
1021
 
278
1022
  // ============ Consent (GDPR/DMA) ============
279
1023
 
280
1024
  /**
281
- * Sets user consent data manually.
1025
+ * Sets consent collected by your own UI. Use `AdshiftConsent.forGDPRUser()`
1026
+ * or `AdshiftConsent.forNonGDPRUser()`.
282
1027
  *
283
- * Use this for manual consent collection (not CMP).
284
- * Use AdshiftConsent.forGDPRUser() or AdshiftConsent.forNonGDPRUser() helpers.
1028
+ * Called before `initialize()`, the consent is kept and applied afterwards.
1029
+ */
1030
+ setConsentData(consent: AdshiftConsent): void {
1031
+ if (
1032
+ !isPlainObject(consent) ||
1033
+ typeof consent.isUserSubjectToGDPR !== 'boolean'
1034
+ ) {
1035
+ reportDeclined(
1036
+ invalidArgument(
1037
+ 'AdShift SDK: consent.isUserSubjectToGDPR must be a boolean'
1038
+ )
1039
+ );
1040
+ return;
1041
+ }
1042
+ if (state === 'uninitialized') {
1043
+ pendingSettings.consent = consent;
1044
+ return;
1045
+ }
1046
+ NativeAdShiftReactNativePlugin.setConsentData(consentToMap(consent));
1047
+ },
1048
+
1049
+ /**
1050
+ * Enables or disables reading IAB TCF v2.2 consent from the CMP on device.
1051
+ * Call before `start()`.
285
1052
  *
286
- * @param consent - Consent data
1053
+ * Called before `initialize()`, the value is kept and applied afterwards.
1054
+ */
1055
+ enableTCFDataCollection(enabled: boolean): void {
1056
+ if (state === 'uninitialized') {
1057
+ pendingSettings.tcfEnabled = enabled === true;
1058
+ return;
1059
+ }
1060
+ NativeAdShiftReactNativePlugin.enableTCFDataCollection(enabled === true);
1061
+ },
1062
+
1063
+ /**
1064
+ * Enables reading an IAB GPP string written by the CMP on device, used for US
1065
+ * state privacy signals. Off until called with `true`.
287
1066
  *
288
- * @example
289
- * ```typescript
290
- * // GDPR user who accepted all
291
- * Adshift.setConsentData(
292
- * AdshiftConsent.forGDPRUser({
293
- * hasConsentForDataUsage: true,
294
- * hasConsentForAdsPersonalization: true,
295
- * hasConsentForAdStorage: true,
296
- * })
297
- * );
1067
+ * The GPP string rides on its own axis: it is forwarded alongside whatever
1068
+ * decides the GDPR axis, including a consent set through `setConsentData()`,
1069
+ * and it does not gate the advertising identifier on the device.
298
1070
  *
299
- * // Non-GDPR user
300
- * Adshift.setConsentData(AdshiftConsent.forNonGDPRUser());
301
- * ```
1071
+ * Call before `start()`. Called before `initialize()`, the value is kept and
1072
+ * applied afterwards.
302
1073
  */
303
- setConsentData(consent: AdshiftConsent): void {
304
- ensureInitialized();
305
- const consentMap = consentToMap(consent);
306
- NativeAdShiftReactNativePlugin.setConsentData(consentMap);
1074
+ enableGPPDataCollection(enabled: boolean): void {
1075
+ if (state === 'uninitialized') {
1076
+ pendingSettings.gppEnabled = enabled === true;
1077
+ return;
1078
+ }
1079
+ NativeAdShiftReactNativePlugin.enableGPPDataCollection(enabled === true);
307
1080
  },
308
1081
 
309
1082
  /**
310
- * Enables/disables automatic TCF v2.2 data collection from CMP.
311
- *
312
- * When enabled, SDK reads IAB TCF consent strings from device storage
313
- * (set by CMPs like Google Funding Choices, Didomi, etc.)
1083
+ * States what the app collected about passing this user's data on to
1084
+ * advertising partners. Use `AdshiftThirdPartySharing.optedOut()` or
1085
+ * `AdshiftThirdPartySharing.allowed()`.
314
1086
  *
315
- * Call this BEFORE start().
1087
+ * This is the answer to a different question than `setConsentData()`, and it
1088
+ * has the opposite default: nothing said here means sharing is allowed, so
1089
+ * only call it once the user has actually been asked. Setting `allowed()` at
1090
+ * startup as a default records a declaration the user never made, and events
1091
+ * already sent cannot be recalled when a real answer arrives.
316
1092
  *
317
- * @param enabled - true to enable TCF collection
1093
+ * Nothing is gated on the device either way — this travels with the events for
1094
+ * the backend to act on.
318
1095
  *
319
- * @example
320
- * ```typescript
321
- * Adshift.enableTCFDataCollection(true);
322
- * await Adshift.start();
323
- * ```
1096
+ * Called before `initialize()`, the answer is kept and applied afterwards.
324
1097
  */
325
- enableTCFDataCollection(enabled: boolean): void {
326
- ensureInitialized();
327
- NativeAdShiftReactNativePlugin.enableTCFDataCollection(enabled);
1098
+ setThirdPartySharing(sharing: AdshiftThirdPartySharing): void {
1099
+ if (!isPlainObject(sharing) || typeof sharing.optOut !== 'boolean') {
1100
+ reportDeclined(
1101
+ invalidArgument('AdShift SDK: sharing.optOut must be a boolean')
1102
+ );
1103
+ return;
1104
+ }
1105
+ if (state === 'uninitialized') {
1106
+ pendingSettings.thirdPartySharing = sharing;
1107
+ return;
1108
+ }
1109
+ NativeAdShiftReactNativePlugin.setThirdPartySharing(
1110
+ thirdPartySharingToMap(sharing)
1111
+ );
328
1112
  },
329
1113
 
330
1114
  /**
331
- * Refreshes consent state from TCF/CMP or manual sources.
1115
+ * Withdraws the answer set by `setThirdPartySharing()`.
332
1116
  *
333
- * Call this after CMP dialog closes to pick up updated consent.
334
- * Priority: Manual > TCF > None
1117
+ * Subsequent events state nothing on this axis, which is not the same as
1118
+ * stating that sharing is allowed: the first leaves the decision to your
1119
+ * dashboard configuration, the second is the app's own declaration and is
1120
+ * recorded as such.
335
1121
  *
336
- * @returns Promise resolving to consent snapshot
1122
+ * Called before `initialize()`, this cancels a `setThirdPartySharing()` that
1123
+ * was also queued.
1124
+ */
1125
+ clearThirdPartySharing(): void {
1126
+ if (state === 'uninitialized') {
1127
+ pendingSettings.thirdPartySharing = null;
1128
+ return;
1129
+ }
1130
+ NativeAdShiftReactNativePlugin.clearThirdPartySharing();
1131
+ },
1132
+
1133
+ /**
1134
+ * Re-reads consent from the CMP or manual source and returns the snapshot.
1135
+ * Call after the CMP dialog closes.
337
1136
  *
338
- * @example
339
- * ```typescript
340
- * // After CMP dialog closes
341
- * const snapshot = await Adshift.refreshConsent();
342
- * console.log('Consent source:', snapshot.source);
343
- * ```
1137
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`).
344
1138
  */
345
- async refreshConsent(): Promise<Record<string, unknown>> {
346
- ensureInitialized();
347
- const result =
348
- (await NativeAdShiftReactNativePlugin.refreshConsent()) as Record<
349
- string,
350
- unknown
351
- >;
352
- return result;
1139
+ async refreshConsent(): Promise<ConsentSnapshot> {
1140
+ if (state === 'uninitialized') {
1141
+ throw notInitializedError();
1142
+ }
1143
+ try {
1144
+ const raw = await NativeAdShiftReactNativePlugin.refreshConsent();
1145
+ return consentSnapshotFromMap(isPlainObject(raw) ? raw : {});
1146
+ } catch (error) {
1147
+ throw toAdshiftError(error);
1148
+ }
353
1149
  },
354
1150
 
355
1151
  // ============ Event Tracking ============
@@ -357,183 +1153,321 @@ export const Adshift = {
357
1153
  /**
358
1154
  * Tracks an in-app event.
359
1155
  *
360
- * Use AdshiftEventType constants for predefined events, or custom strings.
361
- * Events are queued until SDK is started.
362
- *
363
- * @param eventName - Event name (use AdshiftEventType or custom string)
364
- * @param values - Optional event parameters
365
- * @returns Promise resolving on success
1156
+ * `app_install` and `app_open` are reserved: the SDK sends them itself and
1157
+ * passing them here rejects with `INVALID_ARGUMENT`.
366
1158
  *
367
- * @example
368
- * ```typescript
369
- * // Predefined event
370
- * await Adshift.trackEvent(AdshiftEventType.AddToCart, {
371
- * product_id: 'SKU123',
372
- * price: 29.99,
373
- * });
1159
+ * Resolves once the SDK has accepted the event. A call made between
1160
+ * `initialize()` and a successful `start()` waits for the start: it is sent
1161
+ * when the SDK starts, and rejects when the start fails for a reason
1162
+ * retrying cannot fix (rejected key, excluded device) or after `stop()`.
1163
+ * A start that failed for any other reason keeps the call waiting for the
1164
+ * next attempt, so `start()` belongs on every launch path.
374
1165
  *
375
- * // Custom event
376
- * await Adshift.trackEvent('custom_event', { key: 'value' });
377
- * ```
1166
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`, `NOT_STARTED`,
1167
+ * `INVALID_API_KEY`, `OPTED_OUT`, `QUEUE_FULL`, `INVALID_ARGUMENT`).
378
1168
  */
379
- async trackEvent(eventName: string, values?: EventValues): Promise<void> {
380
- ensureInitialized();
381
-
382
- if (!eventName || typeof eventName !== 'string') {
383
- throw new Error('AdShift SDK: eventName must be a non-empty string');
1169
+ trackEvent(
1170
+ eventName: AdshiftEventTypeValue | (string & {}),
1171
+ values?: EventValues
1172
+ ): Promise<void> {
1173
+ if (!isNonEmptyString(eventName)) {
1174
+ return Promise.reject(
1175
+ invalidArgument('AdShift SDK: eventName must be a non-empty string')
1176
+ );
384
1177
  }
385
-
386
- await NativeAdShiftReactNativePlugin.trackEvent(eventName, values ?? null);
1178
+ if (RESERVED_EVENT_NAMES.has(eventName.trim().toLowerCase())) {
1179
+ return Promise.reject(
1180
+ invalidArgument(
1181
+ `AdShift SDK: "${eventName}" is reserved and sent by the SDK; use your own event name`
1182
+ )
1183
+ );
1184
+ }
1185
+ try {
1186
+ validateEventValues(values, 'values');
1187
+ } catch (error) {
1188
+ return Promise.reject(error);
1189
+ }
1190
+ warnAboutPlainParamNames(values);
1191
+ return runWhenStarted(() =>
1192
+ NativeAdShiftReactNativePlugin.trackEvent(eventName, values ?? null)
1193
+ );
387
1194
  },
388
1195
 
389
1196
  /**
390
- * Tracks a purchase event.
391
- *
392
- * Use for revenue tracking and SKAdNetwork conversion value calculation.
393
- *
394
- * @param params - Purchase parameters
395
- * @returns Promise resolving on success
1197
+ * Tracks a purchase.
396
1198
  *
397
- * @example
398
- * ```typescript
399
- * await Adshift.trackPurchase({
400
- * productId: 'premium_subscription',
401
- * revenue: 9.99,
402
- * currency: 'USD',
403
- * transactionId: 'TXN_123456',
404
- * });
405
- * ```
1199
+ * @returns Rejects with `AdshiftError` (see `trackEvent`).
406
1200
  */
407
- async trackPurchase(params: PurchaseParams): Promise<void> {
408
- ensureInitialized();
409
-
1201
+ trackPurchase(params: PurchaseParams): Promise<void> {
1202
+ if (!isPlainObject(params)) {
1203
+ return Promise.reject(
1204
+ invalidArgument('AdShift SDK: params must be an object')
1205
+ );
1206
+ }
410
1207
  const { productId, revenue, currency, transactionId } = params;
411
-
412
- if (!productId) {
413
- throw new Error('AdShift SDK: productId is required');
1208
+ if (!isNonEmptyString(productId)) {
1209
+ return Promise.reject(
1210
+ invalidArgument('AdShift SDK: productId is required')
1211
+ );
414
1212
  }
415
- if (typeof revenue !== 'number' || revenue < 0) {
416
- throw new Error('AdShift SDK: revenue must be a non-negative number');
1213
+ if (!isFiniteNumber(revenue) || revenue < 0) {
1214
+ return Promise.reject(
1215
+ invalidArgument('AdShift SDK: revenue must be a non-negative number')
1216
+ );
417
1217
  }
418
- if (!currency) {
419
- throw new Error('AdShift SDK: currency is required');
1218
+ if (!isNonEmptyString(currency)) {
1219
+ return Promise.reject(
1220
+ invalidArgument('AdShift SDK: currency is required')
1221
+ );
420
1222
  }
421
- if (!transactionId) {
422
- throw new Error('AdShift SDK: transactionId is required');
1223
+ if (!isNonEmptyString(transactionId)) {
1224
+ return Promise.reject(
1225
+ invalidArgument('AdShift SDK: transactionId is required')
1226
+ );
423
1227
  }
1228
+ return runWhenStarted(() =>
1229
+ NativeAdShiftReactNativePlugin.trackPurchase(
1230
+ productId,
1231
+ revenue,
1232
+ currency,
1233
+ transactionId
1234
+ )
1235
+ );
1236
+ },
424
1237
 
425
- // Native SDK uses price/token naming internally
426
- await NativeAdShiftReactNativePlugin.trackPurchase(
427
- productId,
1238
+ /**
1239
+ * Logs ad revenue for a single impression.
1240
+ *
1241
+ * @returns Rejects with `AdshiftError` (see `trackEvent`).
1242
+ */
1243
+ logAdRevenue(params: AdRevenueParams): Promise<void> {
1244
+ if (!isPlainObject(params)) {
1245
+ return Promise.reject(
1246
+ invalidArgument('AdShift SDK: params must be an object')
1247
+ );
1248
+ }
1249
+ const {
1250
+ monetizationNetwork,
1251
+ mediationNetwork,
1252
+ currency,
428
1253
  revenue,
1254
+ adUnitId,
1255
+ precision,
1256
+ additionalParameters,
1257
+ } = params;
1258
+ if (!isNonEmptyString(monetizationNetwork)) {
1259
+ return Promise.reject(
1260
+ invalidArgument('AdShift SDK: monetizationNetwork is required')
1261
+ );
1262
+ }
1263
+ if (
1264
+ !isNonEmptyString(mediationNetwork) ||
1265
+ !MEDIATION_NETWORKS.has(mediationNetwork)
1266
+ ) {
1267
+ return Promise.reject(
1268
+ invalidArgument(
1269
+ 'AdShift SDK: mediationNetwork must be an AdshiftMediationNetwork value'
1270
+ )
1271
+ );
1272
+ }
1273
+ if (!isNonEmptyString(currency)) {
1274
+ return Promise.reject(
1275
+ invalidArgument('AdShift SDK: currency is required')
1276
+ );
1277
+ }
1278
+ if (currency.length !== 3) {
1279
+ return Promise.reject(
1280
+ invalidArgument(
1281
+ 'AdShift SDK: currency must be a 3-letter ISO 4217 code'
1282
+ )
1283
+ );
1284
+ }
1285
+ if (!isFiniteNumber(revenue) || revenue <= 0) {
1286
+ return Promise.reject(
1287
+ invalidArgument('AdShift SDK: revenue must be a positive number')
1288
+ );
1289
+ }
1290
+ if (revenue > MAX_AD_REVENUE_PER_IMPRESSION) {
1291
+ devWarn(
1292
+ `logAdRevenue: revenue above ${MAX_AD_REVENUE_PER_IMPRESSION} is not recorded. ` +
1293
+ 'Pass the revenue of a single impression, not an aggregate.'
1294
+ );
1295
+ }
1296
+ if (adUnitId !== undefined && typeof adUnitId !== 'string') {
1297
+ return Promise.reject(
1298
+ invalidArgument('AdShift SDK: adUnitId must be a string')
1299
+ );
1300
+ }
1301
+ if (precision !== undefined && typeof precision !== 'string') {
1302
+ return Promise.reject(
1303
+ invalidArgument('AdShift SDK: precision must be a string')
1304
+ );
1305
+ }
1306
+ try {
1307
+ validateEventValues(additionalParameters, 'additionalParameters');
1308
+ } catch (error) {
1309
+ return Promise.reject(error);
1310
+ }
1311
+ warnAboutPlainParamNames(additionalParameters);
1312
+ const data: Record<string, unknown> = {
1313
+ monetizationNetwork,
1314
+ mediationNetwork,
429
1315
  currency,
430
- transactionId
1316
+ revenue,
1317
+ };
1318
+ if (adUnitId !== undefined) data.adUnitId = adUnitId;
1319
+ if (precision !== undefined) data.precision = precision;
1320
+ if (additionalParameters !== undefined) {
1321
+ data.additionalParameters = additionalParameters;
1322
+ }
1323
+ return runWhenStarted(() =>
1324
+ NativeAdShiftReactNativePlugin.logAdRevenue(data)
431
1325
  );
432
1326
  },
433
1327
 
1328
+ // ============ Identity ============
1329
+
1330
+ /**
1331
+ * Returns the AdShift device id, or `null` before `initialize()`.
1332
+ */
1333
+ async getAdShiftDeviceId(): Promise<string | null> {
1334
+ if (state === 'uninitialized') {
1335
+ return null;
1336
+ }
1337
+ try {
1338
+ const value = await NativeAdShiftReactNativePlugin.getAdShiftDeviceId();
1339
+ return typeof value === 'string' && value.length > 0 ? value : null;
1340
+ } catch (error) {
1341
+ throw toAdshiftError(error);
1342
+ }
1343
+ },
1344
+
434
1345
  // ============ Deep Links ============
435
1346
 
436
1347
  /**
437
- * Handles a deep link URL.
438
- *
439
- * Call this when your app receives a deep link (e.g., from Linking API).
440
- * Extracts campaign parameters for attribution.
441
- *
442
- * @param url - Deep link URL string
443
- * @returns Promise resolving to deep link response
1348
+ * Passes a URL to the SDK.
444
1349
  *
445
- * @example
446
- * ```typescript
447
- * import { Linking } from 'react-native';
1350
+ * Not needed when `autoHandleDeepLinks` is on (the default). The result is
1351
+ * delivered through `onDeepLink()`; the promise resolves once the SDK has
1352
+ * finished processing the URL.
448
1353
  *
449
- * Linking.addEventListener('url', async ({ url }) => {
450
- * const deepLink = await Adshift.handleDeepLink(url);
451
- * if (deepLink.status === AdshiftDeepLinkStatus.Found) {
452
- * // Navigate based on deepLink.params
453
- * }
454
- * });
455
- * ```
1354
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`,
1355
+ * `INVALID_ARGUMENT`).
456
1356
  */
457
- async handleDeepLink(url: string): Promise<AdshiftDeepLink> {
458
- ensureInitialized();
459
-
460
- if (!url || typeof url !== 'string') {
461
- return AdshiftDeepLinkHelpers.error('Invalid URL');
1357
+ async handleDeepLink(url: string): Promise<void> {
1358
+ if (state === 'uninitialized') {
1359
+ throw notInitializedError();
462
1360
  }
463
-
1361
+ if (!isNonEmptyString(url)) {
1362
+ throw invalidArgument('AdShift SDK: url must be a non-empty string');
1363
+ }
1364
+ if (wasAutoForwardedRecently(url)) {
1365
+ return;
1366
+ }
1367
+ // Recorded here as well, so automatic forwarding does not repeat a URL the
1368
+ // app passed in first.
1369
+ pruneAutoForwarded();
1370
+ autoForwarded.set(url, Date.now());
464
1371
  try {
465
- const result = (await NativeAdShiftReactNativePlugin.handleDeepLink(
466
- url
467
- )) as Record<string, unknown>;
468
- return AdshiftDeepLinkHelpers.fromMap(result);
1372
+ await NativeAdShiftReactNativePlugin.handleDeepLink(url, false);
469
1373
  } catch (error) {
470
- const message = error instanceof Error ? error.message : 'Unknown error';
471
- return AdshiftDeepLinkHelpers.error(message);
1374
+ const mapped = toAdshiftError(error);
1375
+ if (mapped.code === AdshiftErrorCode.OptedOut) {
1376
+ return;
1377
+ }
1378
+ throw mapped;
472
1379
  }
473
1380
  },
474
1381
 
475
1382
  /**
476
- * Registers a listener for deep link events.
477
- *
478
- * Called when:
479
- * - Deferred deep links are resolved (after first install)
480
- * - App links are received while app is running
1383
+ * Adds a key path inside push payloads that carries an AdShift deep link.
481
1384
  *
482
- * If a deep link was received before listener was set (cold start),
483
- * the callback is called immediately with the cached deep link.
484
- *
485
- * @param callback - Function called when deep link is received
486
- * @returns Subscription object with remove() method
1385
+ * Called before `initialize()`, the path is kept and registered afterwards.
1386
+ * The first path you register takes over from the top-level `as_push_link`
1387
+ * the SDK reads on its own, so register that key too if you still need it.
1388
+ */
1389
+ addPushNotificationDeepLinkPath(path: string[]): void {
1390
+ if (!isStringArray(path) || path.length === 0) {
1391
+ reportDeclined(
1392
+ invalidArgument(
1393
+ 'AdShift SDK: path must be a non-empty array of strings'
1394
+ )
1395
+ );
1396
+ return;
1397
+ }
1398
+ if (state === 'uninitialized') {
1399
+ pendingSettings.pushDeepLinkPaths.push([...path]);
1400
+ return;
1401
+ }
1402
+ NativeAdShiftReactNativePlugin.addPushNotificationDeepLinkPath(path);
1403
+ },
1404
+
1405
+ /**
1406
+ * Passes a push notification payload to the SDK. Resolves to `true` when
1407
+ * the payload carried an AdShift deep link; the result then arrives
1408
+ * through `onDeepLink()`.
487
1409
  *
488
- * @example
489
- * ```typescript
490
- * useEffect(() => {
491
- * const subscription = Adshift.onDeepLink((deepLink) => {
492
- * if (deepLink.status === AdshiftDeepLinkStatus.Found) {
493
- * console.log('Deep link:', deepLink.deepLink);
494
- * console.log('Params:', deepLink.params);
495
- * // Navigate to appropriate screen
496
- * }
497
- * });
1410
+ * @returns Rejects with `AdshiftError` (`NOT_INITIALIZED`,
1411
+ * `INVALID_ARGUMENT`).
1412
+ */
1413
+ async handlePushNotification(
1414
+ payload: Record<string, unknown>
1415
+ ): Promise<boolean> {
1416
+ if (state === 'uninitialized') {
1417
+ throw notInitializedError();
1418
+ }
1419
+ if (!isPlainObject(payload)) {
1420
+ throw invalidArgument('AdShift SDK: payload must be an object');
1421
+ }
1422
+ try {
1423
+ return (
1424
+ (await NativeAdShiftReactNativePlugin.handlePushNotification(
1425
+ payload
1426
+ )) === true
1427
+ );
1428
+ } catch (error) {
1429
+ throw toAdshiftError(error);
1430
+ }
1431
+ },
1432
+
1433
+ /**
1434
+ * Registers a deep link listener.
498
1435
  *
499
- * return () => subscription.remove();
500
- * }, []);
501
- * ```
1436
+ * Safe to call before `initialize()`. Results that arrive while no
1437
+ * listener is registered are buffered and delivered to the first listener.
1438
+ * Every link that reaches the SDK (direct, deferred, push) is delivered.
502
1439
  */
503
1440
  onDeepLink(callback: DeepLinkCallback): DeepLinkSubscription {
504
- ensureInitialized();
505
-
506
- const eventEmitter = getEventEmitter();
507
-
508
- const subscription = eventEmitter.addListener(
509
- 'onDeepLink',
510
- (event: unknown) => {
511
- const deepLink = AdshiftDeepLinkHelpers.fromMap(
512
- event as Record<string, unknown>
513
- );
514
- callback(deepLink);
515
- }
516
- );
517
-
1441
+ if (typeof callback !== 'function') {
1442
+ reportDeclined(
1443
+ invalidArgument('AdShift SDK: callback must be a function')
1444
+ );
1445
+ return { remove: () => {} };
1446
+ }
1447
+ const entry: ListenerEntry = { callback };
1448
+ const wasEmpty = listeners.size === 0;
1449
+ listeners.add(entry);
1450
+ if (wasEmpty && deepLinkBuffer.length > 0) {
1451
+ scheduleReplay();
1452
+ }
518
1453
  return {
519
1454
  remove: () => {
520
- subscription.remove();
1455
+ listeners.delete(entry);
521
1456
  },
522
1457
  };
523
1458
  },
524
1459
 
525
- // ============ Debug ============
1460
+ // ============ Info ============
526
1461
 
527
- /**
528
- * Returns SDK version and platform info.
529
- * Useful for debugging.
530
- */
531
- getInfo(): { platform: string; version: string } {
1462
+ getInfo(): AdshiftInfo {
532
1463
  return {
533
1464
  platform: Platform.OS,
534
- version: '1.0.0', // TODO: Get from package.json
1465
+ version: PLUGIN_VERSION,
1466
+ nativeSdkVersions: { ...NATIVE_SDK_VERSIONS },
535
1467
  };
536
1468
  },
537
- };
1469
+ } as const;
1470
+
1471
+ Object.freeze(Adshift);
538
1472
 
539
1473
  export default Adshift;