@altcraft/react-native-sdk 0.0.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 (33) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +46 -0
  3. package/Sdk.podspec +48 -0
  4. package/android/build.gradle +78 -0
  5. package/android/gradle.properties +5 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +1242 -0
  8. package/android/src/main/java/com/altcraft/sdk/SdkPackage.kt +33 -0
  9. package/android/src/main/java/com/altcraft/sdk/interfaces/RnFCMProvider.kt +27 -0
  10. package/android/src/main/java/com/altcraft/sdk/interfaces/RnHMSProvider.kt +32 -0
  11. package/android/src/main/java/com/altcraft/sdk/interfaces/RnJWTProvider.kt +21 -0
  12. package/android/src/main/java/com/altcraft/sdk/interfaces/RnRustoreProvider.kt +53 -0
  13. package/ios/Sdk.h +19 -0
  14. package/ios/Sdk.mm +1112 -0
  15. package/ios/SdkModule.swift +888 -0
  16. package/ios/protocols/RNAPNSProvider.swift +15 -0
  17. package/ios/protocols/RNFCMProvider.swift +24 -0
  18. package/ios/protocols/RNHMSProvider.swift +24 -0
  19. package/ios/protocols/RNJWTProvider.swift +15 -0
  20. package/lib/module/NativeSdk.js +13 -0
  21. package/lib/module/NativeSdk.js.map +1 -0
  22. package/lib/module/index.js +561 -0
  23. package/lib/module/index.js.map +1 -0
  24. package/lib/module/package.json +1 -0
  25. package/lib/typescript/package.json +1 -0
  26. package/lib/typescript/src/NativeSdk.d.ts +114 -0
  27. package/lib/typescript/src/NativeSdk.d.ts.map +1 -0
  28. package/lib/typescript/src/index.d.ts +391 -0
  29. package/lib/typescript/src/index.d.ts.map +1 -0
  30. package/package.json +128 -0
  31. package/react-native.config.js +10 -0
  32. package/src/NativeSdk.ts +171 -0
  33. package/src/index.tsx +670 -0
@@ -0,0 +1,1242 @@
1
+ package com.altcraft.sdk
2
+
3
+ import androidx.activity.ComponentActivity
4
+ import com.altcraft.sdk.AltcraftSDK
5
+ import com.altcraft.sdk.config.AltcraftConfiguration
6
+ import com.altcraft.sdk.data.DataClasses
7
+ import com.altcraft.sdk.mob_events.PublicMobileEventFunction
8
+ import com.altcraft.sdk.push.events.PublicPushEventFunctions
9
+ import com.altcraft.sdk.push.subscribe.PublicPushSubscriptionFunctions
10
+ 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
15
+ import com.altcraft.sdk.sdk_events.Events
16
+ import com.facebook.react.bridge.Arguments
17
+ import com.facebook.react.bridge.Promise
18
+ import com.facebook.react.bridge.ReactApplicationContext
19
+ import com.facebook.react.bridge.ReadableArray
20
+ import com.facebook.react.bridge.ReadableMap
21
+ import com.facebook.react.bridge.WritableMap
22
+ import com.facebook.react.bridge.UiThreadUtil
23
+ import com.facebook.react.module.annotations.ReactModule
24
+ import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
25
+ import kotlinx.coroutines.CoroutineScope
26
+ import kotlinx.coroutines.Dispatchers
27
+ import kotlinx.coroutines.SupervisorJob
28
+ import kotlinx.coroutines.launch
29
+
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
+ }
130
+
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
+ }
149
+
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
+ }
158
+
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
+ }
167
+
168
+ /**
169
+ * Sets RuStore token for Android push provider.
170
+ *
171
+ * If [token] is null/blank:
172
+ * - Clears provider state and unregisters provider from SDK.
173
+ *
174
+ * If [token] is provided:
175
+ * - Stores token and registers provider in SDK push token functions.
176
+ */
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
+ }
185
+ }
186
+
187
+ // ---------------------- required for NativeEventEmitter ----------------------
188
+
189
+ /**
190
+ * React Native requires this method when JS uses NativeEventEmitter.
191
+ *
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].
195
+ */
196
+ override fun addListener(eventName: String) {
197
+ // no-op
198
+ }
199
+
200
+ /**
201
+ * React Native requires this method when JS uses NativeEventEmitter.
202
+ *
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].
205
+ */
206
+ override fun removeListeners(count: Double) {
207
+ // no-op
208
+ }
209
+
210
+ // ---------------------- token-API for RN ----------------------
211
+
212
+ /**
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.
219
+ *
220
+ * Threading:
221
+ * - executed on IO dispatcher.
222
+ */
223
+ override fun getPushToken(promise: Promise) {
224
+ coroutineScope.launch {
225
+ try {
226
+ val tokenData = PublicPushTokenFunctions.getPushToken(reactApplicationContext)
227
+ if (tokenData == null) {
228
+ promise.resolve(null)
229
+ } else {
230
+ val map = Arguments.createMap()
231
+ map.putString("provider", tokenData.provider)
232
+ map.putString("token", tokenData.token)
233
+ promise.resolve(map)
234
+ }
235
+ } catch (e: Exception) {
236
+ promise.reject("getPushToken", e)
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
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.
251
+ *
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.
336
+ */
337
+ override fun setPushToken(provider: String, token: String?, promise: Promise) {
338
+ if (provider.isBlank()) {
339
+ promise.reject("setPushToken", "provider is blank")
340
+ return
341
+ }
342
+
343
+ coroutineScope.launch {
344
+ try {
345
+ if (token == null) {
346
+ PublicPushTokenFunctions.deleteDeviceToken(
347
+ context = reactApplicationContext,
348
+ provider = provider
349
+ )
350
+ promise.resolve(null)
351
+ return@launch
352
+ }
353
+
354
+ PublicPushTokenFunctions.setPushToken(
355
+ context = reactApplicationContext,
356
+ provider = provider,
357
+ token = token
358
+ )
359
+ promise.resolve(null)
360
+ } catch (e: Exception) {
361
+ promise.reject("setPushToken", e)
362
+ }
363
+ }
364
+ }
365
+
366
+ // ---------------------- AltcraftSDK: clear / retry / permission ----------------------
367
+
368
+ /**
369
+ * Clears SDK local state (tokens/subscriptions/cache depending on SDK implementation).
370
+ *
371
+ * Promise:
372
+ * - resolves `null` on success;
373
+ * - rejects on unexpected errors.
374
+ */
375
+ override fun clear(promise: Promise) {
376
+ try {
377
+ AltcraftSDK.clear(reactApplicationContext) {
378
+ promise.resolve(null)
379
+ }
380
+ } catch (e: Exception) {
381
+ promise.reject("clear", e)
382
+ }
383
+ }
384
+
385
+ /**
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.
409
+ */
410
+ override fun requestNotificationPermission() {
411
+ val activity = currentActivity
412
+ if (activity !is ComponentActivity) {
413
+ return
414
+ }
415
+ UiThreadUtil.runOnUiThread {
416
+ try {
417
+ AltcraftSDK.requestNotificationPermission(
418
+ reactApplicationContext,
419
+ activity
420
+ )
421
+ } catch (_: Exception) {
422
+ }
423
+ }
424
+ }
425
+
426
+ // ---------------------- MobileEvent bridge ----------------------
427
+
428
+ /**
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.
439
+ *
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.
443
+ */
444
+ override fun mobileEvent(
445
+ sid: String,
446
+ eventName: String,
447
+ sendMessageId: String?,
448
+ payload: ReadableMap?,
449
+ matching: ReadableMap?,
450
+ matchingType: String?,
451
+ profileFields: ReadableMap?
452
+ ) {
453
+ try {
454
+ 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
465
+ )
466
+ } catch (_: Exception) {
467
+ }
468
+ }
469
+
470
+ // ---------------------- push payload bridge ----------------------
471
+
472
+ /**
473
+ * Passes raw push payload to SDK for parsing/processing.
474
+ *
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.
481
+ */
482
+ override fun takePush(message: ReadableMap?) {
483
+ 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
+
497
+ if (map.isNotEmpty()) {
498
+ AltcraftSDK.PushReceiver.takePush(reactApplicationContext, map)
499
+ }
500
+ }
501
+
502
+ /**
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.
508
+ *
509
+ * Notes:
510
+ * - Exceptions are swallowed to avoid breaking JS flow.
511
+ */
512
+ override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
513
+ try {
514
+ val map = message.toStringMapOrNull()
515
+ PublicPushEventFunctions.deliveryEvent(
516
+ context = reactApplicationContext,
517
+ message = map,
518
+ messageUID = messageUID
519
+ )
520
+ } catch (_: Exception) {
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Sends push open event (SDK analytics/track).
526
+ *
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.
533
+ */
534
+ override fun openEvent(message: ReadableMap?, messageUID: String?) {
535
+ try {
536
+ val map = message.toStringMapOrNull()
537
+ PublicPushEventFunctions.openEvent(
538
+ context = reactApplicationContext,
539
+ message = map,
540
+ messageUID = messageUID
541
+ )
542
+ } catch (_: Exception) {
543
+ }
544
+ }
545
+
546
+ // --------------------- Events bridge for RN ---------------------
547
+
548
+ /**
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).
557
+ */
558
+ override fun subscribeToEvents() {
559
+ Events.subscribe { event -> sendEventToJs(event) }
560
+ }
561
+
562
+ /**
563
+ * Unsubscribes from SDK event stream.
564
+ *
565
+ * This stops forwarding events to JS.
566
+ */
567
+ override fun unsubscribeFromEvent() {
568
+ Events.unsubscribe()
569
+ }
570
+
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
+ private fun sendEventToJs(event: DataClasses.Event) {
582
+ val eventMap = Arguments.createMap()
583
+ eventMap.putString("function", event.function)
584
+
585
+ val code = event.eventCode
586
+ if (code != null) {
587
+ eventMap.putInt("code", code)
588
+ } else {
589
+ eventMap.putNull("code")
590
+ }
591
+
592
+ val message = event.eventMessage ?: event.toString()
593
+ eventMap.putString("message", message)
594
+
595
+ val value = event.eventValue
596
+ if (value != null) {
597
+ val valueMap = Arguments.createMap()
598
+ for ((key, anyValue) in value.entries) {
599
+ when (anyValue) {
600
+ null -> valueMap.putNull(key)
601
+ is String -> valueMap.putString(key, anyValue)
602
+ is Boolean -> valueMap.putBoolean(key, anyValue)
603
+ is Int -> valueMap.putInt(key, anyValue)
604
+ is Double -> valueMap.putDouble(key, anyValue)
605
+ is Float -> valueMap.putDouble(key, anyValue.toDouble())
606
+ is Long -> valueMap.putDouble(key, anyValue.toDouble())
607
+ else -> valueMap.putString(key, anyValue.toString())
608
+ }
609
+ }
610
+ eventMap.putMap("value", valueMap)
611
+ } else {
612
+ eventMap.putNull("value")
613
+ }
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)
621
+
622
+ 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()
711
+ }
712
+
713
+ // --------------------- subscription bridge ---------------------
714
+
715
+ /**
716
+ * Subscribes device/profile for push notifications.
717
+ *
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).
725
+ */
726
+ override fun pushSubscribe(
727
+ sync: Boolean?,
728
+ profileFields: ReadableMap?,
729
+ customFields: ReadableMap?,
730
+ cats: ReadableArray?,
731
+ replace: Boolean?,
732
+ skipTriggers: Boolean?
733
+ ) {
734
+ val isSync = sync ?: true
735
+ 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
743
+ )
744
+ }
745
+
746
+ /**
747
+ * Suspends current push subscription (temporarily disables).
748
+ *
749
+ * Params are equivalent to [pushSubscribe].
750
+ */
751
+ override fun pushSuspend(
752
+ sync: Boolean?,
753
+ profileFields: ReadableMap?,
754
+ customFields: ReadableMap?,
755
+ cats: ReadableArray?,
756
+ replace: Boolean?,
757
+ skipTriggers: Boolean?
758
+ ) {
759
+ val isSync = sync ?: true
760
+ 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
768
+ )
769
+ }
770
+
771
+ /**
772
+ * Unsubscribes (disables) current push subscription.
773
+ *
774
+ * Params are equivalent to [pushSubscribe].
775
+ */
776
+ override fun pushUnSubscribe(
777
+ sync: Boolean?,
778
+ profileFields: ReadableMap?,
779
+ customFields: ReadableMap?,
780
+ cats: ReadableArray?,
781
+ replace: Boolean?,
782
+ skipTriggers: Boolean?
783
+ ) {
784
+ val isSync = sync ?: true
785
+ 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
793
+ )
794
+ }
795
+
796
+ // --------------------- async status bridges ---------------------
797
+
798
+ /**
799
+ * Tries to un-suspend push subscription (async request to backend).
800
+ *
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
806
+ */
807
+ override fun unSuspendPushSubscription(promise: Promise) {
808
+ coroutineScope.launch {
809
+ try {
810
+ val res = PublicPushSubscriptionFunctions.unSuspendPushSubscription(
811
+ reactApplicationContext
812
+ )
813
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
814
+ } catch (e: Exception) {
815
+ promise.reject("unSuspendPushSubscription", e)
816
+ }
817
+ }
818
+ }
819
+
820
+ /**
821
+ * Returns status of the latest subscription operation (async).
822
+ *
823
+ * Promise:
824
+ * - resolves mapped ResponseWithHttpCode or null
825
+ * - rejects on unexpected errors
826
+ */
827
+ override fun getStatusOfLatestSubscription(promise: Promise) {
828
+ coroutineScope.launch {
829
+ try {
830
+ val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
831
+ reactApplicationContext
832
+ )
833
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
834
+ } catch (e: Exception) {
835
+ promise.reject("getStatusOfLatestSubscription", e)
836
+ }
837
+ }
838
+ }
839
+
840
+ /**
841
+ * Returns status of the latest subscription operation for a specific [provider] (async).
842
+ *
843
+ * Promise:
844
+ * - resolves mapped ResponseWithHttpCode or null
845
+ * - rejects on unexpected errors
846
+ */
847
+ override fun getStatusOfLatestSubscriptionForProvider(
848
+ provider: String?,
849
+ promise: Promise
850
+ ) {
851
+ coroutineScope.launch {
852
+ try {
853
+ val res = PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
854
+ context = reactApplicationContext,
855
+ provider = provider
856
+ )
857
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
858
+ } catch (e: Exception) {
859
+ promise.reject("getStatusOfLatestSubscriptionForProvider", e)
860
+ }
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Returns status for current subscription (async).
866
+ *
867
+ * Promise:
868
+ * - resolves mapped ResponseWithHttpCode or null
869
+ * - rejects on unexpected errors
870
+ */
871
+ override fun getStatusForCurrentSubscription(promise: Promise) {
872
+ coroutineScope.launch {
873
+ try {
874
+ val res = PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
875
+ reactApplicationContext
876
+ )
877
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
878
+ } catch (e: Exception) {
879
+ promise.reject("getStatusForCurrentSubscription", e)
880
+ }
881
+ }
882
+ }
883
+
884
+ /**
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
906
+ */
907
+ private fun responseWithHttpCodeToWritableMap(
908
+ data: DataClasses.ResponseWithHttpCode?
909
+ ): WritableMap? {
910
+ if (data == null) return null
911
+
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
+ val resp = data.response
922
+ if (resp == null) {
923
+ root.putNull("response")
924
+ return root
925
+ }
926
+
927
+ val respMap = Arguments.createMap()
928
+
929
+ val error = resp.error
930
+ if (error != null) {
931
+ respMap.putInt("error", error)
932
+ } else {
933
+ respMap.putNull("error")
934
+ }
935
+
936
+ val errorText = resp.errorText
937
+ if (errorText != null) {
938
+ respMap.putString("errorText", errorText)
939
+ } else {
940
+ respMap.putNull("errorText")
941
+ }
942
+
943
+ val profile = resp.profile
944
+ if (profile == null) {
945
+ respMap.putNull("profile")
946
+ } else {
947
+ val profileMap = Arguments.createMap()
948
+
949
+ val profileId = profile.id
950
+ if (profileId != null) {
951
+ profileMap.putString("id", profileId)
952
+ } else {
953
+ profileMap.putNull("id")
954
+ }
955
+
956
+ val status = profile.status
957
+ if (status != null) {
958
+ profileMap.putString("status", status)
959
+ } else {
960
+ profileMap.putNull("status")
961
+ }
962
+
963
+ val isTest = profile.isTest
964
+ if (isTest != null) {
965
+ profileMap.putBoolean("isTest", isTest)
966
+ } else {
967
+ profileMap.putNull("isTest")
968
+ }
969
+
970
+ val sub = profile.subscription
971
+ if (sub == null) {
972
+ profileMap.putNull("subscription")
973
+ } else {
974
+ val subMap = Arguments.createMap()
975
+
976
+ val subscriptionId = sub.subscriptionId
977
+ if (subscriptionId != null) {
978
+ subMap.putString("subscriptionId", subscriptionId)
979
+ } else {
980
+ subMap.putNull("subscriptionId")
981
+ }
982
+
983
+ val hashId = sub.hashId
984
+ if (hashId != null) {
985
+ subMap.putString("hashId", hashId)
986
+ } else {
987
+ subMap.putNull("hashId")
988
+ }
989
+
990
+ val provider = sub.provider
991
+ if (provider != null) {
992
+ subMap.putString("provider", provider)
993
+ } else {
994
+ subMap.putNull("provider")
995
+ }
996
+
997
+ val subStatus = sub.status
998
+ if (subStatus != null) {
999
+ subMap.putString("status", subStatus)
1000
+ } else {
1001
+ subMap.putNull("status")
1002
+ }
1003
+
1004
+ // Kept as is (reserved for future schema extension).
1005
+ subMap.putNull("fields")
1006
+ subMap.putNull("cats")
1007
+
1008
+ profileMap.putMap("subscription", subMap)
1009
+ }
1010
+
1011
+ respMap.putMap("profile", profileMap)
1012
+ }
1013
+
1014
+ root.putMap("response", respMap)
1015
+ return root
1016
+ }
1017
+
1018
+ companion object {
1019
+ const val NAME: String = "Sdk"
1020
+ }
1021
+ }
1022
+
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
+ */
1029
+ internal object AltcraftRnInitializer {
1030
+
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
+ ) {
1044
+ try {
1045
+ val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
1046
+
1047
+ AltcraftSDK.initialization(
1048
+ reactContext,
1049
+ configuration
1050
+ ) { result ->
1051
+ reactContext.runOnUiQueueThread {
1052
+ if (result.isSuccess) {
1053
+ promise.resolve(null)
1054
+ } else {
1055
+ val throwable = result.exceptionOrNull()
1056
+ if (throwable != null) {
1057
+ promise.reject(
1058
+ "ALTCRAFT_INIT_ERROR",
1059
+ throwable.message ?: "Altcraft initialization error",
1060
+ throwable
1061
+ )
1062
+ } else {
1063
+ promise.reject(
1064
+ "ALTCRAFT_INIT_ERROR",
1065
+ "Altcraft initialization failed with unknown error"
1066
+ )
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ } catch (e: Exception) {
1072
+ promise.reject(
1073
+ "ALTCRAFT_INIT_INVALID_CONFIG",
1074
+ e.message ?: "Invalid Altcraft configuration",
1075
+ e
1076
+ )
1077
+ }
1078
+ }
1079
+ }
1080
+
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
+ */
1089
+ internal object AltcraftRnConfigMapper {
1090
+
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
+ }
1100
+
1101
+ val apiUrl = config.getString("apiUrl")
1102
+ ?: throw IllegalArgumentException("apiUrl must be a non-null string")
1103
+
1104
+ // ---------------- COMMON ----------------
1105
+
1106
+ val rToken: String? =
1107
+ if (config.hasKey("rToken") && !config.isNull("rToken")) {
1108
+ config.getString("rToken")
1109
+ } else {
1110
+ null
1111
+ }
1112
+
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
+ }
1125
+
1126
+ val appIID =
1127
+ if (appInfoMap.hasKey("appIID") && !appInfoMap.isNull("appIID")) {
1128
+ appInfoMap.getString("appIID") ?: ""
1129
+ } else {
1130
+ ""
1131
+ }
1132
+
1133
+ val appVer =
1134
+ if (appInfoMap.hasKey("appVer") && !appInfoMap.isNull("appVer")) {
1135
+ appInfoMap.getString("appVer") ?: ""
1136
+ } else {
1137
+ ""
1138
+ }
1139
+
1140
+ DataClasses.AppInfo(
1141
+ appID = appID,
1142
+ appIID = appIID,
1143
+ appVer = appVer
1144
+ )
1145
+ }
1146
+ } else {
1147
+ null
1148
+ }
1149
+
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
+ }
1157
+
1158
+ val enableLogging: Boolean? =
1159
+ if (config.hasKey("enableLogging") && !config.isNull("enableLogging")) {
1160
+ config.getBoolean("enableLogging")
1161
+ } else {
1162
+ null
1163
+ }
1164
+
1165
+ // ---------------- ANDROID-ONLY ----------------
1166
+
1167
+ val icon: Int? =
1168
+ if (config.hasKey("android_icon") && !config.isNull("android_icon")) {
1169
+ config.getInt("android_icon")
1170
+ } else {
1171
+ null
1172
+ }
1173
+
1174
+ val usingService: Boolean =
1175
+ if (config.hasKey("android_usingService") && !config.isNull("android_usingService")) {
1176
+ config.getBoolean("android_usingService")
1177
+ } else {
1178
+ false
1179
+ }
1180
+
1181
+ val serviceMessage: String? =
1182
+ if (config.hasKey("android_serviceMessage") && !config.isNull("android_serviceMessage")) {
1183
+ config.getString("android_serviceMessage")
1184
+ } else {
1185
+ null
1186
+ }
1187
+
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
+ }
1195
+
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
+ }
1209
+
1210
+ 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
1241
+ }
1242
+ }