@kerdly/expo 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/android/build.gradle +61 -0
  4. package/android/src/main/AndroidManifest.xml +19 -0
  5. package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
  6. package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
  7. package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
  8. package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
  9. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
  10. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
  11. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
  12. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
  13. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
  14. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
  15. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +110 -0
  16. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
  17. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
  18. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
  19. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
  20. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
  21. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
  22. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
  23. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
  24. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
  25. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
  26. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
  27. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
  28. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
  29. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
  30. package/app.plugin.js +2 -0
  31. package/build/Kerdly.d.ts +106 -0
  32. package/build/Kerdly.d.ts.map +1 -0
  33. package/build/Kerdly.js +494 -0
  34. package/build/Kerdly.js.map +1 -0
  35. package/build/index.d.ts +4 -0
  36. package/build/index.d.ts.map +1 -0
  37. package/build/index.js +2 -0
  38. package/build/index.js.map +1 -0
  39. package/build/log.d.ts +13 -0
  40. package/build/log.d.ts.map +1 -0
  41. package/build/log.js +45 -0
  42. package/build/log.js.map +1 -0
  43. package/build/native.d.ts +74 -0
  44. package/build/native.d.ts.map +1 -0
  45. package/build/native.js +56 -0
  46. package/build/native.js.map +1 -0
  47. package/build/normalize.d.ts +8 -0
  48. package/build/normalize.d.ts.map +1 -0
  49. package/build/normalize.js +86 -0
  50. package/build/normalize.js.map +1 -0
  51. package/build/types.d.ts +134 -0
  52. package/build/types.d.ts.map +1 -0
  53. package/build/types.js +3 -0
  54. package/build/types.js.map +1 -0
  55. package/build/validation.d.ts +70 -0
  56. package/build/validation.d.ts.map +1 -0
  57. package/build/validation.js +349 -0
  58. package/build/validation.js.map +1 -0
  59. package/build/version.d.ts +4 -0
  60. package/build/version.d.ts.map +1 -0
  61. package/build/version.js +5 -0
  62. package/build/version.js.map +1 -0
  63. package/expo-module.config.json +9 -0
  64. package/ios/KerdlySDK/.kerdly-sync.json +7 -0
  65. package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
  66. package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
  67. package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
  68. package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
  69. package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
  70. package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
  71. package/ios/KerdlySDK/Core/Support.swift +95 -0
  72. package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
  73. package/ios/KerdlySDK/Logic/Batch.swift +180 -0
  74. package/ios/KerdlySDK/Logic/Context.swift +85 -0
  75. package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
  76. package/ios/KerdlySDK/Logic/DeferredLinks.swift +236 -0
  77. package/ios/KerdlySDK/Logic/Environment.swift +39 -0
  78. package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
  79. package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
  80. package/ios/KerdlySDK/Logic/Events.swift +102 -0
  81. package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
  82. package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
  83. package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
  84. package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
  85. package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
  86. package/ios/KerdlySDK/Logic/Skan.swift +343 -0
  87. package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
  88. package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
  89. package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
  90. package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
  91. package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
  92. package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
  93. package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
  94. package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
  95. package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
  96. package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
  97. package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
  98. package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
  99. package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +96 -0
  100. package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
  101. package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
  102. package/ios/KerdlySdk.podspec +45 -0
  103. package/ios/KerdlySdkModule.swift +332 -0
  104. package/package.json +96 -4
  105. package/plugin/withKerdly.js +163 -0
  106. package/src/Kerdly.ts +524 -0
  107. package/src/index.ts +23 -0
  108. package/src/log.ts +49 -0
  109. package/src/native.ts +150 -0
  110. package/src/normalize.ts +82 -0
  111. package/src/types.ts +182 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,163 @@
1
+ // @ts-check
2
+ // Expo config plugin for @kerdly/expo. Plain CommonJS on purpose: it needs no build step, so it
3
+ // works straight from a git checkout or a `file:` install. Type-checked by tsc (checkJs).
4
+
5
+ const pkg = require('../package.json');
6
+
7
+ /** @returns {typeof import('@expo/config-plugins')} */
8
+ function loadConfigPlugins() {
9
+ try {
10
+ // The app's own copy, as Expo recommends for plugins. `expo` is not a dev dependency here.
11
+ // @ts-ignore
12
+ return require('expo/config-plugins');
13
+ } catch {
14
+ return require('@expo/config-plugins');
15
+ }
16
+ }
17
+
18
+ const { AndroidConfig, WarningAggregator, createRunOncePlugin, withAndroidManifest, withInfoPlist, withStringsXml } =
19
+ loadConfigPlugins();
20
+
21
+ /** Manifest meta-data the native Android SDK (and this module's bridge) reads when `configure` gets no `metaAppId`. */
22
+ const META_APP_ID_KEY = 'com.kerdly.sdk.META_APP_ID';
23
+
24
+ /**
25
+ * The id goes through a string resource: a literal `android:value="1234567890123456"` is compiled
26
+ * as a number, not a string, and `Bundle.getString` would not return it.
27
+ */
28
+ const META_APP_ID_STRING = 'kerdly_meta_app_id';
29
+ /** The same string as plugin builds before 0.1.0 named it: always removed. */
30
+ const LEGACY_META_APP_ID_STRING = 'afr_meta_app_id';
31
+
32
+ /**
33
+ * @typedef {object} KerdlyPluginProps
34
+ * @property {string} [metaAppId] Android: the Facebook app id, written to the
35
+ * `com.kerdly.sdk.META_APP_ID` manifest meta-data (enables the Meta Install Referrer read).
36
+ * @property {string} [userTrackingPermission] iOS: `NSUserTrackingUsageDescription`, the text of the
37
+ * App Tracking Transparency prompt.
38
+ * @property {string} [skanEndpoint] iOS: `NSAdvertisingAttributionReportEndpoint`, the https origin
39
+ * that receives copies of SKAdNetwork postbacks (e.g. `https://sdk.example.com`).
40
+ */
41
+
42
+ /**
43
+ * @typedef {object} NormalizedProps
44
+ * @property {string | null} metaAppId
45
+ * @property {string | null} userTrackingPermission
46
+ * @property {string | null} skanEndpoint
47
+ */
48
+
49
+ /**
50
+ * @param {unknown} value
51
+ * @param {string} name
52
+ * @returns {string | null}
53
+ */
54
+ function optionalString(value, name) {
55
+ if (value === undefined || value === null) return null;
56
+ if (typeof value === 'string') return value.trim().length > 0 ? value.trim() : null;
57
+ throw new Error(`[@kerdly/expo] plugin option \`${name}\` must be a string, got ${typeof value}`);
58
+ }
59
+
60
+ /**
61
+ * @param {unknown} props
62
+ * @returns {NormalizedProps}
63
+ */
64
+ function normalizeProps(props) {
65
+ if (props === undefined || props === null) {
66
+ return { metaAppId: null, userTrackingPermission: null, skanEndpoint: null };
67
+ }
68
+ if (typeof props !== 'object' || Array.isArray(props)) {
69
+ throw new Error('[@kerdly/expo] plugin options must be an object');
70
+ }
71
+ const raw = /** @type {Record<string, unknown>} */ (props);
72
+ // An app id written as a JSON number is accepted (ids are below 2^53).
73
+ const metaAppIdRaw = typeof raw.metaAppId === 'number' && Number.isSafeInteger(raw.metaAppId) ? String(raw.metaAppId) : raw.metaAppId;
74
+ const metaAppId = optionalString(metaAppIdRaw, 'metaAppId');
75
+ if (metaAppId !== null && !/^\d+$/.test(metaAppId)) {
76
+ WarningAggregator.addWarningAndroid('@kerdly/expo', `metaAppId "${metaAppId}" is not numeric; Facebook app ids are digits only.`);
77
+ }
78
+ const skanEndpoint = optionalString(raw.skanEndpoint, 'skanEndpoint');
79
+ if (skanEndpoint !== null && !/^https:\/\/[^/?#\s]+\/?$/.test(skanEndpoint)) {
80
+ WarningAggregator.addWarningIOS(
81
+ '@kerdly/expo',
82
+ `skanEndpoint "${skanEndpoint}" should be a bare https origin such as https://sdk.example.com; Apple appends /.well-known/skadnetwork/report-attribution/ itself.`
83
+ );
84
+ }
85
+ return {
86
+ metaAppId,
87
+ userTrackingPermission: optionalString(raw.userTrackingPermission, 'userTrackingPermission'),
88
+ skanEndpoint,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Sets the given keys; never removes a key, so values the app sets in `ios.infoPlist` survive.
94
+ * @param {import('@expo/config-plugins').InfoPlist} infoPlist
95
+ * @param {NormalizedProps} props
96
+ */
97
+ function applyInfoPlist(infoPlist, props) {
98
+ if (props.userTrackingPermission !== null) {
99
+ infoPlist.NSUserTrackingUsageDescription = props.userTrackingPermission;
100
+ }
101
+ if (props.skanEndpoint !== null) {
102
+ infoPlist.NSAdvertisingAttributionReportEndpoint = props.skanEndpoint;
103
+ }
104
+ return infoPlist;
105
+ }
106
+
107
+ /**
108
+ * Adds (or replaces) the meta-data item, or removes it when there is no id.
109
+ * @param {import('@expo/config-plugins').AndroidConfig.Manifest.AndroidManifest} manifest
110
+ * @param {string | null} metaAppId
111
+ */
112
+ function applyMetaAppIdToManifest(manifest, metaAppId) {
113
+ const application = AndroidConfig.Manifest.getMainApplicationOrThrow(manifest);
114
+ if (metaAppId !== null) {
115
+ AndroidConfig.Manifest.addMetaDataItemToMainApplication(application, META_APP_ID_KEY, `@string/${META_APP_ID_STRING}`, 'value');
116
+ } else {
117
+ AndroidConfig.Manifest.removeMetaDataItemFromMainApplication(application, META_APP_ID_KEY);
118
+ }
119
+ return manifest;
120
+ }
121
+
122
+ /**
123
+ * @param {import('@expo/config-plugins').AndroidConfig.Resources.ResourceXML} strings
124
+ * @param {string | null} metaAppId
125
+ */
126
+ function applyMetaAppIdToStrings(strings, metaAppId) {
127
+ strings = AndroidConfig.Strings.removeStringItem(LEGACY_META_APP_ID_STRING, strings);
128
+ if (metaAppId !== null) {
129
+ const item = AndroidConfig.Resources.buildResourceItem({ name: META_APP_ID_STRING, value: metaAppId, translatable: false });
130
+ return AndroidConfig.Strings.setStringItem([item], strings);
131
+ }
132
+ return AndroidConfig.Strings.removeStringItem(META_APP_ID_STRING, strings);
133
+ }
134
+
135
+ /** @type {import('@expo/config-plugins').ConfigPlugin<KerdlyPluginProps | void>} */
136
+ const withKerdlySdk = (config, props) => {
137
+ const options = normalizeProps(props);
138
+ config = withInfoPlist(config, (cfg) => {
139
+ cfg.modResults = applyInfoPlist(cfg.modResults, options);
140
+ return cfg;
141
+ });
142
+ config = withStringsXml(config, (cfg) => {
143
+ cfg.modResults = applyMetaAppIdToStrings(cfg.modResults, options.metaAppId);
144
+ return cfg;
145
+ });
146
+ config = withAndroidManifest(config, (cfg) => {
147
+ cfg.modResults = applyMetaAppIdToManifest(cfg.modResults, options.metaAppId);
148
+ return cfg;
149
+ });
150
+ return config;
151
+ };
152
+
153
+ const withKerdly = createRunOncePlugin(withKerdlySdk, pkg.name, pkg.version);
154
+
155
+ module.exports = {
156
+ withKerdly,
157
+ normalizeProps,
158
+ applyInfoPlist,
159
+ applyMetaAppIdToManifest,
160
+ applyMetaAppIdToStrings,
161
+ META_APP_ID_KEY,
162
+ META_APP_ID_STRING,
163
+ };
package/src/Kerdly.ts ADDED
@@ -0,0 +1,524 @@
1
+ import { Linking, Platform } from 'react-native';
2
+
3
+ import { devError, devWarn, isLogLevel, setLogLevel } from './log';
4
+ import { ATTRIBUTION_EVENT, callNative, getNativeModule, type NativeConfigureOptions } from './native';
5
+ import { normalizeAttribution, normalizeDeepLink } from './normalize';
6
+ import type {
7
+ KerdlyAttStatus,
8
+ KerdlyAttribution,
9
+ KerdlyAttributionListener,
10
+ KerdlyConfigureOptions,
11
+ KerdlyConsent,
12
+ KerdlyDeepLink,
13
+ KerdlyDeepLinkSource,
14
+ KerdlyEnvironment,
15
+ KerdlyEventProperties,
16
+ KerdlyNetworkSend,
17
+ KerdlyPurchase,
18
+ KerdlyPurchaseEvent,
19
+ KerdlyRegistrationEvent,
20
+ KerdlyRevenueEvent,
21
+ KerdlySubscription,
22
+ } from './types';
23
+ import {
24
+ isUuid,
25
+ sanitizeNetworkSend,
26
+ sanitizePartnerIds,
27
+ sanitizePurchase,
28
+ validateEvent,
29
+ validateStandardEvent,
30
+ type StandardEventMethod,
31
+ type StandardEventValidation,
32
+ } from './validation';
33
+ import { WRAPPER } from './version';
34
+
35
+ // Every public function is total: it validates its input, never throws, and its promise never
36
+ // rejects. Calls go straight to the native SDK, which holds calls made before `configure` and runs
37
+ // them after it. The only behaviour of this layer is the automatic deep-link capture.
38
+
39
+ const ENVIRONMENTS: readonly KerdlyEnvironment[] = ['auto', 'production', 'sandbox', 'development'];
40
+ const ATT_STATUSES: readonly KerdlyAttStatus[] = [
41
+ 'authorized',
42
+ 'denied',
43
+ 'restricted',
44
+ 'not_determined',
45
+ 'not_applicable',
46
+ ];
47
+
48
+ const NOOP_SUBSCRIPTION: KerdlySubscription = { remove() {} };
49
+
50
+ // Deep-link capture: one `url` subscription, and one read of the initial URL per JS runtime.
51
+ let urlSubscription: { remove(): void } | null = null;
52
+ let initialUrlRequested = false;
53
+
54
+ function warnProblems(context: string, problems: string[]): void {
55
+ if (problems.length > 0) devWarn(`${context}: ${problems.join('; ')}`);
56
+ }
57
+
58
+ function shown(value: unknown): string {
59
+ try {
60
+ return typeof value === 'string' ? JSON.stringify(value) : String(value);
61
+ } catch {
62
+ return typeof value;
63
+ }
64
+ }
65
+
66
+ // expo-dev-client opens the app with `<scheme>://expo-development-client/?url=<dev server>`;
67
+ // that is the development server, not a deep link.
68
+ function isDevLauncherUrl(url: string): boolean {
69
+ return /^[a-z][a-z0-9+.-]*:\/\/expo-development-client(?:[/?#]|$)/i.test(url);
70
+ }
71
+
72
+ function forwardUrl(url: unknown, source: KerdlyDeepLinkSource): void {
73
+ if (typeof url !== 'string' || url.length === 0 || isDevLauncherUrl(url)) return;
74
+ void callNative('handleUrl', url, source);
75
+ }
76
+
77
+ function setDeepLinkCapture(enabled: boolean): void {
78
+ if (!enabled) {
79
+ if (urlSubscription) {
80
+ try {
81
+ urlSubscription.remove();
82
+ } catch (error) {
83
+ devWarn('Removing the Linking url listener failed:', error);
84
+ }
85
+ urlSubscription = null;
86
+ }
87
+ return;
88
+ }
89
+ if (!urlSubscription) {
90
+ try {
91
+ urlSubscription = Linking.addEventListener('url', (event: { url: string }) =>
92
+ forwardUrl(event?.url, 'runtime')
93
+ );
94
+ } catch (error) {
95
+ devWarn('Could not subscribe to Linking url events:', error);
96
+ }
97
+ }
98
+ if (!initialUrlRequested) {
99
+ initialUrlRequested = true;
100
+ try {
101
+ Promise.resolve(Linking.getInitialURL()).then(
102
+ (url) => forwardUrl(url, 'initial'),
103
+ (error: unknown) => devWarn('Linking.getInitialURL failed:', error)
104
+ );
105
+ } catch (error) {
106
+ devWarn('Linking.getInitialURL failed:', error);
107
+ }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Starts the native SDK. Call it once, as early as possible (module scope of the root component).
113
+ * Resolves when the native `configure` has run; never rejects.
114
+ */
115
+ /** The Kerdly collector, used when `endpoint` is not given. */
116
+ export const DEFAULT_ENDPOINT = 'https://app.kerdly.com/api';
117
+
118
+ async function configure(options: KerdlyConfigureOptions): Promise<void> {
119
+ try {
120
+ if (options === null || typeof options !== 'object') {
121
+ devWarn('configure: an options object with `key` is required; ignored');
122
+ return;
123
+ }
124
+ const { key } = options;
125
+ const endpoint = options.endpoint === undefined ? DEFAULT_ENDPOINT : options.endpoint;
126
+ if (typeof key !== 'string' || key.length === 0) {
127
+ devWarn('configure: `key` (pk_live_… / pk_test_…) is required; ignored');
128
+ return;
129
+ }
130
+ if (typeof endpoint !== 'string' || endpoint.length === 0) {
131
+ devWarn('configure: `endpoint` must be the collector base URL; ignored');
132
+ return;
133
+ }
134
+ if (key.startsWith('sk_')) {
135
+ devError('configure: that is a server key (sk_…); apps take their public pk_ key. The SDK stays off');
136
+ return;
137
+ }
138
+ if (!/^pk_(live|test)_/.test(key)) {
139
+ devWarn('configure: `key` should be the app public key (pk_live_… / pk_test_…)');
140
+ }
141
+
142
+ let logLevel = options.logLevel ?? 'warn';
143
+ if (!isLogLevel(logLevel)) {
144
+ devWarn(`configure: unknown logLevel ${shown(logLevel)}; using "warn"`);
145
+ logLevel = 'warn';
146
+ }
147
+ setLogLevel(logLevel);
148
+
149
+ let environment = options.environment ?? 'auto';
150
+ if (!ENVIRONMENTS.includes(environment)) {
151
+ devWarn(`configure: unknown environment ${shown(environment)}; using "auto"`);
152
+ environment = 'auto';
153
+ }
154
+
155
+ const nativeOptions: NativeConfigureOptions = {
156
+ key,
157
+ endpoint,
158
+ environment,
159
+ collectAdvertisingId: options.collectAdvertisingId !== false,
160
+ skanWriter: options.skanWriter === true,
161
+ logLevel,
162
+ wrapper: WRAPPER,
163
+ };
164
+ if (typeof options.metaAppId === 'string' && options.metaAppId.length > 0) {
165
+ nativeOptions.metaAppId = options.metaAppId;
166
+ }
167
+
168
+ if (!getNativeModule()) return;
169
+ // Native calls run in call order, so URLs forwarded below reach a configured SDK.
170
+ const configured = callNative('configure', nativeOptions);
171
+ setDeepLinkCapture(options.autoDeepLinks !== false);
172
+ await configured;
173
+ } catch (error) {
174
+ devWarn('configure failed:', error);
175
+ }
176
+ }
177
+
178
+ /** Sets (or, with `null`, clears) the app's user id; attached to every later event. */
179
+ function setUserId(userId: string | null): void {
180
+ try {
181
+ if (userId === null || userId === undefined) {
182
+ void callNative('setUserId', null);
183
+ } else if (typeof userId === 'string' && userId.length > 0) {
184
+ void callNative('setUserId', userId);
185
+ } else {
186
+ devWarn(`setUserId: expected a non-empty string or null, got ${shown(userId)}; ignored`);
187
+ }
188
+ } catch (error) {
189
+ devWarn('setUserId failed:', error);
190
+ }
191
+ }
192
+
193
+ /** Records a custom event. Invalid names drop the event, invalid props are dropped. */
194
+ function track(name: string, properties?: KerdlyEventProperties): void {
195
+ try {
196
+ const { event, problems } = validateEvent(name, properties);
197
+ if (!event) {
198
+ warnProblems('track: event dropped', problems);
199
+ return;
200
+ }
201
+ warnProblems(`track(${shown(event.name)}): dropped`, problems);
202
+ void callNative('track', event.name, event.properties);
203
+ } catch (error) {
204
+ devWarn('track failed:', error);
205
+ }
206
+ }
207
+
208
+ // Standard events: a malformed typed field is dropped, never the event.
209
+ function validStandardEvent(method: StandardEventMethod, input: unknown): StandardEventValidation['event'] {
210
+ const { event, problems } = validateStandardEvent(method, input);
211
+ warnProblems(event ? `${method}: dropped` : `${method}: event dropped`, problems);
212
+ return event;
213
+ }
214
+
215
+ /** Records `registration`: the user signed up (`method`: `anonymous`, `apple`, `google`, `email`, …). */
216
+ function trackRegistration(event?: KerdlyRegistrationEvent): void {
217
+ try {
218
+ const clean = validStandardEvent('trackRegistration', event);
219
+ if (!clean) return;
220
+ void callNative('trackRegistration', clean.fields.method, clean.properties);
221
+ } catch (error) {
222
+ devWarn('trackRegistration failed:', error);
223
+ }
224
+ }
225
+
226
+ /** Records `start_trial`. `value` is what the user paid (0 for a free trial) and needs `currency`. */
227
+ function trackStartTrial(event?: KerdlyRevenueEvent): void {
228
+ try {
229
+ const clean = validStandardEvent('trackStartTrial', event);
230
+ if (!clean) return;
231
+ const { productId, value, currency, transactionId } = clean.fields;
232
+ void callNative('trackStartTrial', productId, value, currency, transactionId, clean.properties);
233
+ } catch (error) {
234
+ devWarn('trackStartTrial failed:', error);
235
+ }
236
+ }
237
+
238
+ /** Records `subscribe`: the first paid period started. `value` needs `currency`. */
239
+ function trackSubscribe(event?: KerdlyRevenueEvent): void {
240
+ try {
241
+ const clean = validStandardEvent('trackSubscribe', event);
242
+ if (!clean) return;
243
+ const { productId, value, currency, transactionId } = clean.fields;
244
+ void callNative('trackSubscribe', productId, value, currency, transactionId, clean.properties);
245
+ } catch (error) {
246
+ devWarn('trackSubscribe failed:', error);
247
+ }
248
+ }
249
+
250
+ /** Records `purchase`: a one-time purchase. `value` needs `currency`; `quantity` is an integer ≥ 1. */
251
+ function trackPurchase(event?: KerdlyPurchaseEvent): void {
252
+ try {
253
+ const clean = validStandardEvent('trackPurchase', event);
254
+ if (!clean) return;
255
+ const { productId, value, currency, quantity, transactionId } = clean.fields;
256
+ void callNative('trackPurchase', productId, value, currency, quantity, transactionId, clean.properties);
257
+ } catch (error) {
258
+ devWarn('trackPurchase failed:', error);
259
+ }
260
+ }
261
+
262
+ /** Updates consent flags; an omitted flag keeps its current value. */
263
+ function setConsent(consent: KerdlyConsent): void {
264
+ try {
265
+ if (consent === null || typeof consent !== 'object') {
266
+ devWarn('setConsent: expected { analytics?: boolean, ads?: boolean }; ignored');
267
+ return;
268
+ }
269
+ const flag = (name: 'analytics' | 'ads'): boolean | null => {
270
+ const value: unknown = consent[name];
271
+ if (value === undefined || value === null) return null;
272
+ if (typeof value === 'boolean') return value;
273
+ devWarn(`setConsent: \`${name}\` must be a boolean, got ${shown(value)}; ignored`);
274
+ return null;
275
+ };
276
+ const analytics = flag('analytics');
277
+ const ads = flag('ads');
278
+ if (analytics === null && ads === null) {
279
+ devWarn('setConsent: neither `analytics` nor `ads` was given; nothing to change');
280
+ return;
281
+ }
282
+ void callNative('setConsent', analytics, ads);
283
+ } catch (error) {
284
+ devWarn('setConsent failed:', error);
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Hands a deep link to the native SDK (which records `$deeplink`) and returns what it parsed.
290
+ * With `autoDeepLinks` on (the default) Linking URLs are already forwarded: use this only for
291
+ * URLs that do not arrive through React Native's `Linking`.
292
+ */
293
+ async function handleUrl(url: string): Promise<KerdlyDeepLink | null> {
294
+ try {
295
+ if (typeof url !== 'string' || url.length === 0) {
296
+ devWarn(`handleUrl: expected a URL string, got ${shown(url)}`);
297
+ return null;
298
+ }
299
+ return normalizeDeepLink(await callNative('handleUrl', url, null));
300
+ } catch (error) {
301
+ devWarn('handleUrl failed:', error);
302
+ return null;
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Sets (or, with `null`, clears) the account token the app's purchases carry. iOS: the StoreKit
308
+ * `appAccountToken` UUID. Android: the Play `obfuscatedAccountId` (a UUID, or Superwall's
309
+ * `$SuperwallAlias:<uuid>` before identify).
310
+ */
311
+ function setAppAccountToken(token: string | null): void {
312
+ try {
313
+ if (token === null || token === undefined) {
314
+ void callNative('setAppAccountToken', null);
315
+ } else if (typeof token !== 'string' || token.trim().length === 0) {
316
+ devWarn(`setAppAccountToken: expected a token string or null, got ${shown(token)}; ignored`);
317
+ } else if (Platform.OS === 'ios' && !isUuid(token)) {
318
+ devWarn(`setAppAccountToken: iOS takes the StoreKit appAccountToken UUID, got ${shown(token)}; ignored`);
319
+ } else {
320
+ void callNative('setAppAccountToken', token);
321
+ }
322
+ } catch (error) {
323
+ devWarn('setAppAccountToken failed:', error);
324
+ }
325
+ }
326
+
327
+ /** Ids of other SDKs (e.g. `meta_anon_id`, `superwall_alias`) for the collector to join on. */
328
+ function setPartnerIds(ids: Record<string, string>): void {
329
+ try {
330
+ const { ids: clean, problems } = sanitizePartnerIds(ids);
331
+ warnProblems('setPartnerIds: ignored', problems);
332
+ if (!clean) return;
333
+ if (Object.keys(clean).length === 0 && problems.length > 0) return;
334
+ void callNative('setPartnerIds', clean);
335
+ } catch (error) {
336
+ devWarn('setPartnerIds failed:', error);
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Links a store purchase to this install (`$purchase_link`, once per transaction / token).
342
+ * Accepts the iOS or the Android shape. On iOS, calling it without a purchase sweeps
343
+ * `Transaction.currentEntitlements`; Android needs `purchaseToken`.
344
+ */
345
+ function notifyPurchase(purchase?: KerdlyPurchase | null): void {
346
+ try {
347
+ const { purchase: clean, problems } = sanitizePurchase(purchase);
348
+ warnProblems('notifyPurchase: ignored', problems);
349
+ if (purchase !== undefined && purchase !== null && clean === null) return;
350
+ if (Platform.OS === 'android' && !clean?.purchaseToken) {
351
+ devWarn('notifyPurchase: Android needs the purchase `purchaseToken`; ignored');
352
+ return;
353
+ }
354
+ void callNative('notifyPurchase', clean);
355
+ } catch (error) {
356
+ devWarn('notifyPurchase failed:', error);
357
+ }
358
+ }
359
+
360
+ /** Records a conversion the app sent to an ad network itself (`$network_send`). */
361
+ function recordNetworkSend(send: KerdlyNetworkSend): void {
362
+ try {
363
+ const { send: clean, problems } = sanitizeNetworkSend(send);
364
+ warnProblems('recordNetworkSend: ignored', problems);
365
+ if (!clean) return;
366
+ void callNative('recordNetworkSend', clean);
367
+ } catch (error) {
368
+ devWarn('recordNetworkSend failed:', error);
369
+ }
370
+ }
371
+
372
+ /** The cached attribution, or `null` until the collector has decided one. */
373
+ async function getAttribution(): Promise<KerdlyAttribution | null> {
374
+ try {
375
+ return normalizeAttribution(await callNative('getAttribution'));
376
+ } catch (error) {
377
+ devWarn('getAttribution failed:', error);
378
+ return null;
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Calls `listener` with the current attribution at once (when already known) and whenever the
384
+ * native SDK reports a new one, like the native `Kerdly.onAttribution`.
385
+ */
386
+ function addAttributionListener(listener: KerdlyAttributionListener): KerdlySubscription {
387
+ try {
388
+ if (typeof listener !== 'function') {
389
+ devWarn('addAttributionListener: listener must be a function');
390
+ return NOOP_SUBSCRIPTION;
391
+ }
392
+ const native = getNativeModule();
393
+ if (!native || typeof native.addListener !== 'function') return NOOP_SUBSCRIPTION;
394
+ let removed = false;
395
+ let delivered = false;
396
+ const deliver = (attribution: KerdlyAttribution): void => {
397
+ delivered = true;
398
+ try {
399
+ listener(attribution);
400
+ } catch (error) {
401
+ devError('An attribution listener threw:', error);
402
+ }
403
+ };
404
+ const subscription = native.addListener(ATTRIBUTION_EVENT, (payload: unknown) => {
405
+ const attribution = normalizeAttribution(payload);
406
+ if (attribution) deliver(attribution);
407
+ else devWarn('Ignored a malformed onAttribution event:', payload);
408
+ });
409
+ // The native handler is registered once per process, so its "at once" call happened before
410
+ // this listener existed; replay the cached value unless an event got here first.
411
+ void callNative('getAttribution').then((payload) => {
412
+ if (removed || delivered) return;
413
+ const attribution = normalizeAttribution(payload);
414
+ if (attribution) deliver(attribution);
415
+ });
416
+ return {
417
+ remove() {
418
+ if (removed) return;
419
+ removed = true;
420
+ try {
421
+ subscription?.remove();
422
+ } catch (error) {
423
+ devWarn('Removing the attribution listener failed:', error);
424
+ }
425
+ },
426
+ };
427
+ } catch (error) {
428
+ devWarn('addAttributionListener failed:', error);
429
+ return NOOP_SUBSCRIPTION;
430
+ }
431
+ }
432
+
433
+ /**
434
+ * iOS: shows the App Tracking Transparency prompt (needs `NSUserTrackingUsageDescription`, which
435
+ * the config plugin's `userTrackingPermission` sets) and resolves the resulting status.
436
+ * Android: resolves `not_applicable`.
437
+ */
438
+ async function requestTrackingAuthorization(): Promise<KerdlyAttStatus> {
439
+ try {
440
+ if (Platform.OS !== 'ios') return 'not_applicable';
441
+ const status = await callNative('requestTrackingAuthorization');
442
+ return typeof status === 'string' && (ATT_STATUSES as readonly string[]).includes(status)
443
+ ? (status as KerdlyAttStatus)
444
+ : 'not_determined';
445
+ } catch (error) {
446
+ devWarn('requestTrackingAuthorization failed:', error);
447
+ return 'not_determined';
448
+ }
449
+ }
450
+
451
+ /** Asks the native SDK to send its queue now. Resolves once the request is handed over. */
452
+ async function flush(): Promise<void> {
453
+ try {
454
+ await callNative('flush');
455
+ } catch (error) {
456
+ devWarn('flush failed:', error);
457
+ }
458
+ }
459
+
460
+ /** The install id (a lowercase UUID), or `null` before the first `configure`. */
461
+ async function getInstallId(): Promise<string | null> {
462
+ try {
463
+ const id = await callNative('getInstallId');
464
+ return typeof id === 'string' && id.length > 0 ? id : null;
465
+ } catch (error) {
466
+ devWarn('getInstallId failed:', error);
467
+ return null;
468
+ }
469
+ }
470
+
471
+ /** One network's answer to a deferred-deep-link request (`debugFetchDeferredLinks`). */
472
+ export interface KerdlyDeferredLinkAnswer {
473
+ network: string;
474
+ /** `link` | `none` | `error` | `skipped_att` | `skipped_consent` | `not_configured`. */
475
+ status: string;
476
+ url?: string;
477
+ clickTime?: string;
478
+ httpStatus?: number;
479
+ detail?: string;
480
+ }
481
+
482
+ /**
483
+ * Debug builds only (iOS): asks Meta (ids from the app's Facebook config) and TikTok
484
+ * (`tiktokAppId`) for this device's deferred deep link and resolves each network's raw answer.
485
+ * Sends nothing to Kerdly. Asks only when the `ads` consent is on and tracking is authorized. In a
486
+ * release build it asks nothing and every answer is `error` ("debug builds only"). Android
487
+ * resolves `[]`.
488
+ */
489
+ async function debugFetchDeferredLinks(
490
+ options: { tiktokAppId?: string | null; storeAppId?: string | null } = {},
491
+ ): Promise<KerdlyDeferredLinkAnswer[]> {
492
+ try {
493
+ if (Platform.OS !== 'ios') return [];
494
+ const answers = await callNative('debugFetchDeferredLinks', options.tiktokAppId ?? null, options.storeAppId ?? null);
495
+ return Array.isArray(answers) ? (answers as KerdlyDeferredLinkAnswer[]) : [];
496
+ } catch (error) {
497
+ devWarn('debugFetchDeferredLinks failed:', error);
498
+ return [];
499
+ }
500
+ }
501
+
502
+ export const Kerdly = {
503
+ configure,
504
+ setUserId,
505
+ track,
506
+ trackRegistration,
507
+ trackStartTrial,
508
+ trackSubscribe,
509
+ trackPurchase,
510
+ setConsent,
511
+ handleUrl,
512
+ setAppAccountToken,
513
+ setPartnerIds,
514
+ notifyPurchase,
515
+ recordNetworkSend,
516
+ getAttribution,
517
+ addAttributionListener,
518
+ requestTrackingAuthorization,
519
+ flush,
520
+ getInstallId,
521
+ debugFetchDeferredLinks,
522
+ };
523
+
524
+ export type KerdlyApi = typeof Kerdly;