@cavlyn/react-native-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CavlynReactNative.podspec +23 -0
  2. package/LICENSE +202 -0
  3. package/README.md +164 -2
  4. package/android/build.gradle +52 -0
  5. package/android/src/main/AndroidManifest.xml +3 -0
  6. package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativeModule.kt +394 -0
  7. package/android/src/main/kotlin/com/cavlyn/reactnative/CavlynReactNativePackage.kt +14 -0
  8. package/dist/client.d.ts +95 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +395 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/hooks.d.ts +24 -0
  13. package/dist/hooks.d.ts.map +1 -0
  14. package/dist/hooks.js +78 -0
  15. package/dist/hooks.js.map +1 -0
  16. package/dist/http.d.ts +30 -0
  17. package/dist/http.d.ts.map +1 -0
  18. package/dist/http.js +126 -0
  19. package/dist/http.js.map +1 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +26 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/nativeBridge.d.ts +46 -0
  25. package/dist/nativeBridge.d.ts.map +1 -0
  26. package/dist/nativeBridge.js +99 -0
  27. package/dist/nativeBridge.js.map +1 -0
  28. package/dist/parser.d.ts +38 -0
  29. package/dist/parser.d.ts.map +1 -0
  30. package/dist/parser.js +198 -0
  31. package/dist/parser.js.map +1 -0
  32. package/dist/storage.d.ts +27 -0
  33. package/dist/storage.d.ts.map +1 -0
  34. package/dist/storage.js +72 -0
  35. package/dist/storage.js.map +1 -0
  36. package/dist/types.d.ts +182 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +3 -0
  39. package/dist/types.js.map +1 -0
  40. package/ios/CavlynReactNative.m +40 -0
  41. package/ios/CavlynReactNative.swift +463 -0
  42. package/package.json +65 -4
  43. package/react-native.config.js +14 -0
  44. package/src/client.ts +479 -0
  45. package/src/hooks.ts +117 -0
  46. package/src/http.ts +158 -0
  47. package/src/index.ts +38 -0
  48. package/src/nativeBridge.ts +109 -0
  49. package/src/parser.ts +202 -0
  50. package/src/storage.ts +76 -0
  51. package/src/types.ts +214 -0
@@ -0,0 +1,463 @@
1
+ import Foundation
2
+ import React
3
+ import UIKit
4
+
5
+ #if canImport(AdServices)
6
+ import AdServices
7
+ #endif
8
+
9
+ @objc(CavlynReactNative)
10
+ public final class CavlynReactNative: RCTEventEmitter {
11
+ private static let eventNameLinkReceived = "CavlynLinkReceived"
12
+ private static let initialUriKey = "com.cavlyn.sdk.initial_uri"
13
+ private static let currentUriKey = "com.cavlyn.sdk.current_uri"
14
+ private static let installationIdKey = "com.cavlyn.sdk.installation_id"
15
+ private static let linkIdKeys: Set<String> = ["linkId", "link_id"]
16
+ private static let clickIdKeys: Set<String> = ["clickId", "click_id"]
17
+
18
+ private static weak var activeInstance: CavlynReactNative?
19
+ private static var pendingUrl: URL?
20
+ private static let staticLock = NSLock()
21
+
22
+ private let lock = NSLock()
23
+ private let queue = DispatchQueue(label: "com.cavlyn.rn.dispatcher", qos: .utility)
24
+ private let defaults = UserDefaults.standard
25
+ private let isoFormatter = ISO8601DateFormatter()
26
+
27
+ private var apiKey: String?
28
+ private var apiBaseUrl: String = "https://api.cavlyn.com"
29
+ private var isInitialized = false
30
+ private var hasListeners = false
31
+ private var pendingEmit: [String: Any]?
32
+
33
+ public override init() {
34
+ super.init()
35
+ Self.staticLock.lock()
36
+ Self.activeInstance = self
37
+ Self.staticLock.unlock()
38
+ }
39
+
40
+ @objc
41
+ public override static func requiresMainQueueSetup() -> Bool {
42
+ return false
43
+ }
44
+
45
+ public override func supportedEvents() -> [String]! {
46
+ return [Self.eventNameLinkReceived]
47
+ }
48
+
49
+ public override func startObserving() {
50
+ lock.lock()
51
+ hasListeners = true
52
+ let pending = pendingEmit
53
+ pendingEmit = nil
54
+ lock.unlock()
55
+ // Deliver a link (e.g. cold-start) that arrived before JS subscribed.
56
+ if let pending = pending {
57
+ sendEvent(withName: Self.eventNameLinkReceived, body: pending)
58
+ }
59
+ }
60
+
61
+ public override func stopObserving() {
62
+ lock.lock()
63
+ hasListeners = false
64
+ lock.unlock()
65
+ }
66
+
67
+ // MARK: - AppDelegate Helpers
68
+
69
+ /// Forward iOS Universal Links from `AppDelegate.application(_:continue:restorationHandler:)`.
70
+ @objc
71
+ @discardableResult
72
+ public static func application(
73
+ _ application: UIApplication,
74
+ continue userActivity: NSUserActivity,
75
+ restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
76
+ ) -> Bool {
77
+ guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
78
+ let url = userActivity.webpageURL else {
79
+ return false
80
+ }
81
+ return handleIncomingUrlFromAppDelegate(url)
82
+ }
83
+
84
+ /// Forward custom URL schemes from `AppDelegate.application(_:open:options:)`.
85
+ @objc
86
+ @discardableResult
87
+ public static func application(
88
+ _ app: UIApplication,
89
+ open url: URL,
90
+ options: [UIApplication.OpenURLOptionsKey: Any] = [:]
91
+ ) -> Bool {
92
+ return handleIncomingUrlFromAppDelegate(url)
93
+ }
94
+
95
+ private static func handleIncomingUrlFromAppDelegate(_ url: URL) -> Bool {
96
+ staticLock.lock()
97
+ let instance = activeInstance
98
+ if instance == nil || !(instance?.isReady() ?? false) {
99
+ pendingUrl = url
100
+ staticLock.unlock()
101
+ return parse(url: url) != nil
102
+ }
103
+ staticLock.unlock()
104
+ return instance?.processUrl(url) != nil
105
+ }
106
+
107
+ private func isReady() -> Bool {
108
+ lock.lock()
109
+ defer { lock.unlock() }
110
+ return isInitialized
111
+ }
112
+
113
+ // MARK: - React Native Bridged Methods
114
+
115
+ @objc(initialize:apiBaseUrl:resolver:rejecter:)
116
+ public func initialize(
117
+ _ apiKey: String,
118
+ apiBaseUrl: String,
119
+ resolver resolve: @escaping RCTPromiseResolveBlock,
120
+ rejecter reject: @escaping RCTPromiseRejectBlock
121
+ ) {
122
+ let trimmedKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
123
+ guard !trimmedKey.isEmpty else {
124
+ reject("INVALID_ARGS", "Cavlyn: apiKey is required", nil)
125
+ return
126
+ }
127
+
128
+ lock.lock()
129
+ if !isInitialized {
130
+ self.apiKey = trimmedKey
131
+ let trimmedUrl = apiBaseUrl.trimmingCharacters(in: .whitespacesAndNewlines)
132
+ self.apiBaseUrl = (trimmedUrl.isEmpty ? "https://api.cavlyn.com" : trimmedUrl)
133
+ .replacingOccurrences(of: "/+$", with: "", options: .regularExpression)
134
+ self.isInitialized = true
135
+ }
136
+ lock.unlock()
137
+
138
+ Self.staticLock.lock()
139
+ let buffered = Self.pendingUrl
140
+ Self.pendingUrl = nil
141
+ Self.staticLock.unlock()
142
+
143
+ if let url = buffered {
144
+ _ = processUrl(url)
145
+ }
146
+
147
+ resolve(nil)
148
+ }
149
+
150
+ @objc(handleUrl:resolver:rejecter:)
151
+ public func handleUrl(
152
+ _ urlString: String,
153
+ resolver resolve: @escaping RCTPromiseResolveBlock,
154
+ rejecter reject: @escaping RCTPromiseRejectBlock
155
+ ) {
156
+ guard isReady() else {
157
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
158
+ return
159
+ }
160
+ guard let url = URL(string: urlString) else {
161
+ resolve(nil)
162
+ return
163
+ }
164
+ resolve(processUrl(url))
165
+ }
166
+
167
+ @objc(initialLink:rejecter:)
168
+ public func initialLink(
169
+ _ resolve: @escaping RCTPromiseResolveBlock,
170
+ rejecter reject: @escaping RCTPromiseRejectBlock
171
+ ) {
172
+ guard isReady() else {
173
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
174
+ return
175
+ }
176
+ resolve(readStoredLink(forKey: Self.initialUriKey))
177
+ }
178
+
179
+ @objc(currentLink:rejecter:)
180
+ public func currentLink(
181
+ _ resolve: @escaping RCTPromiseResolveBlock,
182
+ rejecter reject: @escaping RCTPromiseRejectBlock
183
+ ) {
184
+ guard isReady() else {
185
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
186
+ return
187
+ }
188
+ resolve(readStoredLink(forKey: Self.currentUriKey))
189
+ }
190
+
191
+ @objc(trackEvent:properties:resolver:rejecter:)
192
+ public func trackEvent(
193
+ _ name: String,
194
+ properties: NSDictionary,
195
+ resolver resolve: @escaping RCTPromiseResolveBlock,
196
+ rejecter reject: @escaping RCTPromiseRejectBlock
197
+ ) {
198
+ guard isReady() else {
199
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
200
+ return
201
+ }
202
+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
203
+ guard !trimmed.isEmpty else {
204
+ reject("INVALID_ARGS", "Event name must not be blank", nil)
205
+ return
206
+ }
207
+
208
+ if let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
209
+ let metadata = properties as? [String: Any] ?? [:]
210
+ dispatchEvent(
211
+ type: "CONVERSION",
212
+ eventName: trimmed,
213
+ link: context,
214
+ extraFields: [:],
215
+ metadata: metadata,
216
+ idempotencyKey: UUID().uuidString.lowercased()
217
+ )
218
+ }
219
+ resolve(nil)
220
+ }
221
+
222
+ @objc(trackCommerceEvent:resolver:rejecter:)
223
+ public func trackCommerceEvent(
224
+ _ payload: NSDictionary,
225
+ resolver resolve: @escaping RCTPromiseResolveBlock,
226
+ rejecter reject: @escaping RCTPromiseRejectBlock
227
+ ) {
228
+ guard isReady() else {
229
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
230
+ return
231
+ }
232
+ guard let rawType = payload["type"] as? String, !rawType.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
233
+ reject("INVALID_ARGS", "Commerce event type is required", nil)
234
+ return
235
+ }
236
+
237
+ if let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
238
+ var extra: [String: Any] = [:]
239
+ for key in ["storeId", "productId", "variantId", "orderId", "currency", "value", "quantity"] {
240
+ if let val = payload[key] {
241
+ extra[key] = val
242
+ }
243
+ }
244
+ let eventName = (payload["eventName"] as? String) ?? rawType.lowercased()
245
+ let metadata = payload["metadata"] as? [String: Any] ?? [:]
246
+ dispatchEvent(
247
+ type: rawType,
248
+ eventName: eventName,
249
+ link: context,
250
+ extraFields: extra,
251
+ metadata: metadata,
252
+ idempotencyKey: UUID().uuidString.lowercased()
253
+ )
254
+ }
255
+ resolve(nil)
256
+ }
257
+
258
+ @objc(getAdServicesToken:rejecter:)
259
+ public func getAdServicesToken(
260
+ _ resolve: @escaping RCTPromiseResolveBlock,
261
+ rejecter reject: @escaping RCTPromiseRejectBlock
262
+ ) {
263
+ #if canImport(AdServices)
264
+ if #available(iOS 14.3, *) {
265
+ do {
266
+ let token = try AAAttribution.attributionToken()
267
+ resolve(token)
268
+ return
269
+ } catch {
270
+ resolve(nil)
271
+ return
272
+ }
273
+ }
274
+ #endif
275
+ resolve(nil)
276
+ }
277
+
278
+ @objc(recordAdServicesToken:resolver:rejecter:)
279
+ public func recordAdServicesToken(
280
+ _ token: String,
281
+ resolver resolve: @escaping RCTPromiseResolveBlock,
282
+ rejecter reject: @escaping RCTPromiseRejectBlock
283
+ ) {
284
+ guard isReady() else {
285
+ reject("NOT_INITIALIZED", "Call Cavlyn.initialize before using the SDK", nil)
286
+ return
287
+ }
288
+ let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines)
289
+ if !trimmed.isEmpty,
290
+ let context = readStoredLink(forKey: Self.currentUriKey) ?? readStoredLink(forKey: Self.initialUriKey) {
291
+ dispatchEvent(
292
+ type: "CONVERSION",
293
+ eventName: "apple_search_ads_token",
294
+ link: context,
295
+ extraFields: [:],
296
+ metadata: ["adServicesToken": trimmed],
297
+ idempotencyKey: UUID().uuidString.lowercased()
298
+ )
299
+ }
300
+ resolve(nil)
301
+ }
302
+
303
+ @objc(getInstallationId:rejecter:)
304
+ public func getInstallationId(
305
+ _ resolve: @escaping RCTPromiseResolveBlock,
306
+ rejecter reject: @escaping RCTPromiseRejectBlock
307
+ ) {
308
+ resolve(getOrCreateInstallationId())
309
+ }
310
+
311
+ // MARK: - Internal Processing & Networking
312
+
313
+ private func processUrl(_ url: URL) -> [String: Any]? {
314
+ guard let link = Self.parse(url: url) else {
315
+ return nil
316
+ }
317
+
318
+ let installId = getOrCreateInstallationId()
319
+ lock.lock()
320
+ let isFirstLink = defaults.string(forKey: Self.initialUriKey) == nil
321
+ if isFirstLink {
322
+ defaults.set(url.absoluteString, forKey: Self.initialUriKey)
323
+ }
324
+ defaults.set(url.absoluteString, forKey: Self.currentUriKey)
325
+ let shouldEmit = hasListeners
326
+ if !shouldEmit { pendingEmit = link }
327
+ lock.unlock()
328
+
329
+ if isFirstLink, let linkId = link["linkId"] as? String {
330
+ dispatchEvent(
331
+ type: "INSTALL",
332
+ eventName: nil,
333
+ link: link,
334
+ extraFields: [:],
335
+ metadata: [:],
336
+ idempotencyKey: "install:\(installId):\(linkId)"
337
+ )
338
+ }
339
+
340
+ dispatchEvent(
341
+ type: "APP_OPEN",
342
+ eventName: "app_open",
343
+ link: link,
344
+ extraFields: [:],
345
+ metadata: [:],
346
+ idempotencyKey: UUID().uuidString.lowercased()
347
+ )
348
+
349
+ if shouldEmit {
350
+ sendEvent(withName: Self.eventNameLinkReceived, body: link)
351
+ }
352
+
353
+ return link
354
+ }
355
+
356
+ private static func parse(url: URL) -> [String: Any]? {
357
+ guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
358
+ let queryItems = components.queryItems else {
359
+ return nil
360
+ }
361
+
362
+ var params: [String: String] = [:]
363
+ var linkIdUUID: UUID?
364
+ var clickIdUUID: UUID?
365
+
366
+ for item in queryItems {
367
+ let key = item.name
368
+ let value = item.value ?? ""
369
+ if linkIdKeys.contains(key) {
370
+ if linkIdUUID == nil { linkIdUUID = UUID(uuidString: value) }
371
+ } else if clickIdKeys.contains(key) {
372
+ if clickIdUUID == nil { clickIdUUID = UUID(uuidString: value) }
373
+ } else {
374
+ params[key] = value
375
+ }
376
+ }
377
+
378
+ guard let validLinkId = linkIdUUID else {
379
+ return nil
380
+ }
381
+
382
+ var result: [String: Any] = [
383
+ "uri": url.absoluteString,
384
+ "linkId": validLinkId.uuidString.lowercased(),
385
+ "parameters": params
386
+ ]
387
+ if let validClickId = clickIdUUID {
388
+ result["clickId"] = validClickId.uuidString.lowercased()
389
+ }
390
+ return result
391
+ }
392
+
393
+ private func readStoredLink(forKey key: String) -> [String: Any]? {
394
+ guard let uriString = defaults.string(forKey: key),
395
+ let url = URL(string: uriString) else {
396
+ return nil
397
+ }
398
+ return Self.parse(url: url)
399
+ }
400
+
401
+ private func getOrCreateInstallationId() -> String {
402
+ if let existing = defaults.string(forKey: Self.installationIdKey), !existing.isEmpty {
403
+ return existing
404
+ }
405
+ let fresh = UUID().uuidString.lowercased()
406
+ defaults.set(fresh, forKey: Self.installationIdKey)
407
+ return fresh
408
+ }
409
+
410
+ private func dispatchEvent(
411
+ type: String,
412
+ eventName: String?,
413
+ link: [String: Any],
414
+ extraFields: [String: Any],
415
+ metadata: [String: Any],
416
+ idempotencyKey: String
417
+ ) {
418
+ lock.lock()
419
+ let key = apiKey
420
+ let baseUrl = apiBaseUrl
421
+ lock.unlock()
422
+
423
+ guard let apiKey = key,
424
+ let linkId = link["linkId"] as? String,
425
+ let endpoint = URL(string: "\(baseUrl)/api/v1/events") else {
426
+ return
427
+ }
428
+
429
+ var body: [String: Any] = [
430
+ "linkId": linkId,
431
+ "type": type,
432
+ "installId": getOrCreateInstallationId(),
433
+ "platform": "IOS",
434
+ "occurredAt": isoFormatter.string(from: Date()),
435
+ "metadata": metadata
436
+ ]
437
+ if let clickId = link["clickId"] as? String {
438
+ body["clickId"] = clickId
439
+ }
440
+ if let eventName = eventName, type != "INSTALL" {
441
+ body["eventName"] = eventName
442
+ }
443
+ for (field, value) in extraFields {
444
+ body[field] = value
445
+ }
446
+
447
+ queue.async {
448
+ var request = URLRequest(url: endpoint)
449
+ request.httpMethod = "POST"
450
+ request.timeoutInterval = 10
451
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
452
+ request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
453
+ request.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key")
454
+ guard let jsonData = try? JSONSerialization.data(withJSONObject: body, options: []) else {
455
+ return
456
+ }
457
+ request.httpBody = jsonData
458
+ URLSession.shared.dataTask(with: request) { _, _, _ in
459
+ // Non-fatal to host application runtime
460
+ }.resume()
461
+ }
462
+ }
463
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@cavlyn/react-native-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "React Native SDK for Cavlyn dynamic links, Universal Links / App Links routing, deferred link resolution, and install/conversion/commerce attribution.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "react-native": "src/index.ts",
8
+ "files": [
9
+ "dist",
10
+ "src",
11
+ "ios",
12
+ "android",
13
+ "CavlynReactNative.podspec",
14
+ "react-native.config.js",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "clean": "rm -rf dist",
21
+ "test": "node --test tests/*.test.js",
22
+ "prepublishOnly": "npm run clean && npm run build && npm test"
23
+ },
24
+ "keywords": [
25
+ "react-native",
26
+ "expo",
27
+ "cavlyn",
28
+ "dynamic-links",
29
+ "deep-linking",
30
+ "universal-links",
31
+ "app-links",
32
+ "attribution",
33
+ "deferred-deep-linking"
34
+ ],
35
+ "author": "Cavlyn System <dev@cavlyn.com>",
36
+ "license": "Apache-2.0",
37
+ "homepage": "https://github.com/casontek/smart-attribution-system/tree/main/sdk/react-native#readme",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/casontek/smart-attribution-system.git",
41
+ "directory": "sdk/react-native"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/casontek/smart-attribution-system/issues"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "peerDependencies": {
50
+ "react": ">=18.0.0",
51
+ "react-native": ">=0.72.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "react": {
55
+ "optional": true
56
+ },
57
+ "react-native": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "typescript": "^5.7.0"
63
+ },
64
+ "engines": {
65
+ "node": ">=18.0.0"
66
+ }
67
+ }
@@ -0,0 +1,14 @@
1
+ module.exports = {
2
+ dependency: {
3
+ platforms: {
4
+ ios: {
5
+ podspecPath: './CavlynReactNative.podspec',
6
+ },
7
+ android: {
8
+ sourceDir: './android',
9
+ packageImportPath: 'import com.cavlyn.reactnative.CavlynReactNativePackage;',
10
+ packageInstance: 'new CavlynReactNativePackage()',
11
+ },
12
+ },
13
+ },
14
+ };