@altcraft/react-native-sdk 0.0.1 → 0.0.3

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 (34) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +5 -2
  3. package/android/build.gradle +2 -3
  4. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +493 -896
  5. package/android/src/main/java/com/altcraft/sdk/utilities/Converter.kt +326 -0
  6. package/android/src/main/java/com/altcraft/sdk/utilities/Extension.kt +72 -0
  7. package/ios/Converter.swift +640 -0
  8. package/ios/Sdk.h +4 -3
  9. package/ios/Sdk.mm +124 -370
  10. package/ios/SdkModule.swift +436 -653
  11. package/lib/module/NativeSdk.js +35 -0
  12. package/lib/module/NativeSdk.js.map +1 -1
  13. package/lib/module/Utilities.js +94 -0
  14. package/lib/module/Utilities.js.map +1 -0
  15. package/lib/module/index.js +180 -419
  16. package/lib/module/index.js.map +1 -1
  17. package/lib/typescript/src/NativeSdk.d.ts +117 -32
  18. package/lib/typescript/src/NativeSdk.d.ts.map +1 -1
  19. package/lib/typescript/src/Utilities.d.ts +15 -0
  20. package/lib/typescript/src/Utilities.d.ts.map +1 -0
  21. package/lib/typescript/src/index.d.ts +113 -308
  22. package/lib/typescript/src/index.d.ts.map +1 -1
  23. package/package.json +2 -2
  24. package/src/NativeSdk.ts +156 -46
  25. package/src/Utilities.ts +116 -0
  26. package/src/index.tsx +255 -483
  27. package/android/src/main/java/com/altcraft/sdk/interfaces/RnFCMProvider.kt +0 -27
  28. package/android/src/main/java/com/altcraft/sdk/interfaces/RnHMSProvider.kt +0 -32
  29. package/android/src/main/java/com/altcraft/sdk/interfaces/RnJWTProvider.kt +0 -21
  30. package/android/src/main/java/com/altcraft/sdk/interfaces/RnRustoreProvider.kt +0 -53
  31. package/ios/protocols/RNAPNSProvider.swift +0 -15
  32. package/ios/protocols/RNFCMProvider.swift +0 -24
  33. package/ios/protocols/RNHMSProvider.swift +0 -24
  34. package/ios/protocols/RNJWTProvider.swift +0 -15
@@ -1,25 +1,35 @@
1
1
  package com.altcraft.sdk
2
2
 
3
+ // Created by Andrey Pogodin.
4
+ //
5
+ // Copyright © 2025 Altcraft. All rights reserved.
6
+
3
7
  import androidx.activity.ComponentActivity
4
- import com.altcraft.sdk.AltcraftSDK
5
8
  import com.altcraft.sdk.config.AltcraftConfiguration
6
9
  import com.altcraft.sdk.data.DataClasses
7
10
  import com.altcraft.sdk.mob_events.PublicMobileEventFunction
8
11
  import com.altcraft.sdk.push.events.PublicPushEventFunctions
9
12
  import com.altcraft.sdk.push.subscribe.PublicPushSubscriptionFunctions
10
13
  import com.altcraft.sdk.push.token.PublicPushTokenFunctions
11
- import com.altcraft.sdk.rn.providers.RnFCMProvider
12
- import com.altcraft.sdk.rn.providers.RnHMSProvider
13
- import com.altcraft.sdk.rn.providers.RnJWTProvider
14
- import com.altcraft.sdk.rn.providers.RnRuStoreProvider
14
+ import com.altcraft.sdk.rn.getArrayOrNull
15
+ import com.altcraft.sdk.rn.getBooleanOrNull
16
+ import com.altcraft.sdk.rn.getIntOrNull
17
+ import com.altcraft.sdk.rn.getMapOrNull
18
+ import com.altcraft.sdk.rn.getStringOrNull
19
+ import com.altcraft.sdk.rn.hasNonNullKey
20
+ import com.altcraft.sdk.rn.putNullableBoolean
21
+ import com.altcraft.sdk.rn.putNullableInt
22
+ import com.altcraft.sdk.rn.putNullableString
23
+ import com.altcraft.sdk.rn.toStringList
15
24
  import com.altcraft.sdk.sdk_events.Events
25
+ import com.altcraft.sdk.utilities.Converter
16
26
  import com.facebook.react.bridge.Arguments
17
27
  import com.facebook.react.bridge.Promise
18
28
  import com.facebook.react.bridge.ReactApplicationContext
19
29
  import com.facebook.react.bridge.ReadableArray
20
30
  import com.facebook.react.bridge.ReadableMap
21
- import com.facebook.react.bridge.WritableMap
22
31
  import com.facebook.react.bridge.UiThreadUtil
32
+ import com.facebook.react.bridge.WritableMap
23
33
  import com.facebook.react.module.annotations.ReactModule
24
34
  import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
25
35
  import kotlinx.coroutines.CoroutineScope
@@ -27,198 +37,120 @@ import kotlinx.coroutines.Dispatchers
27
37
  import kotlinx.coroutines.SupervisorJob
28
38
  import kotlinx.coroutines.launch
29
39
 
30
- /**
31
- * React Native bridge module for Altcraft Android SDK.
32
- *
33
- * Responsibilities:
34
- * - Initializes the SDK from JS configuration.
35
- * - Provides token/auth providers (JWT, FCM, HMS, RuStore).
36
- * - Exposes push token API (get/set/delete/force update).
37
- * - Bridges subscription calls and async status methods.
38
- * - Emits SDK events to JS via DeviceEventEmitter ("AltcraftSdkEvent").
39
- *
40
- * Threading:
41
- * - Async / I/O methods are executed on [Dispatchers.IO].
42
- * - Some SDK callbacks are marshalled back to the UI queue when required.
43
- */
44
- @ReactModule(name = SdkModule.NAME)
45
- class SdkModule(
46
- reactContext: ReactApplicationContext
47
- ) : NativeSdkSpec(reactContext) {
48
-
49
- /**
50
- * Background scope for bridge calls that must not block JS thread.
51
- *
52
- * Note: lifecycle is bound to the module instance. If you later add teardown,
53
- * cancel this scope accordingly.
54
- */
55
- private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
56
-
57
- override fun getName(): String = NAME
58
-
59
- // ---------------------- init / auth / providers ----------------------
60
-
61
- /**
62
- * Initializes Altcraft SDK with configuration provided from React Native.
63
- *
64
- * Expected behavior:
65
- * - Resolves [promise] with `null` on success.
66
- * - Rejects [promise] with:
67
- * - ALTCRAFT_INIT_INVALID_CONFIG — if config mapping failed/invalid.
68
- * - ALTCRAFT_INIT_ERROR — if SDK initialization returned failure.
69
- *
70
- * Threading:
71
- * - SDK init callback is marshalled to UI queue before resolving/rejecting.
72
- */
73
- override fun initialize(config: ReadableMap, promise: Promise) {
74
- AltcraftRnInitializer.initialize(
75
- reactApplicationContext,
76
- config,
77
- promise
78
- )
79
- }
80
-
81
- /**
82
- * Sets JWT token for requests performed by Altcraft SDK.
83
- *
84
- * If [token] is null/blank:
85
- * - Clears RN provider state and disables JWT provider in the SDK.
86
- *
87
- * If [token] is provided:
88
- * - Stores token in RN provider and registers it in the SDK.
89
- *
90
- * Notes:
91
- * - This method is synchronous and safe to call multiple times.
92
- */
93
- override fun setJwt(token: String?) {
94
- if (token.isNullOrBlank()) {
95
- RnJWTProvider.clear()
96
- AltcraftSDK.setJWTProvider(null)
97
- } else {
98
- RnJWTProvider.setToken(token)
99
- AltcraftSDK.setJWTProvider(RnJWTProvider)
100
- }
101
- }
102
-
103
- /**
104
- * Sets FCM token for Android push provider.
105
- *
106
- * If [token] is null/blank:
107
- * - Clears provider state and unregisters provider from SDK.
108
- *
109
- * If [token] is provided:
110
- * - Stores token and registers provider in SDK push token functions.
111
- */
112
- override fun setAndroidFcmToken(token: String?) {
113
- if (token.isNullOrBlank()) {
114
- RnFCMProvider.clear()
115
- PublicPushTokenFunctions.setFCMTokenProvider(null)
116
- } else {
117
- RnFCMProvider.setToken(token)
118
- PublicPushTokenFunctions.setFCMTokenProvider(RnFCMProvider)
119
- }
120
- }
121
-
122
- /**
123
- * iOS-only API. No-op on Android.
124
- *
125
- * Exists to keep the RN Spec platform-agnostic.
126
- */
127
- override fun setIosFcmToken(token: String?) {
128
- // no-op on Android
129
- }
40
+ // ---------------------- Constants ----------------------
41
+
42
+ private object RnConstants {
43
+ // Module
44
+ const val MODULE_NAME: String = "Sdk"
45
+
46
+ // JS event emitter
47
+ const val JS_EVENT_NAME: String = "AltcraftSdkEvent"
48
+
49
+ // Promise reject codes
50
+ const val ERR_INIT_INVALID_CONFIG: String = "ALTCRAFT_INIT_INVALID_CONFIG"
51
+ const val ERR_INIT_ERROR: String = "ALTCRAFT_INIT_ERROR"
52
+ const val ERR_GET_PUSH_TOKEN: String = "getPushToken"
53
+ const val ERR_SET_PUSH_TOKEN: String = "setPushToken"
54
+ const val ERR_CLEAR: String = "clear"
55
+ const val ERR_UNSUSPEND: String = "unSuspendPushSubscription"
56
+ const val ERR_GET_LATEST_STATUS: String = "getStatusOfLatestSubscription"
57
+ const val ERR_GET_CURRENT_STATUS: String = "getStatusForCurrentSubscription"
58
+ const val ERR_GET_LATEST_STATUS_PROVIDER: String = "getStatusOfLatestSubscriptionForProvider"
59
+
60
+ // Promise reject messages
61
+ const val MSG_PROVIDER_IS_BLANK: String = "provider is blank"
62
+ const val MSG_INIT_UNKNOWN: String = "Altcraft initialization failed with unknown error"
63
+ const val MSG_INIT_ERROR: String = "Altcraft initialization error"
64
+
65
+ // Keys: TokenData map
66
+ const val KEY_PROVIDER: String = "provider"
67
+ const val KEY_TOKEN: String = "token"
68
+
69
+ // Keys: SDK event map
70
+ const val KEY_FUNCTION: String = "function"
71
+ const val KEY_CODE: String = "code"
72
+ const val KEY_MESSAGE: String = "message"
73
+ const val KEY_TYPE: String = "type"
74
+ const val KEY_VALUE: String = "value"
75
+
76
+ // Event types for JS
77
+ const val TYPE_EVENT: String = "event"
78
+ const val TYPE_ERROR: String = "error"
79
+ const val TYPE_RETRY_ERROR: String = "retryError"
80
+
81
+ // Keys: ResponseWithHttpCode -> JS map
82
+ const val KEY_HTTP_CODE: String = "httpCode"
83
+ const val KEY_RESPONSE: String = "response"
84
+ const val KEY_ERROR: String = "error"
85
+ const val KEY_ERROR_TEXT: String = "errorText"
86
+ const val KEY_PROFILE: String = "profile"
87
+ const val KEY_ID: String = "id"
88
+ const val KEY_STATUS: String = "status"
89
+ const val KEY_IS_TEST: String = "isTest"
90
+ const val KEY_SUBSCRIPTION: String = "subscription"
91
+ const val KEY_SUBSCRIPTION_ID: String = "subscriptionId"
92
+ const val KEY_HASH_ID: String = "hashId"
93
+
94
+ // Fields not mapped yet (kept for parity with TS)
95
+ const val KEY_FIELDS: String = "fields"
96
+ const val KEY_CATS: String = "cats"
97
+ }
130
98
 
131
- /**
132
- * Sets HMS token for Android push provider.
133
- *
134
- * If [token] is null/blank:
135
- * - Clears provider state and unregisters provider from SDK.
136
- *
137
- * If [token] is provided:
138
- * - Stores token and registers provider in SDK push token functions.
139
- */
140
- override fun setAndroidHmsToken(token: String?) {
141
- if (token.isNullOrBlank()) {
142
- RnHMSProvider.clear()
143
- PublicPushTokenFunctions.setHMSTokenProvider(null)
144
- } else {
145
- RnHMSProvider.setToken(token)
146
- PublicPushTokenFunctions.setHMSTokenProvider(RnHMSProvider)
147
- }
148
- }
99
+ @ReactModule(name = RnConstants.MODULE_NAME)
100
+ class SdkModule(reactContext: ReactApplicationContext) : NativeSdkSpec(reactContext) {
149
101
 
150
- /**
151
- * iOS-only API. No-op on Android.
152
- *
153
- * Exists to keep the RN Spec platform-agnostic.
154
- */
155
- override fun setIosHmsToken(token: String?) {
156
- // no-op on Android
157
- }
102
+ private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
158
103
 
159
- /**
160
- * iOS-only API. No-op on Android.
161
- *
162
- * Exists to keep the RN Spec platform-agnostic.
163
- */
164
- override fun setApnsToken(token: String?) {
165
- // no-op on Android
166
- }
104
+ override fun getName(): String = RnConstants.MODULE_NAME
167
105
 
168
106
  /**
169
- * Sets RuStore token for Android push provider.
170
- *
171
- * If [token] is null/blank:
172
- * - Clears provider state and unregisters provider from SDK.
107
+ * Required by NativeEventEmitter (no-op on Android).
173
108
  *
174
- * If [token] is provided:
175
- * - Stores token and registers provider in SDK push token functions.
109
+ * @param eventName Event name from JS side.
176
110
  */
177
- override fun setRustoreToken(token: String?) {
178
- if (token.isNullOrBlank()) {
179
- RnRuStoreProvider.clear()
180
- PublicPushTokenFunctions.setRuStoreTokenProvider(null)
181
- } else {
182
- RnRuStoreProvider.setToken(token)
183
- PublicPushTokenFunctions.setRuStoreTokenProvider(RnRuStoreProvider)
184
- }
111
+ override fun addListener(eventName: String) {
112
+ // no-op
185
113
  }
186
114
 
187
- // ---------------------- required for NativeEventEmitter ----------------------
188
-
189
115
  /**
190
- * React Native requires this method when JS uses NativeEventEmitter.
116
+ * Required by NativeEventEmitter (no-op on Android).
191
117
  *
192
- * RN may call it when JS adds a listener for a given [eventName].
193
- * We don't need native-side bookkeeping here because we manage SDK subscription
194
- * explicitly via [subscribeToEvents]/[unsubscribeFromEvent].
118
+ * @param count Number of JS listeners removed.
195
119
  */
196
- override fun addListener(eventName: String) {
120
+ override fun removeListeners(count: Double) {
197
121
  // no-op
198
122
  }
199
123
 
124
+ // ---------------------- init ----------------------
125
+
200
126
  /**
201
- * React Native requires this method when JS uses NativeEventEmitter.
127
+ * Initializes the native Altcraft SDK using RN config map.
202
128
  *
203
- * RN may call it to notify native side that [count] listeners were removed.
204
- * We keep it as no-op for symmetry with [addListener].
129
+ * @param config React Native configuration object.
130
+ * ```
131
+ * Required: `apiUrl`.
132
+ * Optional: `rToken`, `appInfo`, `providerPriorityList`, `enableLogging`,
133
+ * Android-only: `android_icon`, `android_usingService`, `android_serviceMessage`,
134
+ * `android_pushReceiverModules`, `android_pushChannelName`, `android_pushChannelDescription`.
135
+ * @param promise
136
+ * ```
137
+ * Promise resolved on success; rejected on invalid config or initialization failure.
205
138
  */
206
- override fun removeListeners(count: Double) {
207
- // no-op
139
+ override fun initialize(config: ReadableMap, promise: Promise) {
140
+ AltcraftRnInitializer.initialize(
141
+ reactContext = reactApplicationContext,
142
+ config = config,
143
+ promise = promise
144
+ )
208
145
  }
209
146
 
210
- // ---------------------- token-API for RN ----------------------
147
+ // ---------------------- token-API for RN (ONLY getPushToken / setPushToken)
148
+ // ----------------------
211
149
 
212
150
  /**
213
- * Returns current push token resolved by Altcraft SDK (if available).
214
- *
215
- * Promise:
216
- * - resolves `null` if token is not available yet;
217
- * - resolves `{ provider: string, token: string }` if available;
218
- * - rejects on unexpected errors.
151
+ * Returns current push token data from native side.
219
152
  *
220
- * Threading:
221
- * - executed on IO dispatcher.
153
+ * @param promise Resolves to `{ provider, token }` or `null` if token is not available.
222
154
  */
223
155
  override fun getPushToken(promise: Promise) {
224
156
  coroutineScope.launch {
@@ -228,197 +160,74 @@ class SdkModule(
228
160
  promise.resolve(null)
229
161
  } else {
230
162
  val map = Arguments.createMap()
231
- map.putString("provider", tokenData.provider)
232
- map.putString("token", tokenData.token)
163
+ map.putString(RnConstants.KEY_PROVIDER, tokenData.provider)
164
+ map.putString(RnConstants.KEY_TOKEN, tokenData.token)
233
165
  promise.resolve(map)
234
166
  }
235
167
  } catch (e: Exception) {
236
- promise.reject("getPushToken", e)
168
+ promise.reject(RnConstants.ERR_GET_PUSH_TOKEN, e)
237
169
  }
238
170
  }
239
171
  }
240
172
 
241
173
  /**
242
- * Deletes device token for a specific provider on backend (and/or local SDK state,
243
- * depending on SDK implementation).
244
- *
245
- * Params:
246
- * - [provider] — provider identifier (e.g. "fcm", "hms", "rustore").
247
- *
248
- * Promise:
249
- * - resolves `null` on success;
250
- * - rejects if [provider] is null or request fails.
174
+ * Sets or clears push token for the given provider.
251
175
  *
252
- * Threading:
253
- * - executed on IO dispatcher.
254
- */
255
- override fun deleteDeviceToken(provider: String?, promise: Promise) {
256
- val p: String = provider ?: run {
257
- promise.reject("deleteDeviceToken", "provider is null")
258
- return
259
- }
260
-
261
- coroutineScope.launch {
262
- try {
263
- PublicPushTokenFunctions.deleteDeviceToken(reactApplicationContext, p)
264
- promise.resolve(null)
265
- } catch (e: Exception) {
266
- promise.reject("deleteDeviceToken", e)
267
- }
268
- }
269
- }
270
-
271
- /**
272
- * Forces push token update flow in the SDK.
273
- *
274
- * Promise:
275
- * - resolves `null` when update flow completes (SDK callback).
276
- * - rejects on unexpected errors.
277
- *
278
- * Threading:
279
- * - executed on IO dispatcher.
280
- */
281
- override fun forcedTokenUpdate(promise: Promise) {
282
- coroutineScope.launch {
283
- try {
284
- PublicPushTokenFunctions.forcedTokenUpdate(reactApplicationContext) {
285
- promise.resolve(null)
286
- }
287
- } catch (e: Exception) {
288
- promise.reject("forcedTokenUpdate", e)
289
- }
290
- }
291
- }
292
-
293
- /**
294
- * Updates push provider priority list (order of providers to be used/preferred).
295
- *
296
- * Params:
297
- * - [priorityList] — array of provider ids in desired order.
298
- *
299
- * Promise:
300
- * - resolves `null` on success;
301
- * - rejects on failure.
302
- *
303
- * Threading:
304
- * - executed on IO dispatcher.
305
- */
306
- override fun changePushProviderPriorityList(priorityList: ReadableArray?, promise: Promise) {
307
- val list = priorityList.toStringList()
308
- coroutineScope.launch {
309
- try {
310
- PublicPushTokenFunctions.changePushProviderPriorityList(
311
- context = reactApplicationContext,
312
- priorityList = list
313
- )
314
- promise.resolve(null)
315
- } catch (e: Exception) {
316
- promise.reject("changePushProviderPriorityList", e)
317
- }
318
- }
319
- }
320
-
321
- /**
322
- * Sets or clears push token for a specific provider.
323
- *
324
- * JS Spec: setPushToken(provider: string, token: string | null): Promise<void>
325
- *
326
- * Behavior:
327
- * - if [token] == null -> treated as "clear token" and calls deleteDeviceToken(provider)
328
- * - if [token] != null -> calls setPushToken(provider, token)
329
- *
330
- * Promise:
331
- * - resolves `null` on success;
332
- * - rejects on invalid provider or request failures.
333
- *
334
- * Threading:
335
- * - executed on IO dispatcher.
176
+ * @param provider Provider identifier (must be non-blank).
177
+ * @param token Token string or `null` to clear (native expects String; `null` is converted to
178
+ * empty string).
179
+ * @param promise Resolves when the token is saved on native side.
336
180
  */
337
181
  override fun setPushToken(provider: String, token: String?, promise: Promise) {
338
182
  if (provider.isBlank()) {
339
- promise.reject("setPushToken", "provider is blank")
183
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, RnConstants.MSG_PROVIDER_IS_BLANK)
340
184
  return
341
185
  }
342
186
 
343
187
  coroutineScope.launch {
344
188
  try {
345
- if (token == null) {
346
- PublicPushTokenFunctions.deleteDeviceToken(
347
- context = reactApplicationContext,
348
- provider = provider
349
- )
350
- promise.resolve(null)
351
- return@launch
352
- }
189
+ val tokenToPass: String = token ?: ""
353
190
 
354
191
  PublicPushTokenFunctions.setPushToken(
355
- context = reactApplicationContext,
356
- provider = provider,
357
- token = token
192
+ context = reactApplicationContext,
193
+ provider = provider,
194
+ token = tokenToPass
358
195
  )
359
196
  promise.resolve(null)
360
197
  } catch (e: Exception) {
361
- promise.reject("setPushToken", e)
198
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, e)
362
199
  }
363
200
  }
364
201
  }
365
202
 
366
- // ---------------------- AltcraftSDK: clear / retry / permission ----------------------
203
+ // ---------------------- AltcraftSDK: clear / permission ----------------------
367
204
 
368
205
  /**
369
- * Clears SDK local state (tokens/subscriptions/cache depending on SDK implementation).
206
+ * Clears SDK local state and stored data (native).
370
207
  *
371
- * Promise:
372
- * - resolves `null` on success;
373
- * - rejects on unexpected errors.
208
+ * @param promise Resolves after cleanup is finished.
374
209
  */
375
210
  override fun clear(promise: Promise) {
376
211
  try {
377
- AltcraftSDK.clear(reactApplicationContext) {
378
- promise.resolve(null)
379
- }
212
+ AltcraftSDK.clear(reactApplicationContext) { promise.resolve(null) }
380
213
  } catch (e: Exception) {
381
- promise.reject("clear", e)
214
+ promise.reject(RnConstants.ERR_CLEAR, e)
382
215
  }
383
216
  }
384
217
 
385
218
  /**
386
- * Reinitializes retry control for current session.
387
- *
388
- * Intended use:
389
- * - allows SDK to reset retry counters/logic without full re-init.
390
- *
391
- * Notes:
392
- * - swallow exceptions by design (bridge safety).
393
- */
394
- override fun reinitializeRetryControlInThisSession() {
395
- try {
396
- AltcraftSDK.reinitializeRetryControlInThisSession()
397
- } catch (_: Exception) {
398
- }
399
- }
400
-
401
- /**
402
- * Requests Android notification permission (where applicable).
403
- *
404
- * Requirements:
405
- * - [currentActivity] must be a [ComponentActivity], otherwise this is no-op.
406
- *
407
- * Threading:
408
- * - permission request is executed on UI thread.
219
+ * Requests notification permission (Android-only runtime behavior). Safe no-op if current
220
+ * Activity is not a ComponentActivity.
409
221
  */
410
222
  override fun requestNotificationPermission() {
411
223
  val activity = currentActivity
412
- if (activity !is ComponentActivity) {
413
- return
414
- }
224
+ if (activity !is ComponentActivity) return
225
+
415
226
  UiThreadUtil.runOnUiThread {
416
227
  try {
417
- AltcraftSDK.requestNotificationPermission(
418
- reactApplicationContext,
419
- activity
420
- )
228
+ AltcraftSDK.requestNotificationPermission(reactApplicationContext, activity)
421
229
  } catch (_: Exception) {
230
+ // ignore
422
231
  }
423
232
  }
424
233
  }
@@ -426,171 +235,142 @@ class SdkModule(
426
235
  // ---------------------- MobileEvent bridge ----------------------
427
236
 
428
237
  /**
429
- * Sends a mobile event to Altcraft backend via SDK.
430
- *
431
- * Params:
432
- * - [sid] — session/subscribe identifier (SDK-specific).
433
- * - [eventName] — event name.
434
- * - [sendMessageId] — optional message id to link event with campaign.
435
- * - [payload] — event payload.
436
- * - [matching] — matching fields.
437
- * - [matchingType] — matching strategy/type (SDK-specific).
438
- * - [profileFields] — profile fields to attach/update.
238
+ * Sends a mobile event to the server (fire-and-forget).
439
239
  *
440
- * Notes:
441
- * - `subscription` and `utm` are not supported in RN bridge yet (sent as null).
442
- * - exceptions are swallowed by design to keep JS bridge stable.
240
+ * @param sid Pixel identifier.
241
+ * @param eventName Event name.
242
+ * @param sendMessageId Optional message identifier to link the event.
243
+ * @param payload Optional event payload (string-only map).
244
+ * @param matching Optional matching parameters (string-only map).
245
+ * @param matchingType Optional matching mode/type.
246
+ * @param profileFields Optional profile fields (string-only map).
247
+ * @param subscription Optional subscription info (email/sms/push/cc_data), converted on native
248
+ * side.
249
+ * @param utm Optional UTM tags for attribution.
443
250
  */
444
251
  override fun mobileEvent(
445
- sid: String,
446
- eventName: String,
447
- sendMessageId: String?,
448
- payload: ReadableMap?,
449
- matching: ReadableMap?,
450
- matchingType: String?,
451
- profileFields: ReadableMap?
252
+ sid: String,
253
+ eventName: String,
254
+ sendMessageId: String?,
255
+ payload: ReadableMap?,
256
+ matching: ReadableMap?,
257
+ matchingType: String?,
258
+ profileFields: ReadableMap?,
259
+ subscription: ReadableMap?,
260
+ utm: ReadableMap?
452
261
  ) {
453
262
  try {
263
+ val utmData =
264
+ utm?.let {
265
+ DataClasses.UTM(
266
+ campaign = it.getString("campaign"),
267
+ content = it.getString("content"),
268
+ keyword = it.getString("keyword"),
269
+ medium = it.getString("medium"),
270
+ source = it.getString("source"),
271
+ temp = it.getString("temp")
272
+ )
273
+ }
274
+
454
275
  PublicMobileEventFunction.mobileEvent(
455
- context = reactApplicationContext,
456
- sid = sid,
457
- eventName = eventName,
458
- sendMessageId = sendMessageId,
459
- payload = payload.toMapOrNull(),
460
- matching = matching.toMapOrNull(),
461
- matchingType = matchingType,
462
- profileFields = profileFields.toMapOrNull(),
463
- subscription = null,
464
- utm = null
276
+ context = reactApplicationContext,
277
+ sid = sid,
278
+ eventName = eventName,
279
+ sendMessageId = sendMessageId,
280
+ payload = Converter.toKotlinMap(payload),
281
+ matching = Converter.toKotlinMap(matching),
282
+ matchingType = matchingType,
283
+ profileFields = Converter.toKotlinMap(profileFields),
284
+ subscription = Converter.toSubscriptionOrNull(subscription),
285
+ utm = utmData
465
286
  )
466
- } catch (_: Exception) {
287
+ } catch (e: Exception) {
288
+ // Log error but don't crash bridge
289
+ e.printStackTrace()
467
290
  }
468
291
  }
469
292
 
470
293
  // ---------------------- push payload bridge ----------------------
471
294
 
472
295
  /**
473
- * Passes raw push payload to SDK for parsing/processing.
296
+ * Forwards a push payload to native SDK (Android-only behavior).
474
297
  *
475
- * Input:
476
- * - [message] is a map of string key/value pairs (RN side object).
477
- *
478
- * Behavior:
479
- * - converts [ReadableMap] into Map<String, String> and forwards it into SDK receiver.
480
- * - if [message] is null or results in empty map — no-op.
298
+ * @param message Push payload map (string-only).
481
299
  */
482
300
  override fun takePush(message: ReadableMap?) {
483
301
  if (message == null) return
484
-
485
- val map = mutableMapOf<String, String>()
486
- val iterator = message.keySetIterator()
487
- while (iterator.hasNextKey()) {
488
- val key = iterator.nextKey()
489
- if (!message.isNull(key)) {
490
- val value = message.getString(key)
491
- if (value != null) {
492
- map[key] = value
493
- }
494
- }
495
- }
496
-
302
+ val map = Converter.toStringMapOrNull(message) ?: return
497
303
  if (map.isNotEmpty()) {
498
304
  AltcraftSDK.PushReceiver.takePush(reactApplicationContext, map)
499
305
  }
500
306
  }
501
307
 
308
+ // ---------------------- manual push events ----------------------
309
+
502
310
  /**
503
- * Sends push delivery event (SDK analytics/track).
504
- *
505
- * Params:
506
- * - [message] — raw push payload as map (string key/value).
507
- * - [messageUID] — optional unique message id.
311
+ * Reports a push delivery event (Android-only behavior).
508
312
  *
509
- * Notes:
510
- * - Exceptions are swallowed to avoid breaking JS flow.
313
+ * @param message Optional push payload (string-only map).
314
+ * @param messageUID Optional Altcraft message UID.
511
315
  */
512
316
  override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
513
317
  try {
514
- val map = message.toStringMapOrNull()
318
+ val map = Converter.toStringMapOrNull(message)
515
319
  PublicPushEventFunctions.deliveryEvent(
516
- context = reactApplicationContext,
517
- message = map,
518
- messageUID = messageUID
320
+ context = reactApplicationContext,
321
+ message = map,
322
+ messageUID = messageUID
519
323
  )
520
324
  } catch (_: Exception) {
325
+ // ignore
521
326
  }
522
327
  }
523
328
 
524
329
  /**
525
- * Sends push open event (SDK analytics/track).
330
+ * Reports a push open event (Android-only behavior).
526
331
  *
527
- * Params:
528
- * - [message] — raw push payload as map (string key/value).
529
- * - [messageUID] — optional unique message id.
530
- *
531
- * Notes:
532
- * - Exceptions are swallowed to avoid breaking JS flow.
332
+ * @param message Optional push payload (string-only map).
333
+ * @param messageUID Optional Altcraft message UID.
533
334
  */
534
335
  override fun openEvent(message: ReadableMap?, messageUID: String?) {
535
336
  try {
536
- val map = message.toStringMapOrNull()
337
+ val map = Converter.toStringMapOrNull(message)
537
338
  PublicPushEventFunctions.openEvent(
538
- context = reactApplicationContext,
539
- message = map,
540
- messageUID = messageUID
339
+ context = reactApplicationContext,
340
+ message = map,
341
+ messageUID = messageUID
541
342
  )
542
343
  } catch (_: Exception) {
344
+ // ignore
543
345
  }
544
346
  }
545
347
 
546
348
  // --------------------- Events bridge for RN ---------------------
547
349
 
548
350
  /**
549
- * Subscribes to SDK events and forwards them to JS.
550
- *
551
- * JS side listens to:
552
- * - event name: "AltcraftSdkEvent"
553
- * - payload: { function, code?, message, value?, type }
554
- *
555
- * Notes:
556
- * - For multiple subscriptions from JS, use JS-side guard (your TS already does it).
351
+ * Subscribes native SDK events stream and forwards events to JS via DeviceEventEmitter. Calling
352
+ * from JS multiple times replaces handler on JS side (native always emits to the same event
353
+ * name).
557
354
  */
558
355
  override fun subscribeToEvents() {
559
356
  Events.subscribe { event -> sendEventToJs(event) }
560
357
  }
561
358
 
562
- /**
563
- * Unsubscribes from SDK event stream.
564
- *
565
- * This stops forwarding events to JS.
566
- */
359
+ /** Unsubscribes native SDK events stream. */
567
360
  override fun unsubscribeFromEvent() {
568
361
  Events.unsubscribe()
569
362
  }
570
363
 
571
- /**
572
- * Converts SDK event model to React Native friendly payload and emits it to JS.
573
- *
574
- * Payload schema:
575
- * - function: String
576
- * - code: Int? (nullable)
577
- * - message: String
578
- * - value: Map<String, Any?>? (nullable)
579
- * - type: "event" | "error" | "retryError"
580
- */
581
364
  private fun sendEventToJs(event: DataClasses.Event) {
582
365
  val eventMap = Arguments.createMap()
583
- eventMap.putString("function", event.function)
366
+ eventMap.putString(RnConstants.KEY_FUNCTION, event.function)
584
367
 
585
368
  val code = event.eventCode
586
- if (code != null) {
587
- eventMap.putInt("code", code)
588
- } else {
589
- eventMap.putNull("code")
590
- }
369
+ if (code != null) eventMap.putInt(RnConstants.KEY_CODE, code)
370
+ else eventMap.putNull(RnConstants.KEY_CODE)
591
371
 
592
372
  val message = event.eventMessage ?: event.toString()
593
- eventMap.putString("message", message)
373
+ eventMap.putString(RnConstants.KEY_MESSAGE, message)
594
374
 
595
375
  val value = event.eventValue
596
376
  if (value != null) {
@@ -607,447 +387,354 @@ class SdkModule(
607
387
  else -> valueMap.putString(key, anyValue.toString())
608
388
  }
609
389
  }
610
- eventMap.putMap("value", valueMap)
390
+ eventMap.putMap(RnConstants.KEY_VALUE, valueMap)
611
391
  } else {
612
- eventMap.putNull("value")
392
+ eventMap.putNull(RnConstants.KEY_VALUE)
613
393
  }
614
-
615
- val type = when (event) {
616
- is DataClasses.Error -> "error"
617
- is DataClasses.RetryError -> "retryError"
618
- else -> "event"
619
- }
620
- eventMap.putString("type", type)
394
+ val type =
395
+ when (event) {
396
+ is DataClasses.Error -> RnConstants.TYPE_ERROR
397
+ is DataClasses.RetryError -> RnConstants.TYPE_RETRY_ERROR
398
+ else -> RnConstants.TYPE_EVENT
399
+ }
400
+ eventMap.putString(RnConstants.KEY_TYPE, type)
621
401
 
622
402
  reactApplicationContext
623
- .getJSModule(RCTDeviceEventEmitter::class.java)
624
- .emit("AltcraftSdkEvent", eventMap)
625
- }
626
-
627
- // --------------------- utils ---------------------
628
-
629
- /**
630
- * Converts [ReadableMap] into Kotlin Map or returns null for empty input.
631
- */
632
- private fun ReadableMap?.toMapOrNull(): Map<String, Any?>? {
633
- if (this == null) return null
634
- val hash = this.toHashMap()
635
- return if (hash.isEmpty()) null else hash.toMap()
636
- }
637
-
638
- /**
639
- * Converts RN array of category objects into SDK category list.
640
- *
641
- * Returns null for:
642
- * - null input
643
- * - empty input
644
- * - when all items are invalid
645
- */
646
- private fun ReadableArray?.toCategoryListOrNull(): List<DataClasses.CategoryData>? {
647
- if (this == null || this.size() == 0) return null
648
-
649
- val result = mutableListOf<DataClasses.CategoryData>()
650
- for (i in 0 until this.size()) {
651
- val item = this.getMap(i) ?: continue
652
-
653
- val name = if (item.hasKey("name") && !item.isNull("name")) item.getString("name") else null
654
- val title = if (item.hasKey("title") && !item.isNull("title")) item.getString("title") else null
655
- val steady = if (item.hasKey("steady") && !item.isNull("steady")) item.getBoolean("steady") else null
656
- val active = if (item.hasKey("active") && !item.isNull("active")) item.getBoolean("active") else null
657
-
658
- result.add(
659
- DataClasses.CategoryData(
660
- name = name,
661
- title = title,
662
- steady = steady,
663
- active = active
664
- )
665
- )
666
- }
667
-
668
- return if (result.isEmpty()) null else result
669
- }
670
-
671
- /**
672
- * Converts RN string array into Kotlin list.
673
- *
674
- * Returns empty list for null/empty input.
675
- */
676
- private fun ReadableArray?.toStringList(): List<String> {
677
- if (this == null || this.size() == 0) return emptyList()
678
-
679
- val res = mutableListOf<String>()
680
- for (i in 0 until this.size()) {
681
- if (!this.isNull(i)) {
682
- val v = this.getString(i)
683
- if (v != null) res.add(v)
684
- }
685
- }
686
- return res
687
- }
688
-
689
- /**
690
- * Converts RN map into Map<String, String>.
691
- *
692
- * - Skips null values and non-string values (ReadableMap.getString returns null).
693
- * - Returns null if map is null or results in empty output.
694
- */
695
- private fun ReadableMap?.toStringMapOrNull(): Map<String, String>? {
696
- if (this == null) return null
697
- val iterator = this.keySetIterator()
698
- if (!iterator.hasNextKey()) return null
699
-
700
- val result = mutableMapOf<String, String>()
701
- while (iterator.hasNextKey()) {
702
- val key = iterator.nextKey()
703
- if (this.isNull(key)) continue
704
- val value = this.getString(key)
705
- if (value != null) {
706
- result[key] = value
707
- }
708
- }
709
-
710
- return if (result.isEmpty()) null else result.toMap()
403
+ .getJSModule(RCTDeviceEventEmitter::class.java)
404
+ .emit(RnConstants.JS_EVENT_NAME, eventMap)
711
405
  }
712
406
 
713
407
  // --------------------- subscription bridge ---------------------
714
408
 
715
409
  /**
716
- * Subscribes device/profile for push notifications.
410
+ * Sends a push subscribe request.
717
411
  *
718
- * Params:
719
- * - [sync] — if true, performs sync behavior according to SDK rules (defaults to true).
720
- * - [profileFields] — profile fields for subscription.
721
- * - [customFields] — custom fields for subscription.
722
- * - [cats] — categories array.
723
- * - [replace] — replace existing fields/categories (SDK-specific).
724
- * - [skipTriggers] — skip triggers (SDK-specific).
412
+ * @param sync Execution mode:
413
+ * ```
414
+ * `true` — synchronous server request returning the operation result.
415
+ * `false` — asynchronous server request returning enqueue result.
416
+ * `null` — defaults to `true` on Android bridge.
417
+ * @param profileFields
418
+ * ```
419
+ * Optional profile fields (string-only map).
420
+ * @param customFields Optional custom fields (string-only map).
421
+ * @param cats Optional categories list.
422
+ * @param replace Optional flag to replace an existing subscription.
423
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
725
424
  */
726
425
  override fun pushSubscribe(
727
- sync: Boolean?,
728
- profileFields: ReadableMap?,
729
- customFields: ReadableMap?,
730
- cats: ReadableArray?,
731
- replace: Boolean?,
732
- skipTriggers: Boolean?
426
+ sync: Boolean?,
427
+ profileFields: ReadableMap?,
428
+ customFields: ReadableMap?,
429
+ cats: ReadableArray?,
430
+ replace: Boolean?,
431
+ skipTriggers: Boolean?
733
432
  ) {
734
433
  val isSync = sync ?: true
735
434
  PublicPushSubscriptionFunctions.pushSubscribe(
736
- context = reactApplicationContext,
737
- sync = isSync,
738
- profileFields = profileFields.toMapOrNull(),
739
- customFields = customFields.toMapOrNull(),
740
- cats = cats.toCategoryListOrNull(),
741
- replace = replace,
742
- skipTriggers = skipTriggers
435
+ context = reactApplicationContext,
436
+ sync = isSync,
437
+ profileFields = Converter.toKotlinMap(profileFields),
438
+ customFields = Converter.toKotlinMap(customFields),
439
+ cats = Converter.toCategoryListOrNull(cats),
440
+ replace = replace,
441
+ skipTriggers = skipTriggers
743
442
  )
744
443
  }
745
444
 
746
445
  /**
747
- * Suspends current push subscription (temporarily disables).
446
+ * Sends a push suspend request.
748
447
  *
749
- * Params are equivalent to [pushSubscribe].
448
+ * @param sync Execution mode (see [pushSubscribe]).
449
+ * @param profileFields Optional profile fields (string-only map).
450
+ * @param customFields Optional custom fields (string-only map).
451
+ * @param cats Optional categories list.
452
+ * @param replace Optional flag to replace an existing subscription.
453
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
750
454
  */
751
455
  override fun pushSuspend(
752
- sync: Boolean?,
753
- profileFields: ReadableMap?,
754
- customFields: ReadableMap?,
755
- cats: ReadableArray?,
756
- replace: Boolean?,
757
- skipTriggers: Boolean?
456
+ sync: Boolean?,
457
+ profileFields: ReadableMap?,
458
+ customFields: ReadableMap?,
459
+ cats: ReadableArray?,
460
+ replace: Boolean?,
461
+ skipTriggers: Boolean?
758
462
  ) {
759
463
  val isSync = sync ?: true
760
464
  PublicPushSubscriptionFunctions.pushSuspend(
761
- context = reactApplicationContext,
762
- sync = isSync,
763
- profileFields = profileFields.toMapOrNull(),
764
- customFields = customFields.toMapOrNull(),
765
- cats = cats.toCategoryListOrNull(),
766
- replace = replace,
767
- skipTriggers = skipTriggers
465
+ context = reactApplicationContext,
466
+ sync = isSync,
467
+ profileFields = Converter.toKotlinMap(profileFields),
468
+ customFields = Converter.toKotlinMap(customFields),
469
+ cats = Converter.toCategoryListOrNull(cats),
470
+ replace = replace,
471
+ skipTriggers = skipTriggers
768
472
  )
769
473
  }
770
474
 
771
475
  /**
772
- * Unsubscribes (disables) current push subscription.
476
+ * Sends a push unsubscribe request.
773
477
  *
774
- * Params are equivalent to [pushSubscribe].
478
+ * @param sync Execution mode (see [pushSubscribe]).
479
+ * @param profileFields Optional profile fields (string-only map).
480
+ * @param customFields Optional custom fields (string-only map).
481
+ * @param cats Optional categories list.
482
+ * @param replace Optional flag to replace an existing subscription.
483
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
775
484
  */
776
485
  override fun pushUnSubscribe(
777
- sync: Boolean?,
778
- profileFields: ReadableMap?,
779
- customFields: ReadableMap?,
780
- cats: ReadableArray?,
781
- replace: Boolean?,
782
- skipTriggers: Boolean?
486
+ sync: Boolean?,
487
+ profileFields: ReadableMap?,
488
+ customFields: ReadableMap?,
489
+ cats: ReadableArray?,
490
+ replace: Boolean?,
491
+ skipTriggers: Boolean?
783
492
  ) {
784
493
  val isSync = sync ?: true
785
494
  PublicPushSubscriptionFunctions.pushUnSubscribe(
786
- context = reactApplicationContext,
787
- sync = isSync,
788
- profileFields = profileFields.toMapOrNull(),
789
- customFields = customFields.toMapOrNull(),
790
- cats = cats.toCategoryListOrNull(),
791
- replace = replace,
792
- skipTriggers = skipTriggers
495
+ context = reactApplicationContext,
496
+ sync = isSync,
497
+ profileFields = Converter.toKotlinMap(profileFields),
498
+ customFields = Converter.toKotlinMap(customFields),
499
+ cats = Converter.toCategoryListOrNull(cats),
500
+ replace = replace,
501
+ skipTriggers = skipTriggers
793
502
  )
794
503
  }
795
504
 
796
505
  // --------------------- async status bridges ---------------------
797
506
 
798
507
  /**
799
- * Tries to un-suspend push subscription (async request to backend).
508
+ * Unsuspends push subscriptions based on native matching rules.
800
509
  *
801
- * Promise:
802
- * - resolves ResponseWithHttpCode mapped to JS object:
803
- * { httpCode: number|null, response: { ... } | null }
804
- * - resolves null if SDK returned null
805
- * - rejects on unexpected errors
510
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
806
511
  */
807
512
  override fun unSuspendPushSubscription(promise: Promise) {
808
513
  coroutineScope.launch {
809
514
  try {
810
- val res = PublicPushSubscriptionFunctions.unSuspendPushSubscription(
811
- reactApplicationContext
812
- )
515
+ val res =
516
+ PublicPushSubscriptionFunctions.unSuspendPushSubscription(
517
+ reactApplicationContext
518
+ )
813
519
  promise.resolve(responseWithHttpCodeToWritableMap(res))
814
520
  } catch (e: Exception) {
815
- promise.reject("unSuspendPushSubscription", e)
521
+ promise.reject(RnConstants.ERR_UNSUSPEND, e)
816
522
  }
817
523
  }
818
524
  }
819
525
 
820
526
  /**
821
- * Returns status of the latest subscription operation (async).
527
+ * Returns the status of the latest subscription in profile.
822
528
  *
823
- * Promise:
824
- * - resolves mapped ResponseWithHttpCode or null
825
- * - rejects on unexpected errors
529
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
826
530
  */
827
531
  override fun getStatusOfLatestSubscription(promise: Promise) {
828
532
  coroutineScope.launch {
829
533
  try {
830
- val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
831
- reactApplicationContext
832
- )
534
+ val res =
535
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
536
+ reactApplicationContext
537
+ )
833
538
  promise.resolve(responseWithHttpCodeToWritableMap(res))
834
539
  } catch (e: Exception) {
835
- promise.reject("getStatusOfLatestSubscription", e)
540
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS, e)
836
541
  }
837
542
  }
838
543
  }
839
544
 
840
545
  /**
841
- * Returns status of the latest subscription operation for a specific [provider] (async).
546
+ * Returns the status of the latest subscription for the given provider.
842
547
  *
843
- * Promise:
844
- * - resolves mapped ResponseWithHttpCode or null
845
- * - rejects on unexpected errors
548
+ * @param provider Optional provider identifier (may be null).
549
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
846
550
  */
847
- override fun getStatusOfLatestSubscriptionForProvider(
848
- provider: String?,
849
- promise: Promise
850
- ) {
551
+ override fun getStatusOfLatestSubscriptionForProvider(provider: String?, promise: Promise) {
851
552
  coroutineScope.launch {
852
553
  try {
853
- val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
854
- context = reactApplicationContext,
855
- provider = provider
856
- )
554
+ val res =
555
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
556
+ context = reactApplicationContext,
557
+ provider = provider
558
+ )
857
559
  promise.resolve(responseWithHttpCodeToWritableMap(res))
858
560
  } catch (e: Exception) {
859
- promise.reject("getStatusOfLatestSubscriptionForProvider", e)
561
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS_PROVIDER, e)
860
562
  }
861
563
  }
862
564
  }
863
565
 
864
566
  /**
865
- * Returns status for current subscription (async).
567
+ * Returns the status for current subscription (by current provider/token context).
866
568
  *
867
- * Promise:
868
- * - resolves mapped ResponseWithHttpCode or null
869
- * - rejects on unexpected errors
569
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
870
570
  */
871
571
  override fun getStatusForCurrentSubscription(promise: Promise) {
872
572
  coroutineScope.launch {
873
573
  try {
874
- val res = PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
875
- reactApplicationContext
876
- )
574
+ val res =
575
+ PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
576
+ reactApplicationContext
577
+ )
877
578
  promise.resolve(responseWithHttpCodeToWritableMap(res))
878
579
  } catch (e: Exception) {
879
- promise.reject("getStatusForCurrentSubscription", e)
580
+ promise.reject(RnConstants.ERR_GET_CURRENT_STATUS, e)
880
581
  }
881
582
  }
882
583
  }
883
584
 
884
585
  /**
885
- * Maps SDK [DataClasses.ResponseWithHttpCode] into a JS-friendly [WritableMap].
886
- *
887
- * Output schema:
888
- * - httpCode: Int?
889
- * - response: {
890
- * error: Int?,
891
- * errorText: String?,
892
- * profile: {
893
- * id: String?,
894
- * status: String?,
895
- * isTest: Boolean?,
896
- * subscription: {
897
- * subscriptionId: String?,
898
- * hashId: String?,
899
- * provider: String?,
900
- * status: String?,
901
- * fields: null,
902
- * cats: null
903
- * } | null
904
- * } | null
905
- * } | null
586
+ * Maps {@link DataClasses.ResponseWithHttpCode} to a RN {@link WritableMap}. Returns `null` if
587
+ * input is `null`. Unmapped fields (`fields`, `cats`) are set to `null`.
906
588
  */
907
589
  private fun responseWithHttpCodeToWritableMap(
908
- data: DataClasses.ResponseWithHttpCode?
590
+ data: DataClasses.ResponseWithHttpCode?
909
591
  ): WritableMap? {
910
592
  if (data == null) return null
911
593
 
912
- val root = Arguments.createMap()
913
-
914
- val httpCode = data.httpCode
915
- if (httpCode != null) {
916
- root.putInt("httpCode", httpCode)
917
- } else {
918
- root.putNull("httpCode")
919
- }
920
-
921
594
  val resp = data.response
922
- if (resp == null) {
923
- root.putNull("response")
924
- return root
925
- }
926
595
 
927
- val respMap = Arguments.createMap()
596
+ return Arguments.createMap().apply root@{
597
+ putNullableInt(RnConstants.KEY_HTTP_CODE, data.httpCode)
928
598
 
929
- val error = resp.error
930
- if (error != null) {
931
- respMap.putInt("error", error)
932
- } else {
933
- respMap.putNull("error")
934
- }
599
+ if (resp == null) {
600
+ putNull(RnConstants.KEY_RESPONSE)
601
+ return@root
602
+ }
935
603
 
936
- val errorText = resp.errorText
937
- if (errorText != null) {
938
- respMap.putString("errorText", errorText)
939
- } else {
940
- respMap.putNull("errorText")
941
- }
604
+ val respMap =
605
+ Arguments.createMap().apply resp@{
606
+ putNullableInt(RnConstants.KEY_ERROR, resp.error)
607
+ putNullableString(RnConstants.KEY_ERROR_TEXT, resp.errorText)
942
608
 
943
- val profile = resp.profile
944
- if (profile == null) {
945
- respMap.putNull("profile")
946
- } else {
947
- val profileMap = Arguments.createMap()
609
+ val profile = resp.profile
610
+ if (profile == null) {
611
+ putNull(RnConstants.KEY_PROFILE)
612
+ return@resp
613
+ }
948
614
 
949
- val profileId = profile.id
950
- if (profileId != null) {
951
- profileMap.putString("id", profileId)
952
- } else {
953
- profileMap.putNull("id")
954
- }
615
+ val profileMap =
616
+ Arguments.createMap().apply profile@{
617
+ putNullableString(RnConstants.KEY_ID, profile.id)
618
+ putNullableString(RnConstants.KEY_STATUS, profile.status)
619
+ putNullableBoolean(RnConstants.KEY_IS_TEST, profile.isTest)
620
+
621
+ val sub = profile.subscription
622
+ if (sub == null) {
623
+ putNull(RnConstants.KEY_SUBSCRIPTION)
624
+ return@profile
625
+ }
626
+
627
+ val subMap =
628
+ Arguments.createMap().apply sub@{
629
+ putNullableString(
630
+ RnConstants.KEY_SUBSCRIPTION_ID,
631
+ sub.subscriptionId
632
+ )
633
+ putNullableString(
634
+ RnConstants.KEY_HASH_ID,
635
+ sub.hashId
636
+ )
637
+ putNullableString(
638
+ RnConstants.KEY_PROVIDER,
639
+ sub.provider
640
+ )
641
+ putNullableString(
642
+ RnConstants.KEY_STATUS,
643
+ sub.status
644
+ )
645
+
646
+ putNull(RnConstants.KEY_FIELDS)
647
+ putNull(RnConstants.KEY_CATS)
648
+ }
649
+
650
+ putMap(RnConstants.KEY_SUBSCRIPTION, subMap)
651
+ }
652
+
653
+ putMap(RnConstants.KEY_PROFILE, profileMap)
654
+ }
955
655
 
956
- val status = profile.status
957
- if (status != null) {
958
- profileMap.putString("status", status)
959
- } else {
960
- profileMap.putNull("status")
961
- }
656
+ putMap(RnConstants.KEY_RESPONSE, respMap)
657
+ }
658
+ }
962
659
 
963
- val isTest = profile.isTest
964
- if (isTest != null) {
965
- profileMap.putBoolean("isTest", isTest)
966
- } else {
967
- profileMap.putNull("isTest")
968
- }
660
+ /**
661
+ * Stores a key-value pair in native persistent storage.
662
+ *
663
+ * Platform behavior:
664
+ * - iOS: uses UserDefaults (optionally scoped by `suiteName` / App Group).
665
+ * - Android: uses SharedPreferences; `suiteName` is used as preferences name.
666
+ *
667
+ * Supported value types:
668
+ * - primitives (Boolean, Number, String)
669
+ * - complex structures serialized as JSON string
670
+ * - `null` removes the stored value
671
+ *
672
+ * @param suiteName Storage namespace / suite name (platform-dependent).
673
+ * @param key Storage key.
674
+ * @param value Value to store or `null` to remove.
675
+ */
676
+ override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
677
+ val k = key.trim()
678
+ if (k.isEmpty()) return
969
679
 
970
- val sub = profile.subscription
971
- if (sub == null) {
972
- profileMap.putNull("subscription")
973
- } else {
974
- val subMap = Arguments.createMap()
680
+ val prefsName =
681
+ suiteName?.trim().takeUnless { it.isNullOrEmpty() }
682
+ ?: reactApplicationContext.packageName
975
683
 
976
- val subscriptionId = sub.subscriptionId
977
- if (subscriptionId != null) {
978
- subMap.putString("subscriptionId", subscriptionId)
979
- } else {
980
- subMap.putNull("subscriptionId")
981
- }
684
+ val prefs =
685
+ reactApplicationContext.getSharedPreferences(
686
+ prefsName,
687
+ android.content.Context.MODE_PRIVATE
688
+ )
982
689
 
983
- val hashId = sub.hashId
984
- if (hashId != null) {
985
- subMap.putString("hashId", hashId)
986
- } else {
987
- subMap.putNull("hashId")
988
- }
690
+ if (value == null) {
691
+ prefs.edit().remove(k).apply()
692
+ return
693
+ }
989
694
 
990
- val provider = sub.provider
991
- if (provider != null) {
992
- subMap.putString("provider", provider)
993
- } else {
994
- subMap.putNull("provider")
995
- }
695
+ val v = value.trim()
996
696
 
997
- val subStatus = sub.status
998
- if (subStatus != null) {
999
- subMap.putString("status", subStatus)
1000
- } else {
1001
- subMap.putNull("status")
1002
- }
697
+ // Store JSON as String (SharedPreferences has no native JSON type)
698
+ if ((v.startsWith("{") && v.endsWith("}")) || (v.startsWith("[") && v.endsWith("]"))) {
699
+ prefs.edit().putString(k, v).apply()
700
+ return
701
+ }
1003
702
 
1004
- // Kept as is (reserved for future schema extension).
1005
- subMap.putNull("fields")
1006
- subMap.putNull("cats")
703
+ // Boolean
704
+ if (v.equals("true", ignoreCase = true) || v.equals("false", ignoreCase = true)) {
705
+ prefs.edit().putBoolean(k, v.equals("true", ignoreCase = true)).apply()
706
+ return
707
+ }
1007
708
 
1008
- profileMap.putMap("subscription", subMap)
1009
- }
709
+ // Integer (Long)
710
+ v.toLongOrNull()?.let { asLong ->
711
+ prefs.edit().putLong(k, asLong).apply()
712
+ return
713
+ }
1010
714
 
1011
- respMap.putMap("profile", profileMap)
715
+ // Double -> keep precision as String
716
+ v.toDoubleOrNull()?.let {
717
+ prefs.edit().putString(k, v).apply()
718
+ return
1012
719
  }
1013
720
 
1014
- root.putMap("response", respMap)
1015
- return root
721
+ // Fallback: String
722
+ prefs.edit().putString(k, value).apply()
1016
723
  }
1017
724
 
1018
725
  companion object {
1019
- const val NAME: String = "Sdk"
726
+ const val NAME: String = RnConstants.MODULE_NAME
1020
727
  }
1021
728
  }
1022
729
 
1023
- /**
1024
- * Internal RN initializer entry point.
1025
- *
1026
- * Converts RN config -> [AltcraftConfiguration] and performs [AltcraftSDK.initialization].
1027
- * All errors are mapped into RN Promise rejections with stable error codes.
1028
- */
730
+ /** Internal RN initializer entry point. */
1029
731
  internal object AltcraftRnInitializer {
1030
732
 
1031
- /**
1032
- * Initializes Altcraft SDK with mapped configuration.
1033
- *
1034
- * Promise contract:
1035
- * - resolve(null) on success
1036
- * - reject("ALTCRAFT_INIT_INVALID_CONFIG", ...) if config mapping failed
1037
- * - reject("ALTCRAFT_INIT_ERROR", ...) if SDK init failed
1038
- */
1039
- fun initialize(
1040
- reactContext: ReactApplicationContext,
1041
- config: ReadableMap,
1042
- promise: Promise
1043
- ) {
733
+ fun initialize(reactContext: ReactApplicationContext, config: ReadableMap, promise: Promise) {
1044
734
  try {
1045
735
  val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
1046
736
 
1047
- AltcraftSDK.initialization(
1048
- reactContext,
1049
- configuration
1050
- ) { result ->
737
+ AltcraftSDK.initialization(reactContext, configuration) { result ->
1051
738
  reactContext.runOnUiQueueThread {
1052
739
  if (result.isSuccess) {
1053
740
  promise.resolve(null)
@@ -1055,188 +742,98 @@ internal object AltcraftRnInitializer {
1055
742
  val throwable = result.exceptionOrNull()
1056
743
  if (throwable != null) {
1057
744
  promise.reject(
1058
- "ALTCRAFT_INIT_ERROR",
1059
- throwable.message ?: "Altcraft initialization error",
1060
- throwable
745
+ RnConstants.ERR_INIT_ERROR,
746
+ throwable.message ?: RnConstants.MSG_INIT_ERROR,
747
+ throwable
1061
748
  )
1062
749
  } else {
1063
- promise.reject(
1064
- "ALTCRAFT_INIT_ERROR",
1065
- "Altcraft initialization failed with unknown error"
1066
- )
750
+ promise.reject(RnConstants.ERR_INIT_ERROR, RnConstants.MSG_INIT_UNKNOWN)
1067
751
  }
1068
752
  }
1069
753
  }
1070
754
  }
1071
755
  } catch (e: Exception) {
1072
756
  promise.reject(
1073
- "ALTCRAFT_INIT_INVALID_CONFIG",
1074
- e.message ?: "Invalid Altcraft configuration",
1075
- e
757
+ RnConstants.ERR_INIT_INVALID_CONFIG,
758
+ e.message ?: "Invalid Altcraft configuration",
759
+ e
1076
760
  )
1077
761
  }
1078
762
  }
1079
763
  }
1080
764
 
1081
- /**
1082
- * Maps React Native configuration object to native [AltcraftConfiguration].
1083
- *
1084
- * Notes:
1085
- * - `apiUrl` is required.
1086
- * - `enableLogging` is nullable to keep SDK default behavior when not provided.
1087
- * - android-only keys are prefixed with `android_*` so iOS can safely ignore them.
1088
- */
765
+ /** Maps React Native configuration object to native [AltcraftConfiguration]. */
1089
766
  internal object AltcraftRnConfigMapper {
1090
767
 
1091
- /**
1092
- * Builds native SDK configuration from RN map.
1093
- *
1094
- * @throws IllegalArgumentException if required fields are missing or invalid.
1095
- */
1096
- fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
1097
- if (!config.hasKey("apiUrl") || config.isNull("apiUrl")) {
1098
- throw IllegalArgumentException("apiUrl is required for AltcraftConfiguration")
1099
- }
768
+ private const val KEY_API_URL = "apiUrl"
769
+ private const val KEY_R_TOKEN = "rToken"
770
+ private const val KEY_APP_INFO = "appInfo"
771
+ private const val KEY_PROVIDER_PRIORITY_LIST = "providerPriorityList"
772
+ private const val KEY_ENABLE_LOGGING = "enableLogging"
1100
773
 
1101
- val apiUrl = config.getString("apiUrl")
1102
- ?: throw IllegalArgumentException("apiUrl must be a non-null string")
774
+ private const val KEY_ANDROID_ICON = "android_icon"
775
+ private const val KEY_ANDROID_USING_SERVICE = "android_usingService"
776
+ private const val KEY_ANDROID_SERVICE_MESSAGE = "android_serviceMessage"
777
+ private const val KEY_ANDROID_PUSH_RECEIVER_MODULES = "android_pushReceiverModules"
778
+ private const val KEY_ANDROID_PUSH_CHANNEL_NAME = "android_pushChannelName"
779
+ private const val KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION = "android_pushChannelDescription"
1103
780
 
1104
- // ---------------- COMMON ----------------
781
+ private const val KEY_APP_ID = "appID"
782
+ private const val KEY_APP_IID = "appIID"
783
+ private const val KEY_APP_VER = "appVer"
1105
784
 
1106
- val rToken: String? =
1107
- if (config.hasKey("rToken") && !config.isNull("rToken")) {
1108
- config.getString("rToken")
1109
- } else {
1110
- null
1111
- }
785
+ private const val MSG_API_URL_REQUIRED = "apiUrl is required for AltcraftConfiguration"
786
+ private const val MSG_API_URL_MUST_BE_STRING = "apiUrl must be a non-null string"
1112
787
 
1113
- val appInfo: DataClasses.AppInfo? =
1114
- if (config.hasKey("appInfo") && !config.isNull("appInfo")) {
1115
- val appInfoMap = config.getMap("appInfo")
1116
- if (appInfoMap == null) {
1117
- null
1118
- } else {
1119
- val appID =
1120
- if (appInfoMap.hasKey("appID") && !appInfoMap.isNull("appID")) {
1121
- appInfoMap.getString("appID") ?: ""
1122
- } else {
1123
- ""
1124
- }
788
+ fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
789
+ if (!config.hasNonNullKey(KEY_API_URL)) {
790
+ throw IllegalArgumentException(MSG_API_URL_REQUIRED)
791
+ }
1125
792
 
1126
- val appIID =
1127
- if (appInfoMap.hasKey("appIID") && !appInfoMap.isNull("appIID")) {
1128
- appInfoMap.getString("appIID") ?: ""
1129
- } else {
1130
- ""
1131
- }
793
+ val apiUrl =
794
+ config.getString(KEY_API_URL)
795
+ ?: throw IllegalArgumentException(MSG_API_URL_MUST_BE_STRING)
1132
796
 
1133
- val appVer =
1134
- if (appInfoMap.hasKey("appVer") && !appInfoMap.isNull("appVer")) {
1135
- appInfoMap.getString("appVer") ?: ""
1136
- } else {
1137
- ""
1138
- }
797
+ val rToken = config.getStringOrNull(KEY_R_TOKEN)
1139
798
 
1140
- DataClasses.AppInfo(
1141
- appID = appID,
1142
- appIID = appIID,
1143
- appVer = appVer
1144
- )
799
+ val appInfo =
800
+ config.getMapOrNull(KEY_APP_INFO)?.let { appInfoMap ->
801
+ val appID = appInfoMap.getStringOrNull(KEY_APP_ID) ?: ""
802
+ val appIID = appInfoMap.getStringOrNull(KEY_APP_IID) ?: ""
803
+ val appVer = appInfoMap.getStringOrNull(KEY_APP_VER) ?: ""
804
+ DataClasses.AppInfo(appID = appID, appIID = appIID, appVer = appVer)
1145
805
  }
1146
- } else {
1147
- null
1148
- }
1149
806
 
1150
- val providerPriorityList: List<String>? =
1151
- if (config.hasKey("providerPriorityList") && !config.isNull("providerPriorityList")) {
1152
- val array = config.getArray("providerPriorityList")
1153
- if (array == null) null else readableStringArrayToList(array)
1154
- } else {
1155
- null
1156
- }
807
+ val providerPriorityList = config.getArrayOrNull(KEY_PROVIDER_PRIORITY_LIST)?.toStringList()
1157
808
 
1158
- val enableLogging: Boolean? =
1159
- if (config.hasKey("enableLogging") && !config.isNull("enableLogging")) {
1160
- config.getBoolean("enableLogging")
1161
- } else {
1162
- null
1163
- }
809
+ val enableLogging = config.getBooleanOrNull(KEY_ENABLE_LOGGING)
1164
810
 
1165
- // ---------------- ANDROID-ONLY ----------------
811
+ val icon = config.getIntOrNull(KEY_ANDROID_ICON)
1166
812
 
1167
- val icon: Int? =
1168
- if (config.hasKey("android_icon") && !config.isNull("android_icon")) {
1169
- config.getInt("android_icon")
1170
- } else {
1171
- null
1172
- }
813
+ val usingService = config.getBooleanOrNull(KEY_ANDROID_USING_SERVICE) ?: false
1173
814
 
1174
- val usingService: Boolean =
1175
- if (config.hasKey("android_usingService") && !config.isNull("android_usingService")) {
1176
- config.getBoolean("android_usingService")
1177
- } else {
1178
- false
1179
- }
815
+ val serviceMessage = config.getStringOrNull(KEY_ANDROID_SERVICE_MESSAGE)
1180
816
 
1181
- val serviceMessage: String? =
1182
- if (config.hasKey("android_serviceMessage") && !config.isNull("android_serviceMessage")) {
1183
- config.getString("android_serviceMessage")
1184
- } else {
1185
- null
1186
- }
817
+ val pushReceiverModules =
818
+ config.getArrayOrNull(KEY_ANDROID_PUSH_RECEIVER_MODULES)?.toStringList()
1187
819
 
1188
- val pushReceiverModules: List<String>? =
1189
- if (config.hasKey("android_pushReceiverModules") && !config.isNull("android_pushReceiverModules")) {
1190
- val array = config.getArray("android_pushReceiverModules")
1191
- if (array == null) null else readableStringArrayToList(array)
1192
- } else {
1193
- null
1194
- }
820
+ val pushChannelName = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_NAME)
1195
821
 
1196
- val pushChannelName: String? =
1197
- if (config.hasKey("android_pushChannelName") && !config.isNull("android_pushChannelName")) {
1198
- config.getString("android_pushChannelName")
1199
- } else {
1200
- null
1201
- }
1202
-
1203
- val pushChannelDescription: String? =
1204
- if (config.hasKey("android_pushChannelDescription") && !config.isNull("android_pushChannelDescription")) {
1205
- config.getString("android_pushChannelDescription")
1206
- } else {
1207
- null
1208
- }
822
+ val pushChannelDescription = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION)
1209
823
 
1210
824
  return AltcraftConfiguration.Builder(
1211
- apiUrl = apiUrl,
1212
- icon = icon,
1213
- rToken = rToken,
1214
- usingService = usingService,
1215
- serviceMessage = serviceMessage,
1216
- appInfo = appInfo,
1217
- providerPriorityList = providerPriorityList,
1218
- pushReceiverModules = pushReceiverModules,
1219
- pushChannelName = pushChannelName,
1220
- pushChannelDescription = pushChannelDescription,
1221
- enableLogging = enableLogging
1222
- ).build()
1223
- }
1224
-
1225
- /**
1226
- * Converts RN string array into Kotlin list of strings.
1227
- *
1228
- * Skips null elements.
1229
- */
1230
- private fun readableStringArrayToList(array: ReadableArray): List<String> {
1231
- val result = ArrayList<String>()
1232
- for (i in 0 until array.size()) {
1233
- if (!array.isNull(i)) {
1234
- val value = array.getString(i)
1235
- if (value != null) {
1236
- result.add(value)
1237
- }
1238
- }
1239
- }
1240
- return result
825
+ apiUrl = apiUrl,
826
+ icon = icon,
827
+ rToken = rToken,
828
+ usingService = usingService,
829
+ serviceMessage = serviceMessage,
830
+ appInfo = appInfo,
831
+ providerPriorityList = providerPriorityList,
832
+ pushReceiverModules = pushReceiverModules,
833
+ pushChannelName = pushChannelName,
834
+ pushChannelDescription = pushChannelDescription,
835
+ enableLogging = enableLogging
836
+ )
837
+ .build()
1241
838
  }
1242
- }
839
+ }