@altcraft/react-native-sdk 0.0.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +48 -20
  2. package/README.md +21 -120
  3. package/autolink.js +36 -0
  4. package/lib/commonjs/altcraft_sdk.js +297 -0
  5. package/lib/commonjs/altcraft_sdk.js.map +1 -0
  6. package/lib/commonjs/index.js +192 -0
  7. package/lib/commonjs/index.js.map +1 -0
  8. package/lib/commonjs/package.json +1 -0
  9. package/lib/module/altcraft_sdk.js +292 -0
  10. package/lib/module/altcraft_sdk.js.map +1 -0
  11. package/lib/module/index.js +13 -427
  12. package/lib/module/index.js.map +1 -1
  13. package/lib/typescript/commonjs/package.json +1 -0
  14. package/lib/typescript/commonjs/src/altcraft_sdk.d.ts +143 -0
  15. package/lib/typescript/commonjs/src/altcraft_sdk.d.ts.map +1 -0
  16. package/lib/typescript/commonjs/src/index.d.ts +24 -0
  17. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  18. package/lib/typescript/module/src/altcraft_sdk.d.ts +143 -0
  19. package/lib/typescript/module/src/altcraft_sdk.d.ts.map +1 -0
  20. package/lib/typescript/module/src/index.d.ts +24 -0
  21. package/lib/typescript/module/src/index.d.ts.map +1 -0
  22. package/package.json +49 -95
  23. package/scripts/postinstall.cjs +195 -0
  24. package/src/altcraft_sdk.ts +337 -0
  25. package/src/index.ts +91 -0
  26. package/Sdk.podspec +0 -48
  27. package/android/build.gradle +0 -77
  28. package/android/gradle.properties +0 -5
  29. package/android/src/main/AndroidManifest.xml +0 -2
  30. package/android/src/main/java/com/altcraft/sdk/SdkEventEmitter.kt +0 -50
  31. package/android/src/main/java/com/altcraft/sdk/SdkModule.kt +0 -949
  32. package/android/src/main/java/com/altcraft/sdk/SdkPackage.kt +0 -41
  33. package/android/src/main/java/com/altcraft/sdk/utilities/Converter.kt +0 -326
  34. package/android/src/main/java/com/altcraft/sdk/utilities/Extension.kt +0 -72
  35. package/ios/Converter.swift +0 -640
  36. package/ios/Sdk.h +0 -20
  37. package/ios/Sdk.mm +0 -979
  38. package/ios/SdkModule.swift +0 -778
  39. package/lib/module/NativeSdk.js +0 -48
  40. package/lib/module/NativeSdk.js.map +0 -1
  41. package/lib/module/Utilities.js +0 -178
  42. package/lib/module/Utilities.js.map +0 -1
  43. package/lib/typescript/src/NativeSdk.d.ts +0 -215
  44. package/lib/typescript/src/NativeSdk.d.ts.map +0 -1
  45. package/lib/typescript/src/Utilities.d.ts +0 -47
  46. package/lib/typescript/src/Utilities.d.ts.map +0 -1
  47. package/lib/typescript/src/index.d.ts +0 -252
  48. package/lib/typescript/src/index.d.ts.map +0 -1
  49. package/react-native.config.js +0 -10
  50. package/src/NativeSdk.ts +0 -313
  51. package/src/Utilities.ts +0 -180
  52. package/src/index.tsx +0 -570
  53. /package/lib/typescript/{package.json → module/package.json} +0 -0
@@ -1,949 +0,0 @@
1
- package com.altcraft.sdk
2
-
3
- // Created by Andrey Pogodin.
4
- //
5
- // Copyright © 2025 Altcraft. All rights reserved.
6
-
7
- import androidx.activity.ComponentActivity
8
- import com.altcraft.sdk.config.AltcraftConfiguration
9
- import com.altcraft.sdk.data.DataClasses
10
- import com.altcraft.sdk.mob_events.PublicMobileEventFunctions
11
- import com.altcraft.sdk.push.events.PublicPushEventFunctions
12
- import com.altcraft.sdk.push.subscribe.PublicPushSubscriptionFunctions
13
- import com.altcraft.sdk.profile.PublicProfileFunctions
14
- import com.altcraft.sdk.push.token.PublicPushTokenFunctions
15
- import com.altcraft.sdk.rn.getArrayOrNull
16
- import com.altcraft.sdk.rn.getBooleanOrNull
17
- import com.altcraft.sdk.rn.getIntOrNull
18
- import com.altcraft.sdk.rn.getMapOrNull
19
- import com.altcraft.sdk.rn.getStringOrNull
20
- import com.altcraft.sdk.rn.hasNonNullKey
21
- import com.altcraft.sdk.rn.putNullableBoolean
22
- import com.altcraft.sdk.rn.putNullableInt
23
- import com.altcraft.sdk.rn.putNullableString
24
- import com.altcraft.sdk.rn.toStringList
25
- import com.altcraft.sdk.sdk_events.Events
26
- import com.altcraft.sdk.utilities.Converter
27
- import com.facebook.react.bridge.Arguments
28
- import com.facebook.react.bridge.Promise
29
- import com.facebook.react.bridge.ReactApplicationContext
30
- import com.facebook.react.bridge.ReadableArray
31
- import com.facebook.react.bridge.ReadableMap
32
- import com.facebook.react.bridge.UiThreadUtil
33
- import com.facebook.react.bridge.WritableMap
34
- import com.facebook.react.module.annotations.ReactModule
35
-
36
- import kotlinx.coroutines.CoroutineScope
37
- import kotlinx.coroutines.Dispatchers
38
- import kotlinx.coroutines.SupervisorJob
39
- import kotlinx.coroutines.launch
40
-
41
- // ---------------------- Constants ----------------------
42
-
43
- private object RnConstants {
44
- // Module
45
- const val MODULE_NAME: String = "Sdk"
46
-
47
- // JS event emitter
48
- const val JS_EVENT_NAME: String = "AltcraftSdkEvent"
49
-
50
- // Promise reject codes
51
- const val ERR_INIT_INVALID_CONFIG: String = "ALTCRAFT_INIT_INVALID_CONFIG"
52
- const val ERR_INIT_ERROR: String = "ALTCRAFT_INIT_ERROR"
53
- const val ERR_GET_PUSH_TOKEN: String = "getPushToken"
54
- const val ERR_SET_PUSH_TOKEN: String = "setPushToken"
55
- const val ERR_CLEAR: String = "clear"
56
- const val ERR_UNSUSPEND: String = "unSuspendPushSubscription"
57
- const val ERR_GET_LATEST_STATUS: String = "getStatusOfLatestSubscription"
58
- const val ERR_GET_CURRENT_STATUS: String = "getStatusForCurrentSubscription"
59
- const val ERR_GET_LATEST_STATUS_PROVIDER: String = "getStatusOfLatestSubscriptionForProvider"
60
- const val ERR_UPDATE_PROFILE_FIELDS: String = "updateProfileFields"
61
- const val ERR_FORCED_TOKEN_UPDATE: String = "forcedTokenUpdate"
62
- const val ERR_DELETE_DEVICE_TOKEN: String = "deleteDeviceToken"
63
- const val ERR_CHANGE_PROVIDER_PRIORITY: String = "changePushProviderPriorityList"
64
-
65
- // Promise reject messages
66
- const val MSG_PROVIDER_IS_BLANK: String = "provider is blank"
67
- const val MSG_INIT_UNKNOWN: String = "Altcraft initialization failed with unknown error"
68
- const val MSG_INIT_ERROR: String = "Altcraft initialization error"
69
-
70
- // Keys: TokenData map
71
- const val KEY_PROVIDER: String = "provider"
72
- const val KEY_TOKEN: String = "token"
73
-
74
- // Keys: SDK event map
75
- const val KEY_FUNCTION: String = "function"
76
- const val KEY_CODE: String = "code"
77
- const val KEY_MESSAGE: String = "message"
78
- const val KEY_TYPE: String = "type"
79
- const val KEY_VALUE: String = "value"
80
-
81
- // Event types for JS
82
- const val TYPE_EVENT: String = "event"
83
- const val TYPE_ERROR: String = "error"
84
- const val TYPE_RETRY_ERROR: String = "retryError"
85
-
86
- // Keys: ResponseWithHttpCode -> JS map
87
- const val KEY_HTTP_CODE: String = "httpCode"
88
- const val KEY_RESPONSE: String = "response"
89
- const val KEY_ERROR: String = "error"
90
- const val KEY_ERROR_TEXT: String = "errorText"
91
- const val KEY_PROFILE: String = "profile"
92
- const val KEY_ID: String = "id"
93
- const val KEY_STATUS: String = "status"
94
- const val KEY_IS_TEST: String = "isTest"
95
- const val KEY_SUBSCRIPTION: String = "subscription"
96
- const val KEY_SUBSCRIPTION_ID: String = "subscriptionId"
97
- const val KEY_HASH_ID: String = "hashId"
98
-
99
- // Fields not mapped yet (kept for parity with TS)
100
- const val KEY_FIELDS: String = "fields"
101
- const val KEY_CATS: String = "cats"
102
- }
103
-
104
- @ReactModule(name = RnConstants.MODULE_NAME)
105
- class SdkModule(reactContext: ReactApplicationContext) : NativeSdkSpec(reactContext) {
106
-
107
- private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
108
-
109
- override fun getName(): String = RnConstants.MODULE_NAME
110
-
111
- /**
112
- * Required by NativeEventEmitter (no-op on Android).
113
- *
114
- * @param eventName Event name from JS side.
115
- */
116
- override fun addListener(eventName: String) {
117
- // no-op
118
- }
119
-
120
- /**
121
- * Required by NativeEventEmitter (no-op on Android).
122
- *
123
- * @param count Number of JS listeners removed.
124
- */
125
- override fun removeListeners(count: Double) {
126
- // no-op
127
- }
128
-
129
- // ---------------------- init ----------------------
130
-
131
- /**
132
- * Initializes the native Altcraft SDK using RN config map.
133
- *
134
- * @param config React Native configuration object.
135
- * ```
136
- * Required: `apiUrl`.
137
- * Optional: `rToken`, `appInfo`, `providerPriorityList`, `enableLogging`,
138
- * Android-only: `android_icon`, `android_usingService`, `android_serviceMessage`,
139
- * `android_pushReceiverModules`, `android_pushChannelName`, `android_pushChannelDescription`.
140
- * @param promise
141
- * ```
142
- * Promise resolved on success; rejected on invalid config or initialization failure.
143
- */
144
- override fun initialize(config: ReadableMap, promise: Promise) {
145
- AltcraftRnInitializer.initialize(
146
- reactContext = reactApplicationContext,
147
- config = config,
148
- promise = promise
149
- )
150
- }
151
-
152
- // ---------------------- token-API for RN (ONLY getPushToken / setPushToken)
153
- // ----------------------
154
-
155
- /**
156
- * Returns current push token data from native side.
157
- *
158
- * @param promise Resolves to `{ provider, token }` or `null` if token is not available.
159
- */
160
- override fun getPushToken(promise: Promise) {
161
- coroutineScope.launch {
162
- try {
163
- val tokenData = PublicPushTokenFunctions.getPushToken(reactApplicationContext)
164
- if (tokenData == null) {
165
- promise.resolve(null)
166
- } else {
167
- val map = Arguments.createMap()
168
- map.putString(RnConstants.KEY_PROVIDER, tokenData.provider)
169
- map.putString(RnConstants.KEY_TOKEN, tokenData.token)
170
- promise.resolve(map)
171
- }
172
- } catch (e: Exception) {
173
- promise.reject(RnConstants.ERR_GET_PUSH_TOKEN, e)
174
- }
175
- }
176
- }
177
-
178
- /**
179
- * Sets or clears push token for the given provider.
180
- *
181
- * @param provider Provider identifier (must be non-blank).
182
- * @param token Token string or `null` to clear (native expects String; `null` is converted to
183
- * empty string).
184
- * @param promise Resolves when the token is saved on native side.
185
- */
186
- override fun setPushToken(provider: String, token: String?, promise: Promise) {
187
- if (provider.isBlank()) {
188
- promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, RnConstants.MSG_PROVIDER_IS_BLANK)
189
- return
190
- }
191
-
192
- coroutineScope.launch {
193
- try {
194
- val tokenToPass: String = token ?: ""
195
-
196
- PublicPushTokenFunctions.setPushToken(
197
- context = reactApplicationContext,
198
- provider = provider,
199
- token = tokenToPass
200
- )
201
- promise.resolve(null)
202
- } catch (e: Exception) {
203
- promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, e)
204
- }
205
- }
206
- }
207
-
208
- // ---------------------- AltcraftSDK: clear / permission ----------------------
209
-
210
- /**
211
- * Clears SDK local state and stored data (native).
212
- *
213
- * @param promise Resolves after cleanup is finished.
214
- */
215
- override fun clear(promise: Promise) {
216
- try {
217
- AltcraftSDK.clear(reactApplicationContext) { promise.resolve(null) }
218
- } catch (e: Exception) {
219
- promise.reject(RnConstants.ERR_CLEAR, e)
220
- }
221
- }
222
-
223
- /**
224
- * Requests notification permission (Android-only runtime behavior). Safe no-op if current
225
- * Activity is not a ComponentActivity.
226
- */
227
- override fun requestNotificationPermission() {
228
- val activity = currentActivity
229
- if (activity !is ComponentActivity) return
230
-
231
- UiThreadUtil.runOnUiThread {
232
- try {
233
- AltcraftSDK.requestNotificationPermission(reactApplicationContext, activity)
234
- } catch (_: Exception) {
235
- // ignore
236
- }
237
- }
238
- }
239
-
240
- // ---------------------- MobileEvent bridge ----------------------
241
-
242
- /**
243
- * Sends a mobile event to the server (fire-and-forget).
244
- *
245
- * @param sid Pixel identifier.
246
- * @param eventName Event name.
247
- * @param sendMessageId Optional message identifier to link the event.
248
- * @param payload Optional event payload (string-only map).
249
- * @param matching Optional matching parameters (string-only map).
250
- * @param matchingType Optional matching mode/type.
251
- * @param profileFields Optional profile fields (string-only map).
252
- * @param subscription Optional subscription info (email/sms/push/cc_data), converted on native
253
- * side.
254
- * @param utm Optional UTM tags for attribution.
255
- */
256
- override fun mobileEvent(
257
- sid: String,
258
- eventName: String,
259
- sendMessageId: String?,
260
- payload: ReadableMap?,
261
- matching: ReadableMap?,
262
- matchingType: String?,
263
- profileFields: ReadableMap?,
264
- subscription: ReadableMap?,
265
- utm: ReadableMap?
266
- ) {
267
- try {
268
- val utmData =
269
- utm?.let {
270
- DataClasses.UTM(
271
- campaign = it.getString("campaign"),
272
- content = it.getString("content"),
273
- keyword = it.getString("keyword"),
274
- medium = it.getString("medium"),
275
- source = it.getString("source"),
276
- temp = it.getString("temp")
277
- )
278
- }
279
-
280
- PublicMobileEventFunctions.mobileEvent(
281
- context = reactApplicationContext,
282
- sid = sid,
283
- eventName = eventName,
284
- sendMessageId = sendMessageId,
285
- payload = Converter.toKotlinMap(payload),
286
- matching = Converter.toKotlinMap(matching),
287
- matchingType = matchingType,
288
- profileFields = Converter.toKotlinMap(profileFields),
289
- subscription = Converter.toSubscriptionOrNull(subscription),
290
- utm = utmData
291
- )
292
- } catch (e: Exception) {
293
- // Log error but don't crash bridge
294
- e.printStackTrace()
295
- }
296
- }
297
-
298
- // ---------------------- push payload bridge ----------------------
299
-
300
- /**
301
- * Forwards a push payload to native SDK (Android-only behavior).
302
- *
303
- * @param message Push payload map (string-only).
304
- */
305
- override fun takePush(message: ReadableMap?) {
306
- if (message == null) return
307
- val map = Converter.toStringMapOrNull(message) ?: return
308
- if (map.isNotEmpty()) {
309
- AltcraftSDK.PushReceiver.takePush(reactApplicationContext, map)
310
- }
311
- }
312
-
313
- // ---------------------- manual push events ----------------------
314
-
315
- /**
316
- * Reports a push delivery event (Android-only behavior).
317
- *
318
- * @param message Optional push payload (string-only map).
319
- * @param messageUID Optional Altcraft message UID.
320
- */
321
- override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
322
- try {
323
- val map = Converter.toStringMapOrNull(message)
324
- PublicPushEventFunctions.deliveryEvent(
325
- context = reactApplicationContext,
326
- message = map,
327
- messageUID = messageUID
328
- )
329
- } catch (_: Exception) {
330
- // ignore
331
- }
332
- }
333
-
334
- /**
335
- * Reports a push open event (Android-only behavior).
336
- *
337
- * @param message Optional push payload (string-only map).
338
- * @param messageUID Optional Altcraft message UID.
339
- */
340
- override fun openEvent(message: ReadableMap?, messageUID: String?) {
341
- try {
342
- val map = Converter.toStringMapOrNull(message)
343
- PublicPushEventFunctions.openEvent(
344
- context = reactApplicationContext,
345
- message = map,
346
- messageUID = messageUID
347
- )
348
- } catch (_: Exception) {
349
- // ignore
350
- }
351
- }
352
-
353
- // --------------------- Events bridge for RN ---------------------
354
-
355
- /**
356
- * Subscribes native SDK events stream and forwards events to JS via DeviceEventEmitter. Calling
357
- * from JS multiple times replaces handler on JS side (native always emits to the same event
358
- * name).
359
- */
360
- override fun subscribeToEvents() {
361
- Events.subscribe { event -> sendEventToJs(event) }
362
- }
363
-
364
- /** Unsubscribes native SDK events stream. */
365
- override fun unsubscribeFromEvent() {
366
- Events.unsubscribe()
367
- }
368
-
369
- private fun sendEventToJs(event: DataClasses.Event) {
370
- val eventMap = Arguments.createMap()
371
- eventMap.putString(RnConstants.KEY_FUNCTION, event.function)
372
-
373
- val code = event.eventCode
374
- if (code != null) eventMap.putInt(RnConstants.KEY_CODE, code)
375
- else eventMap.putNull(RnConstants.KEY_CODE)
376
-
377
- val message = event.eventMessage ?: event.toString()
378
- eventMap.putString(RnConstants.KEY_MESSAGE, message)
379
-
380
- val value = event.eventValue
381
- if (value != null) {
382
- val valueMap = Arguments.createMap()
383
- for ((key, anyValue) in value.entries) {
384
- when (anyValue) {
385
- null -> valueMap.putNull(key)
386
- is String -> valueMap.putString(key, anyValue)
387
- is Boolean -> valueMap.putBoolean(key, anyValue)
388
- is Int -> valueMap.putInt(key, anyValue)
389
- is Double -> valueMap.putDouble(key, anyValue)
390
- is Float -> valueMap.putDouble(key, anyValue.toDouble())
391
- is Long -> valueMap.putDouble(key, anyValue.toDouble())
392
- else -> valueMap.putString(key, anyValue.toString())
393
- }
394
- }
395
- eventMap.putMap(RnConstants.KEY_VALUE, valueMap)
396
- } else {
397
- eventMap.putNull(RnConstants.KEY_VALUE)
398
- }
399
- val type =
400
- when (event) {
401
- is DataClasses.Error -> RnConstants.TYPE_ERROR
402
- is DataClasses.RetryError -> RnConstants.TYPE_RETRY_ERROR
403
- else -> RnConstants.TYPE_EVENT
404
- }
405
- eventMap.putString(RnConstants.KEY_TYPE, type)
406
-
407
- SdkEventEmitter.emit(RnConstants.JS_EVENT_NAME, eventMap)
408
- }
409
-
410
- // --------------------- subscription bridge ---------------------
411
-
412
- /**
413
- * Sends a push subscribe request.
414
- *
415
- * @param sync Execution mode:
416
- * ```
417
- * `true` — synchronous server request returning the operation result.
418
- * `false` — asynchronous server request returning enqueue result.
419
- * `null` — defaults to `true` on Android bridge.
420
- * @param profileFields
421
- * ```
422
- * Optional profile fields (string-only map).
423
- * @param customFields Optional custom fields (string-only map).
424
- * @param cats Optional categories list.
425
- * @param replace Optional flag to replace an existing subscription.
426
- * @param skipTriggers Optional flag to skip trigger execution on the server.
427
- */
428
- override fun pushSubscribe(
429
- sync: Boolean?,
430
- profileFields: ReadableMap?,
431
- customFields: ReadableMap?,
432
- cats: ReadableArray?,
433
- replace: Boolean?,
434
- skipTriggers: Boolean?
435
- ) {
436
- val isSync = sync ?: true
437
- PublicPushSubscriptionFunctions.pushSubscribe(
438
- context = reactApplicationContext,
439
- sync = isSync,
440
- profileFields = Converter.toKotlinMap(profileFields),
441
- customFields = Converter.toKotlinMap(customFields),
442
- cats = Converter.toCategoryListOrNull(cats),
443
- replace = replace,
444
- skipTriggers = skipTriggers
445
- )
446
- }
447
-
448
- /**
449
- * Sends a push suspend request.
450
- *
451
- * @param sync Execution mode (see [pushSubscribe]).
452
- * @param profileFields Optional profile fields (string-only map).
453
- * @param customFields Optional custom fields (string-only map).
454
- * @param cats Optional categories list.
455
- * @param replace Optional flag to replace an existing subscription.
456
- * @param skipTriggers Optional flag to skip trigger execution on the server.
457
- */
458
- override fun pushSuspend(
459
- sync: Boolean?,
460
- profileFields: ReadableMap?,
461
- customFields: ReadableMap?,
462
- cats: ReadableArray?,
463
- replace: Boolean?,
464
- skipTriggers: Boolean?
465
- ) {
466
- val isSync = sync ?: true
467
- PublicPushSubscriptionFunctions.pushSuspend(
468
- context = reactApplicationContext,
469
- sync = isSync,
470
- profileFields = Converter.toKotlinMap(profileFields),
471
- customFields = Converter.toKotlinMap(customFields),
472
- cats = Converter.toCategoryListOrNull(cats),
473
- replace = replace,
474
- skipTriggers = skipTriggers
475
- )
476
- }
477
-
478
- /**
479
- * Sends a push unsubscribe request.
480
- *
481
- * @param sync Execution mode (see [pushSubscribe]).
482
- * @param profileFields Optional profile fields (string-only map).
483
- * @param customFields Optional custom fields (string-only map).
484
- * @param cats Optional categories list.
485
- * @param replace Optional flag to replace an existing subscription.
486
- * @param skipTriggers Optional flag to skip trigger execution on the server.
487
- */
488
- override fun pushUnSubscribe(
489
- sync: Boolean?,
490
- profileFields: ReadableMap?,
491
- customFields: ReadableMap?,
492
- cats: ReadableArray?,
493
- replace: Boolean?,
494
- skipTriggers: Boolean?
495
- ) {
496
- val isSync = sync ?: true
497
- PublicPushSubscriptionFunctions.pushUnSubscribe(
498
- context = reactApplicationContext,
499
- sync = isSync,
500
- profileFields = Converter.toKotlinMap(profileFields),
501
- customFields = Converter.toKotlinMap(customFields),
502
- cats = Converter.toCategoryListOrNull(cats),
503
- replace = replace,
504
- skipTriggers = skipTriggers
505
- )
506
- }
507
-
508
- // --------------------- async status bridges ---------------------
509
-
510
- /**
511
- * Unsuspends push subscriptions based on native matching rules.
512
- *
513
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
514
- */
515
- override fun unSuspendPushSubscription(promise: Promise) {
516
- coroutineScope.launch {
517
- try {
518
- val res =
519
- PublicPushSubscriptionFunctions.unSuspendPushSubscription(
520
- reactApplicationContext
521
- )
522
- promise.resolve(responseWithHttpCodeToWritableMap(res))
523
- } catch (e: Exception) {
524
- promise.reject(RnConstants.ERR_UNSUSPEND, e)
525
- }
526
- }
527
- }
528
-
529
- /**
530
- * Returns the status of the latest subscription in profile.
531
- *
532
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
533
- */
534
- override fun getStatusOfLatestSubscription(promise: Promise) {
535
- coroutineScope.launch {
536
- try {
537
- val res =
538
- PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
539
- reactApplicationContext
540
- )
541
- promise.resolve(responseWithHttpCodeToWritableMap(res))
542
- } catch (e: Exception) {
543
- promise.reject(RnConstants.ERR_GET_LATEST_STATUS, e)
544
- }
545
- }
546
- }
547
-
548
- /**
549
- * Returns the status of the latest subscription for the given provider.
550
- *
551
- * @param provider Optional provider identifier (may be null).
552
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
553
- */
554
- override fun getStatusOfLatestSubscriptionForProvider(provider: String?, promise: Promise) {
555
- coroutineScope.launch {
556
- try {
557
- val res =
558
- PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
559
- context = reactApplicationContext,
560
- provider = provider
561
- )
562
- promise.resolve(responseWithHttpCodeToWritableMap(res))
563
- } catch (e: Exception) {
564
- promise.reject(RnConstants.ERR_GET_LATEST_STATUS_PROVIDER, e)
565
- }
566
- }
567
- }
568
-
569
- /**
570
- * Returns the status for current subscription (by current provider/token context).
571
- *
572
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
573
- */
574
- override fun getStatusForCurrentSubscription(promise: Promise) {
575
- coroutineScope.launch {
576
- try {
577
- val res =
578
- PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
579
- reactApplicationContext
580
- )
581
- promise.resolve(responseWithHttpCodeToWritableMap(res))
582
- } catch (e: Exception) {
583
- promise.reject(RnConstants.ERR_GET_CURRENT_STATUS, e)
584
- }
585
- }
586
- }
587
-
588
- // ---------------------- Profile API ----------------------
589
-
590
- /**
591
- * Updates profile fields on the server.
592
- *
593
- * @param profileFields Optional profile fields (string-only map).
594
- * @param skipTriggers Optional flag to skip trigger execution on the server.
595
- */
596
- override fun updateProfileFields(
597
- profileFields: ReadableMap?,
598
- skipTriggers: Boolean?
599
- ) {
600
- try {
601
- PublicProfileFunctions.updateProfileFields(
602
- context = reactApplicationContext,
603
- profileFields = Converter.toKotlinMap(profileFields),
604
- skipTriggers = skipTriggers
605
- )
606
- } catch (e: Exception) {
607
- e.printStackTrace()
608
- }
609
- }
610
-
611
- // ---------------------- Token management API ----------------------
612
-
613
- /**
614
- * Forces a push token refresh (delete + re-register).
615
- *
616
- * @param promise Resolves when the token update flow completes.
617
- */
618
- override fun forcedTokenUpdate(promise: Promise) {
619
- coroutineScope.launch {
620
- try {
621
- PublicPushTokenFunctions.forcedTokenUpdate(reactApplicationContext) {
622
- promise.resolve(null)
623
- }
624
- } catch (e: Exception) {
625
- promise.reject(RnConstants.ERR_FORCED_TOKEN_UPDATE, e)
626
- }
627
- }
628
- }
629
-
630
- /**
631
- * Deletes the device token for a given provider.
632
- *
633
- * @param provider Provider identifier (e.g. `android-firebase`).
634
- * @param promise Resolves when the delete call is dispatched.
635
- */
636
- override fun deleteDeviceToken(provider: String, promise: Promise) {
637
- try {
638
- PublicPushTokenFunctions.deleteDeviceToken(
639
- context = reactApplicationContext,
640
- provider = provider
641
- ) {
642
- promise.resolve(null)
643
- }
644
- } catch (e: Exception) {
645
- promise.reject(RnConstants.ERR_DELETE_DEVICE_TOKEN, e)
646
- }
647
- }
648
-
649
- /**
650
- * Changes the push provider priority list at runtime.
651
- *
652
- * @param priorityList Ordered list of provider identifiers.
653
- * @param promise Resolves when the priority list is updated and token update is triggered.
654
- */
655
- override fun changePushProviderPriorityList(priorityList: ReadableArray, promise: Promise) {
656
- coroutineScope.launch {
657
- try {
658
- val list = priorityList.toStringList()
659
- PublicPushTokenFunctions.changePushProviderPriorityList(
660
- context = reactApplicationContext,
661
- priorityList = list
662
- )
663
- promise.resolve(null)
664
- } catch (e: Exception) {
665
- promise.reject(RnConstants.ERR_CHANGE_PROVIDER_PRIORITY, e)
666
- }
667
- }
668
- }
669
-
670
- // ---------------------- PushReceiver helpers ----------------------
671
-
672
- /**
673
- * Checks whether a push payload belongs to Altcraft.
674
- *
675
- * @param message Push payload map (string-only).
676
- * @return `true` if the message contains the Altcraft marker key.
677
- */
678
- override fun isAltcraftPush(message: ReadableMap?): Boolean {
679
- if (message == null) return false
680
- val map = Converter.toStringMapOrNull(message) ?: return false
681
- return AltcraftSDK.PushReceiver.isAltcraftPush(map)
682
- }
683
-
684
- // ---------------------- SDK lifecycle ----------------------
685
-
686
- /**
687
- * Allows re-running initial retry/scheduling/token-check logic
688
- * in this process on the next [initialization].
689
- */
690
- override fun unlockInitialOperationsInThisSession() {
691
- AltcraftSDK.unlockInitialOperationsInThisSession()
692
- }
693
-
694
- /**
695
- * Sets the App Group name (iOS-only, no-op on Android).
696
- */
697
- override fun setAppGroup(groupName: String?) {
698
- // no-op on Android
699
- }
700
-
701
- /**
702
- * Maps {@link DataClasses.ResponseWithHttpCode} to a RN {@link WritableMap}. Returns `null` if
703
- * input is `null`. Unmapped fields (`fields`, `cats`) are set to `null`.
704
- */
705
- private fun responseWithHttpCodeToWritableMap(
706
- data: DataClasses.ResponseWithHttpCode?
707
- ): WritableMap? {
708
- if (data == null) return null
709
-
710
- val resp = data.response
711
-
712
- return Arguments.createMap().apply root@{
713
- putNullableInt(RnConstants.KEY_HTTP_CODE, data.httpCode)
714
-
715
- if (resp == null) {
716
- putNull(RnConstants.KEY_RESPONSE)
717
- return@root
718
- }
719
-
720
- val respMap =
721
- Arguments.createMap().apply resp@{
722
- putNullableInt(RnConstants.KEY_ERROR, resp.error)
723
- putNullableString(RnConstants.KEY_ERROR_TEXT, resp.errorText)
724
-
725
- val profile = resp.profile
726
- if (profile == null) {
727
- putNull(RnConstants.KEY_PROFILE)
728
- return@resp
729
- }
730
-
731
- val profileMap =
732
- Arguments.createMap().apply profile@{
733
- putNullableString(RnConstants.KEY_ID, profile.id)
734
- putNullableString(RnConstants.KEY_STATUS, profile.status)
735
- putNullableBoolean(RnConstants.KEY_IS_TEST, profile.isTest)
736
-
737
- val sub = profile.subscription
738
- if (sub == null) {
739
- putNull(RnConstants.KEY_SUBSCRIPTION)
740
- return@profile
741
- }
742
-
743
- val subMap =
744
- Arguments.createMap().apply sub@{
745
- putNullableString(
746
- RnConstants.KEY_SUBSCRIPTION_ID,
747
- sub.subscriptionId
748
- )
749
- putNullableString(
750
- RnConstants.KEY_HASH_ID,
751
- sub.hashId
752
- )
753
- putNullableString(
754
- RnConstants.KEY_PROVIDER,
755
- sub.provider
756
- )
757
- putNullableString(
758
- RnConstants.KEY_STATUS,
759
- sub.status
760
- )
761
-
762
- putNull(RnConstants.KEY_FIELDS)
763
- putNull(RnConstants.KEY_CATS)
764
- }
765
-
766
- putMap(RnConstants.KEY_SUBSCRIPTION, subMap)
767
- }
768
-
769
- putMap(RnConstants.KEY_PROFILE, profileMap)
770
- }
771
-
772
- putMap(RnConstants.KEY_RESPONSE, respMap)
773
- }
774
- }
775
-
776
- /**
777
- * Stores a key-value pair in native persistent storage.
778
- *
779
- * Platform behavior:
780
- * - iOS: uses UserDefaults (optionally scoped by `suiteName` / App Group).
781
- * - Android: uses SharedPreferences; `suiteName` is used as preferences name.
782
- *
783
- * Supported value types:
784
- * - primitives (Boolean, Number, String)
785
- * - complex structures serialized as JSON string
786
- * - `null` removes the stored value
787
- *
788
- * @param suiteName Storage namespace / suite name (platform-dependent).
789
- * @param key Storage key.
790
- * @param value Value to store or `null` to remove.
791
- */
792
- override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
793
- val k = key.trim()
794
- if (k.isEmpty()) return
795
-
796
- val prefsName =
797
- suiteName?.trim().takeUnless { it.isNullOrEmpty() }
798
- ?: reactApplicationContext.packageName
799
-
800
- val prefs =
801
- reactApplicationContext.getSharedPreferences(
802
- prefsName,
803
- android.content.Context.MODE_PRIVATE
804
- )
805
-
806
- if (value == null) {
807
- prefs.edit().remove(k).apply()
808
- return
809
- }
810
-
811
- val v = value.trim()
812
-
813
- // Store JSON as String (SharedPreferences has no native JSON type)
814
- if ((v.startsWith("{") && v.endsWith("}")) || (v.startsWith("[") && v.endsWith("]"))) {
815
- prefs.edit().putString(k, v).apply()
816
- return
817
- }
818
-
819
- // Boolean
820
- if (v.equals("true", ignoreCase = true) || v.equals("false", ignoreCase = true)) {
821
- prefs.edit().putBoolean(k, v.equals("true", ignoreCase = true)).apply()
822
- return
823
- }
824
-
825
- // Integer (Long)
826
- v.toLongOrNull()?.let { asLong ->
827
- prefs.edit().putLong(k, asLong).apply()
828
- return
829
- }
830
-
831
- // Double -> keep precision as String
832
- v.toDoubleOrNull()?.let {
833
- prefs.edit().putString(k, v).apply()
834
- return
835
- }
836
-
837
- // Fallback: String
838
- prefs.edit().putString(k, value).apply()
839
- }
840
-
841
- companion object {
842
- const val NAME: String = RnConstants.MODULE_NAME
843
- }
844
- }
845
-
846
- /** Internal RN initializer entry point. */
847
- internal object AltcraftRnInitializer {
848
-
849
- fun initialize(reactContext: ReactApplicationContext, config: ReadableMap, promise: Promise) {
850
- try {
851
- val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
852
-
853
- AltcraftSDK.initialization(reactContext, configuration) { result ->
854
- reactContext.runOnUiQueueThread {
855
- if (result.isSuccess) {
856
- promise.resolve(null)
857
- } else {
858
- val throwable = result.exceptionOrNull()
859
- if (throwable != null) {
860
- promise.reject(
861
- RnConstants.ERR_INIT_ERROR,
862
- throwable.message ?: RnConstants.MSG_INIT_ERROR,
863
- throwable
864
- )
865
- } else {
866
- promise.reject(RnConstants.ERR_INIT_ERROR, RnConstants.MSG_INIT_UNKNOWN)
867
- }
868
- }
869
- }
870
- }
871
- } catch (e: Exception) {
872
- promise.reject(
873
- RnConstants.ERR_INIT_INVALID_CONFIG,
874
- e.message ?: "Invalid Altcraft configuration",
875
- e
876
- )
877
- }
878
- }
879
- }
880
-
881
- /** Maps React Native configuration object to native [AltcraftConfiguration]. */
882
- internal object AltcraftRnConfigMapper {
883
-
884
- private const val KEY_API_URL = "apiUrl"
885
- private const val KEY_R_TOKEN = "rToken"
886
- private const val KEY_APP_INFO = "appInfo"
887
- private const val KEY_PROVIDER_PRIORITY_LIST = "providerPriorityList"
888
- private const val KEY_ENABLE_LOGGING = "enableLogging"
889
-
890
- private const val KEY_ANDROID_ICON = "android_icon"
891
- private const val KEY_ANDROID_USING_SERVICE = "android_usingService"
892
- private const val KEY_ANDROID_SERVICE_MESSAGE = "android_serviceMessage"
893
- private const val KEY_ANDROID_PUSH_RECEIVER_MODULES = "android_pushReceiverModules"
894
- private const val KEY_ANDROID_PUSH_CHANNEL_NAME = "android_pushChannelName"
895
- private const val KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION = "android_pushChannelDescription"
896
-
897
- private const val KEY_APP_ID = "appID"
898
- private const val KEY_APP_IID = "appIID"
899
- private const val KEY_APP_VER = "appVer"
900
-
901
- private const val MSG_API_URL_REQUIRED = "apiUrl is required for AltcraftConfiguration"
902
- private const val MSG_API_URL_MUST_BE_STRING = "apiUrl must be a non-null string"
903
-
904
- fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
905
- if (!config.hasNonNullKey(KEY_API_URL)) {
906
- throw IllegalArgumentException(MSG_API_URL_REQUIRED)
907
- }
908
-
909
- val apiUrl =
910
- config.getString(KEY_API_URL)
911
- ?: throw IllegalArgumentException(MSG_API_URL_MUST_BE_STRING)
912
-
913
- val rToken = config.getStringOrNull(KEY_R_TOKEN)
914
-
915
- val appInfo =
916
- config.getMapOrNull(KEY_APP_INFO)?.let { appInfoMap ->
917
- val appID = appInfoMap.getStringOrNull(KEY_APP_ID) ?: ""
918
- val appIID = appInfoMap.getStringOrNull(KEY_APP_IID) ?: ""
919
- val appVer = appInfoMap.getStringOrNull(KEY_APP_VER) ?: ""
920
- DataClasses.AppInfo(appID = appID, appIID = appIID, appVer = appVer)
921
- }
922
-
923
- val providerPriorityList = config.getArrayOrNull(KEY_PROVIDER_PRIORITY_LIST)?.toStringList()
924
-
925
- val enableLogging = config.getBooleanOrNull(KEY_ENABLE_LOGGING)
926
-
927
- val icon = config.getIntOrNull(KEY_ANDROID_ICON)
928
-
929
- val pushReceiverModules =
930
- config.getArrayOrNull(KEY_ANDROID_PUSH_RECEIVER_MODULES)?.toStringList()
931
-
932
- val pushChannelName = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_NAME)
933
-
934
- val pushChannelDescription = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION)
935
-
936
- return AltcraftConfiguration.Builder(
937
- apiUrl = apiUrl,
938
- icon = icon,
939
- rToken = rToken,
940
- appInfo = appInfo,
941
- providerPriorityList = providerPriorityList,
942
- pushReceiverModules = pushReceiverModules,
943
- pushChannelName = pushChannelName,
944
- pushChannelDescription = pushChannelDescription,
945
- enableLogging = enableLogging
946
- )
947
- .build()
948
- }
949
- }