@usesophi/sophi-event-react-native 0.0.0-stage → 0.0.1-alpha01

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 (74) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +116 -2
  3. package/SophiEventSDK-ReactNative.podspec +23 -0
  4. package/android/build.gradle +39 -0
  5. package/android/consumer-rules.pro +1 -0
  6. package/android/src/main/AndroidManifest.xml +3 -0
  7. package/android/src/main/java/com/sophi/eventreactnative/SophiEventsModule.kt +199 -0
  8. package/android/src/main/java/com/sophi/eventreactnative/SophiEventsPackage.kt +11 -0
  9. package/index.ts +4 -0
  10. package/ios/Frameworks/SophiEventSDK.xcframework/Info.plist +44 -0
  11. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Headers/SophiEventSDK-Swift.h +382 -0
  12. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Info.plist +0 -0
  13. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios.abi.json +21707 -0
  14. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios.private.swiftinterface +413 -0
  15. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  16. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios.swiftinterface +413 -0
  17. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/Modules/module.modulemap +3 -0
  18. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/PrivacyInfo.xcprivacy +153 -0
  19. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64/SophiEventSDK.framework/SophiEventSDK +0 -0
  20. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Headers/SophiEventSDK-Swift.h +760 -0
  21. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Info.plist +0 -0
  22. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios-simulator.abi.json +21707 -0
  23. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios-simulator.private.swiftinterface +413 -0
  24. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  25. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/arm64-apple-ios-simulator.swiftinterface +413 -0
  26. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/x86_64-apple-ios-simulator.abi.json +21707 -0
  27. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/x86_64-apple-ios-simulator.private.swiftinterface +413 -0
  28. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  29. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/SophiEventSDK.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +413 -0
  30. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/Modules/module.modulemap +3 -0
  31. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/PrivacyInfo.xcprivacy +153 -0
  32. package/ios/Frameworks/SophiEventSDK.xcframework/ios-arm64_x86_64-simulator/SophiEventSDK.framework/SophiEventSDK +0 -0
  33. package/ios/Frameworks/SophiIdentity.xcframework/Info.plist +44 -0
  34. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Headers/SophiIdentity-Swift.h +382 -0
  35. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Info.plist +0 -0
  36. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios.abi.json +6314 -0
  37. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios.private.swiftinterface +170 -0
  38. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  39. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios.swiftinterface +170 -0
  40. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/Modules/module.modulemap +3 -0
  41. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/PrivacyInfo.xcprivacy +50 -0
  42. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64/SophiIdentity.framework/SophiIdentity +0 -0
  43. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Headers/SophiIdentity-Swift.h +760 -0
  44. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Info.plist +0 -0
  45. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios-simulator.abi.json +6314 -0
  46. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios-simulator.private.swiftinterface +170 -0
  47. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  48. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/arm64-apple-ios-simulator.swiftinterface +170 -0
  49. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/x86_64-apple-ios-simulator.abi.json +6314 -0
  50. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/x86_64-apple-ios-simulator.private.swiftinterface +170 -0
  51. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  52. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/SophiIdentity.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +170 -0
  53. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/Modules/module.modulemap +3 -0
  54. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/PrivacyInfo.xcprivacy +50 -0
  55. package/ios/Frameworks/SophiIdentity.xcframework/ios-arm64_x86_64-simulator/SophiIdentity.framework/SophiIdentity +0 -0
  56. package/ios/SophiEventsModule.m +54 -0
  57. package/ios/SophiEventsModuleImpl.swift +178 -0
  58. package/lib/index.d.ts +4 -0
  59. package/lib/index.js +10 -0
  60. package/lib/src/SophiEvents.d.ts +3 -0
  61. package/lib/src/SophiEvents.js +11 -0
  62. package/lib/src/client.d.ts +60 -0
  63. package/lib/src/client.js +151 -0
  64. package/lib/src/types.d.ts +204 -0
  65. package/lib/src/types.js +3 -0
  66. package/lib/src/wire.d.ts +10 -0
  67. package/lib/src/wire.js +191 -0
  68. package/native-versions.json +16 -0
  69. package/package.json +62 -4
  70. package/react-native.config.js +10 -0
  71. package/src/SophiEvents.ts +13 -0
  72. package/src/client.ts +191 -0
  73. package/src/types.ts +216 -0
  74. package/src/wire.ts +189 -0
package/LICENSE ADDED
@@ -0,0 +1,4 @@
1
+ Copyright (c) 2026 Sophi. All rights reserved.
2
+
3
+ This software is proprietary and UNLICENSED. No permission to use, copy, modify,
4
+ or distribute this software is granted except under a separate agreement with Sophi.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ Proprietary / UNLICENSED. See `LICENSE`.
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # Sophi events for React Native
4
+
5
+ `@usesophi/sophi-event-react-native` reports storefront events (page views, product views, cart,
6
+ checkout, purchase, identify, custom) from a React Native app through Sophi's native event SDKs.
7
+ It is the React Native counterpart of `SophiEventSDK-iOS` and `Sophi-Event-Android`, with the same
8
+ events, consent rules and error codes. The full field reference is the native `EVENT-REFERENCE.md`.
9
+
10
+ - iOS uses the prebuilt `SophiIdentity` and `SophiEventSDK` frameworks from the
11
+ `Sophi-Event-iOS-SDK` release pinned in `native-versions.json`.
12
+ - Android uses `com.usesophi:sophi-event` from Maven Central at the version pinned in the same file.
13
+ - No native SDK source is published in this package.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @usesophi/sophi-event-react-native
19
+ cd ios && pod install
20
+ ```
21
+
22
+ Then rebuild both native apps; autolinking registers the module. The supported React Native lines
23
+ and toolchain are the same as the Sophi chat bridge (`@usesophi/sophi-react-native`): React Native
24
+ 0.81.6+ to 0.84.x with Hermes, iOS 15.1+, Android API 24+, Kotlin 2.3.21, JDK 17.
25
+
26
+ **With Sophi chat:** install both packages. They must use the same identity version; each chat
27
+ release states the event package version it needs. The app then contains one `SophiIdentity`, so
28
+ chat and events recognise the same shopper. (On iOS two copies would be refused at run time.)
29
+
30
+ ## Use
31
+
32
+ ```ts
33
+ import {SophiEvents, SophiEventError} from '@usesophi/sophi-event-react-native';
34
+
35
+ // Once at app startup. Leave analyticsEnabled out while consent is not known yet.
36
+ await SophiEvents.configure({apiKey: TENANT_KEY, externalUserId: signedInCustomerId ?? null});
37
+
38
+ // When the consent platform answers. false deletes the stored queue.
39
+ await SophiEvents.setAnalyticsEnabled(true);
40
+
41
+ await SophiEvents.productView(
42
+ {type: 'Product', url: 'merchant://products/0042'},
43
+ {id: '0042', categoryIds: ['shirts'], name: 'Shirt', url: 'merchant://products/0042',
44
+ productImageUrl: 'https://cdn.example.com/0042.jpg', taxonomy: ['Men', 'Shirts'],
45
+ currency: 'GBP', unitPrice: 25, unitSalePrice: 20, inStock: 1},
46
+ );
47
+ ```
48
+
49
+ | Method | Use |
50
+ | --- | --- |
51
+ | `configure(config, {onDiagnostic})` | Once at startup; await it before tracking. Another key or origin ends the previous tenant |
52
+ | `setAnalyticsEnabled(boolean)` | The consent answer; `false` deletes the stored queue |
53
+ | `updateUser(id \| null)` / `logout()` | Sign-in (merchant customer ID) and sign-out |
54
+ | `pageView`, `productView`, `listingView`, `basketView` | Views, page first |
55
+ | `addToCart`, `removeFromCart` | After a successful merchant change, with the resulting basket. One `addToCart` per added unit |
56
+ | `checkoutStarted`, `purchase` | Checkout start; purchase once per confirmed order |
57
+ | `identify(page, user)` | Memory only, needs granted analytics |
58
+ | `custom(page, properties)` / `track(event)` | Merchant-defined events / any event with extra context |
59
+ | `flush()`, `pendingCount()` | Send what is due now / events waiting on the device |
60
+
61
+ Every event call resolves with a receipt: `queued` (stored on the device; delivery follows and is
62
+ retried), `disabled` (analytics not granted, nothing stored) or `deliveredMemoryOnly` (identify).
63
+ Do not repeat a successful purchase call: a new call is a new occurrence.
64
+
65
+ ## Errors
66
+
67
+ Every call rejects only with `SophiEventError`. `code` is the same on iOS and Android:
68
+
69
+ | Code | Meaning |
70
+ | --- | --- |
71
+ | `validation` | The event is invalid; `fields` lists wire paths such as `basket.line_items[0].quantity`. Do not retry it |
72
+ | `not_configured`, `invalid_configuration` | `configure` has not completed, or its input is invalid |
73
+ | `event_too_large`, `queue_full` | The event was not accepted; nothing was queued |
74
+ | `storage_unavailable` | Device storage failed; see the native README |
75
+ | `network`, `http` (`status`), `invalid_response`, `invalid_receipt`, `backend_unsupported` | Only from `identify`, which is not queued |
76
+ | `disabled`, `merge_pending`, `identity_changed` | Consent, sign-in or configuration changed around the call |
77
+ | `duplicate_identity_module` | Two `SophiIdentity` copies in one iOS app |
78
+ | `internal_error` | Unexpected failure |
79
+
80
+ ## Development
81
+
82
+ ```sh
83
+ npm ci
84
+ npm test # builds, then the JavaScript tests and the shared event corpus check
85
+ npm run lint && npm run typecheck
86
+ npm run check:package # what npm would publish: no native sources, no example or tests
87
+ ```
88
+
89
+ `tests/fixtures/events.json` is the shared corpus of the native SDKs; every valid event in it must
90
+ convert to the identical wire form. Update it from the native repositories when the contract
91
+ changes. See [example/README.md](example/README.md) to run the app on a simulator or device.
92
+
93
+ ## Releasing
94
+
95
+ Releases start only by hand; pushing to `main` never publishes. In the Actions tab, run
96
+ **Release** with the version (for example `0.0.1-alpha02`). It runs as a dry run by default: it
97
+ tests, fetches the pinned native frameworks, packs the archive with that version, checks that no
98
+ native SDK source or font is in it and lists its contents. Run it again with `dry_run` off to
99
+ publish with npm Trusted Publishing (no npm token) in the `prod` environment, tag `v<version>` and
100
+ create the GitHub release. A prerelease goes to the npm tag named by its first word
101
+ (`0.0.1-alpha02` → `alpha`); a plain version goes to `latest`.
102
+
103
+ npm accepts Trusted Publishing only for a package that already exists, so the very first version is
104
+ published once from a maintainer machine, from a clean checkout of the latest `main`:
105
+
106
+ ```sh
107
+ npm login
108
+ npm run release:local -- 0.0.1-alpha01
109
+ ```
110
+
111
+ It runs the same checks, asks you to type the version to confirm, publishes (npm asks for the 2FA
112
+ code) and pushes the tag. Then, on the package's npm settings page, add a Trusted Publisher:
113
+ GitHub Actions, organization `Let-Me-Shop-For-You`, repository `SophiEventSDK-ReactNative`, workflow
114
+ `release.yml`, environment `prod`, with **Allow npm publish** selected.
115
+
116
+ Order, as for the native SDKs: release the event SDKs first (iOS and Android at the same version),
117
+ pin them in `native-versions.json`, release this package, then the chat bridge.
@@ -0,0 +1,23 @@
1
+ require 'json'
2
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
3
+ Pod::Spec.new do |s|
4
+ s.name = 'SophiEventSDK-ReactNative'
5
+ # The repository keeps the placeholder 0.0.0-development; scripts/release.cjs writes the real
6
+ # version into the published package. CocoaPods ranks that prerelease below 0 and then refuses the
7
+ # local pod, so development builds use 0.0.0.
8
+ s.version = package['version'].start_with?('0.0.0-') ? '0.0.0' : package['version']
9
+ s.summary = package['description']
10
+ s.homepage = 'https://github.com/Let-Me-Shop-For-You/SophiEventSDK-ReactNative'
11
+ s.license = { :type => package['license'] }
12
+ s.author = 'Sophi'
13
+ s.platforms = { :ios => '15.1' }
14
+ s.source = { :git => 'https://github.com/Let-Me-Shop-For-You/SophiEventSDK-ReactNative.git', :tag => "v#{s.version}" }
15
+ # Bridge sources only. SophiIdentity and SophiEventSDK ship as prebuilt frameworks fetched by
16
+ # scripts/fetch-native.cjs. The chat bridge uses this SophiIdentity too, so an app has one copy.
17
+ s.source_files = 'ios/*.{h,m,swift}'
18
+ s.vendored_frameworks = ['ios/Frameworks/SophiIdentity.xcframework', 'ios/Frameworks/SophiEventSDK.xcframework']
19
+ s.libraries = 'sqlite3'
20
+ s.swift_version = '5.9'
21
+ s.dependency 'React-Core'
22
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'CLANG_ENABLE_MODULES' => 'YES' }
23
+ end
@@ -0,0 +1,39 @@
1
+ import groovy.json.JsonSlurper
2
+
3
+ buildscript {
4
+ ext.sophiKotlinVersion = rootProject.ext.has('kotlinVersion') ? rootProject.ext.kotlinVersion : '2.3.21'
5
+ def requestedKotlin = sophiKotlinVersion.toString().tokenize('.').collect { it.replaceAll(/[^0-9].*$/, '').toInteger() }
6
+ if (requestedKotlin.size() < 3 || requestedKotlin[0] < 2 ||
7
+ (requestedKotlin[0] == 2 && (requestedKotlin[1] < 3 || (requestedKotlin[1] == 3 && requestedKotlin[2] < 21)))) {
8
+ throw new GradleException("Sophi React Native events are qualified with Kotlin 2.3.21 or newer, the version the Sophi event SDK is built with. Set rootProject.ext.kotlinVersion and the Kotlin Gradle classpath to 2.3.21.")
9
+ }
10
+ repositories { google(); mavenCentral() }
11
+ dependencies {
12
+ classpath 'com.android.tools.build:gradle:8.13.2'
13
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$sophiKotlinVersion"
14
+ }
15
+ }
16
+ apply plugin: 'com.android.library'
17
+ apply plugin: 'org.jetbrains.kotlin.android'
18
+
19
+ // The native SDK ships as a compiled AAR from Maven Central; its version is pinned in native-versions.json.
20
+ def sophiEventVersion = new JsonSlurper().parse(file('../native-versions.json')).android.version
21
+ if (!sophiEventVersion) throw new GradleException('native-versions.json must pin android.version')
22
+
23
+ repositories { google(); mavenCentral() }
24
+
25
+ android {
26
+ namespace 'com.sophi.eventreactnative'
27
+ compileSdk 36
28
+ defaultConfig { minSdk 24; consumerProguardFiles 'consumer-rules.pro' }
29
+ compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
30
+ kotlinOptions { jvmTarget = '17' }
31
+ }
32
+ dependencies {
33
+ // The host React Native Gradle plugin selects the matching react-android version.
34
+ implementation 'com.facebook.react:react-android'
35
+ // Brings com.usesophi:sophi-identity, the shopper identity the chat SDK shares.
36
+ implementation "com.usesophi:sophi-event:$sophiEventVersion"
37
+ implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0'
38
+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0'
39
+ }
@@ -0,0 +1 @@
1
+ -keep class com.sophi.eventreactnative.SophiEventsPackage { *; }
@@ -0,0 +1,3 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!-- The Sophi event SDK AAR merges its own INTERNET permission and WorkManager setup. -->
3
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,199 @@
1
+ package com.sophi.eventreactnative
2
+
3
+ import com.facebook.react.bridge.Arguments
4
+ import com.facebook.react.bridge.Promise
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
7
+ import com.facebook.react.bridge.ReactMethod
8
+ import com.facebook.react.bridge.ReadableMap
9
+ import com.facebook.react.bridge.WritableMap
10
+ import com.facebook.react.modules.core.DeviceEventManagerModule
11
+ import com.sophi.event.EventConfiguration
12
+ import com.sophi.event.EventDiagnostics
13
+ import com.sophi.event.EventException
14
+ import com.sophi.event.EventReceipt
15
+ import com.sophi.event.QueueLimits
16
+ import com.sophi.event.SophiEvent
17
+ import com.sophi.event.external.EventValidationException
18
+ import com.sophi.event.external.SophiEventData
19
+ import kotlinx.coroutines.CancellationException
20
+ import kotlinx.coroutines.CoroutineScope
21
+ import kotlinx.coroutines.Dispatchers
22
+ import kotlinx.coroutines.SupervisorJob
23
+ import kotlinx.coroutines.cancel
24
+ import kotlinx.coroutines.launch
25
+ import kotlinx.serialization.SerializationException
26
+ import kotlinx.serialization.json.Json
27
+
28
+ /**
29
+ * Forwards JavaScript calls to [SophiEvent]. Events arrive as the wire JSON produced by the
30
+ * JavaScript layer and are decoded into the SDK's own [SophiEventData], so validation and delivery
31
+ * stay inside the native SDK. Error codes match the iOS bridge.
32
+ */
33
+ class SophiEventsModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
34
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
35
+ private val json = Json { ignoreUnknownKeys = false }
36
+
37
+ override fun getName() = "SophiEventsModule"
38
+
39
+ @ReactMethod
40
+ fun configure(options: ReadableMap, promise: Promise) {
41
+ val configuration =
42
+ try {
43
+ configuration(options)
44
+ } catch (e: Exception) {
45
+ return reject(promise, EventException("invalid_configuration", cause = e))
46
+ }
47
+ run(promise) {
48
+ SophiEvent.configure(reactApplicationContext, configuration, EventDiagnostics { emit(it.code, it.eventId, it.count) })
49
+ null
50
+ }
51
+ }
52
+
53
+ @ReactMethod
54
+ fun setAnalyticsEnabled(enabled: Boolean, promise: Promise) = run(promise) {
55
+ SophiEvent.setAnalyticsEnabled(enabled)
56
+ null
57
+ }
58
+
59
+ @ReactMethod
60
+ fun updateUser(externalUserId: String?, promise: Promise) = run(promise) {
61
+ SophiEvent.updateUser(externalUserId)
62
+ null
63
+ }
64
+
65
+ @ReactMethod
66
+ fun logout(promise: Promise) = run(promise) {
67
+ SophiEvent.logout()
68
+ null
69
+ }
70
+
71
+ @ReactMethod
72
+ fun track(eventJson: String, promise: Promise) {
73
+ val event =
74
+ try {
75
+ json.decodeFromString(SophiEventData.serializer(), eventJson)
76
+ } catch (e: SerializationException) {
77
+ return reject(promise, EventValidationException(listOf("event")))
78
+ } catch (e: IllegalArgumentException) {
79
+ return reject(promise, EventValidationException(listOf("event")))
80
+ }
81
+ run(promise) {
82
+ val receipt = SophiEvent.track(event)
83
+ Arguments.createMap().apply {
84
+ putString("id", receipt.id?.lowercase())
85
+ putString("status", status(receipt.status))
86
+ }
87
+ }
88
+ }
89
+
90
+ @ReactMethod
91
+ fun flush(promise: Promise) = run(promise) {
92
+ val result = SophiEvent.flush()
93
+ Arguments.createMap().apply {
94
+ putInt("delivered", result.delivered)
95
+ putInt("retried", result.retried)
96
+ putInt("discarded", result.discarded)
97
+ putInt("pending", result.pending)
98
+ putString("pausedReason", result.pausedReason)
99
+ }
100
+ }
101
+
102
+ @ReactMethod
103
+ fun pendingCount(promise: Promise) = run(promise) { SophiEvent.pendingCount() }
104
+
105
+ // Required by NativeEventEmitter.
106
+ @ReactMethod fun addListener(eventName: String) {}
107
+
108
+ @ReactMethod fun removeListeners(count: Double) {}
109
+
110
+ override fun invalidate() {
111
+ scope.cancel()
112
+ super.invalidate()
113
+ }
114
+
115
+ private fun configuration(options: ReadableMap): EventConfiguration {
116
+ val apiKey = if (options.hasKey("apiKey") && !options.isNull("apiKey")) options.getString("apiKey") ?: "" else ""
117
+ val consent = if (options.hasKey("analyticsEnabled") && !options.isNull("analyticsEnabled")) options.getBoolean("analyticsEnabled") else null
118
+ val user = if (options.hasKey("externalUserId") && !options.isNull("externalUserId")) options.getString("externalUserId") else null
119
+ val limits = if (options.hasKey("queueLimits") && !options.isNull("queueLimits")) options.getMap("queueLimits") else null
120
+ val defaults = QueueLimits()
121
+ fun number(name: String): Double? = limits?.takeIf { it.hasKey(name) && !it.isNull(name) }?.getDouble(name)
122
+ val queueLimits =
123
+ QueueLimits(
124
+ maxAgeMillis = number("maxAgeMs")?.toLong() ?: defaults.maxAgeMillis,
125
+ maxEvents = number("maxEvents")?.toInt() ?: defaults.maxEvents,
126
+ maxBytes = number("maxBytes")?.toInt() ?: defaults.maxBytes,
127
+ maxEventBytes = number("maxEventBytes")?.toInt() ?: defaults.maxEventBytes,
128
+ )
129
+ return if (options.hasKey("baseUrl") && !options.isNull("baseUrl")) {
130
+ EventConfiguration(apiKey, options.getString("baseUrl") ?: "", consent, queueLimits, user)
131
+ } else {
132
+ EventConfiguration(apiKey, analyticsEnabled = consent, queueLimits = queueLimits, externalUserId = user)
133
+ }
134
+ }
135
+
136
+ private fun run(promise: Promise, operation: suspend () -> Any?) {
137
+ scope.launch {
138
+ try {
139
+ promise.resolve(operation())
140
+ } catch (e: CancellationException) {
141
+ reject(promise, EventException("internal_error", cause = e))
142
+ } catch (e: Exception) {
143
+ reject(promise, e)
144
+ }
145
+ }
146
+ }
147
+
148
+ private fun emit(code: String, eventId: String?, count: Int) {
149
+ if (!reactApplicationContext.hasActiveReactInstance()) return
150
+ val body =
151
+ Arguments.createMap().apply {
152
+ putString("code", code)
153
+ putString("eventId", eventId?.lowercase())
154
+ putInt("count", count)
155
+ }
156
+ reactApplicationContext
157
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
158
+ .emit("SophiEventDiagnostic", body)
159
+ }
160
+
161
+ private fun status(value: EventReceipt.Status): String =
162
+ when (value) {
163
+ EventReceipt.Status.QUEUED -> "queued"
164
+ EventReceipt.Status.DISABLED -> "disabled"
165
+ EventReceipt.Status.DELIVERED_MEMORY_ONLY -> "deliveredMemoryOnly"
166
+ }
167
+
168
+ private fun reject(promise: Promise, error: Exception) {
169
+ val info: WritableMap = Arguments.createMap()
170
+ when (error) {
171
+ is EventValidationException -> {
172
+ info.putArray("fields", Arguments.fromList(error.fields))
173
+ promise.reject("validation", "Invalid event fields: ${error.fields.joinToString()}", info)
174
+ }
175
+ is EventException -> {
176
+ error.status?.let { info.putInt("status", it) }
177
+ promise.reject(error.reason, message(error.reason, error.status), info)
178
+ }
179
+ else -> promise.reject("internal_error", "The native event SDK failed", info)
180
+ }
181
+ }
182
+
183
+ private fun message(reason: String, status: Int?): String =
184
+ when (reason) {
185
+ "not_configured" -> "Configure the event SDK first"
186
+ "invalid_configuration" -> "The event configuration is invalid"
187
+ "queue_full" -> "The event queue is full"
188
+ "event_too_large" -> "The event is too large"
189
+ "storage_unavailable" -> "Event storage is unavailable"
190
+ "identity_changed" -> "The shopper, consent or configuration changed"
191
+ "backend_unsupported" -> "The backend does not support mobile events"
192
+ "http" -> "The request failed with status $status"
193
+ "invalid_receipt", "invalid_response" -> "The server answer was not usable"
194
+ "network" -> "The server could not be reached"
195
+ "disabled" -> "Analytics is not granted"
196
+ "merge_pending" -> "The sign-in merge is not confirmed yet"
197
+ else -> "The native event SDK failed"
198
+ }
199
+ }
@@ -0,0 +1,11 @@
1
+ package com.sophi.eventreactnative
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class SophiEventsPackage : ReactPackage {
9
+ override fun createNativeModules(context: ReactApplicationContext): List<NativeModule> = listOf(SophiEventsModule(context))
10
+ override fun createViewManagers(context: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
11
+ }
package/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export {default as SophiEvents} from './src/SophiEvents';
2
+ export {SophiEventError} from './src/client';
3
+ export type {SophiEventsClient} from './src/client';
4
+ export type * from './src/types';
@@ -0,0 +1,44 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>AvailableLibraries</key>
6
+ <array>
7
+ <dict>
8
+ <key>BinaryPath</key>
9
+ <string>SophiEventSDK.framework/SophiEventSDK</string>
10
+ <key>LibraryIdentifier</key>
11
+ <string>ios-arm64</string>
12
+ <key>LibraryPath</key>
13
+ <string>SophiEventSDK.framework</string>
14
+ <key>SupportedArchitectures</key>
15
+ <array>
16
+ <string>arm64</string>
17
+ </array>
18
+ <key>SupportedPlatform</key>
19
+ <string>ios</string>
20
+ </dict>
21
+ <dict>
22
+ <key>BinaryPath</key>
23
+ <string>SophiEventSDK.framework/SophiEventSDK</string>
24
+ <key>LibraryIdentifier</key>
25
+ <string>ios-arm64_x86_64-simulator</string>
26
+ <key>LibraryPath</key>
27
+ <string>SophiEventSDK.framework</string>
28
+ <key>SupportedArchitectures</key>
29
+ <array>
30
+ <string>arm64</string>
31
+ <string>x86_64</string>
32
+ </array>
33
+ <key>SupportedPlatform</key>
34
+ <string>ios</string>
35
+ <key>SupportedPlatformVariant</key>
36
+ <string>simulator</string>
37
+ </dict>
38
+ </array>
39
+ <key>CFBundlePackageType</key>
40
+ <string>XFWK</string>
41
+ <key>XCFrameworkFormatVersion</key>
42
+ <string>1.0</string>
43
+ </dict>
44
+ </plist>