@kerdly/expo 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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/android/build.gradle +61 -0
  4. package/android/src/main/AndroidManifest.xml +19 -0
  5. package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
  6. package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
  7. package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
  8. package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
  9. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
  10. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
  11. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
  12. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
  13. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
  14. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
  15. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +110 -0
  16. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
  17. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
  18. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
  19. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
  20. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
  21. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
  22. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
  23. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
  24. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
  25. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
  26. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
  27. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
  28. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
  29. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
  30. package/app.plugin.js +2 -0
  31. package/build/Kerdly.d.ts +106 -0
  32. package/build/Kerdly.d.ts.map +1 -0
  33. package/build/Kerdly.js +494 -0
  34. package/build/Kerdly.js.map +1 -0
  35. package/build/index.d.ts +4 -0
  36. package/build/index.d.ts.map +1 -0
  37. package/build/index.js +2 -0
  38. package/build/index.js.map +1 -0
  39. package/build/log.d.ts +13 -0
  40. package/build/log.d.ts.map +1 -0
  41. package/build/log.js +45 -0
  42. package/build/log.js.map +1 -0
  43. package/build/native.d.ts +74 -0
  44. package/build/native.d.ts.map +1 -0
  45. package/build/native.js +56 -0
  46. package/build/native.js.map +1 -0
  47. package/build/normalize.d.ts +8 -0
  48. package/build/normalize.d.ts.map +1 -0
  49. package/build/normalize.js +86 -0
  50. package/build/normalize.js.map +1 -0
  51. package/build/types.d.ts +134 -0
  52. package/build/types.d.ts.map +1 -0
  53. package/build/types.js +3 -0
  54. package/build/types.js.map +1 -0
  55. package/build/validation.d.ts +70 -0
  56. package/build/validation.d.ts.map +1 -0
  57. package/build/validation.js +349 -0
  58. package/build/validation.js.map +1 -0
  59. package/build/version.d.ts +4 -0
  60. package/build/version.d.ts.map +1 -0
  61. package/build/version.js +5 -0
  62. package/build/version.js.map +1 -0
  63. package/expo-module.config.json +9 -0
  64. package/ios/KerdlySDK/.kerdly-sync.json +7 -0
  65. package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
  66. package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
  67. package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
  68. package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
  69. package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
  70. package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
  71. package/ios/KerdlySDK/Core/Support.swift +95 -0
  72. package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
  73. package/ios/KerdlySDK/Logic/Batch.swift +180 -0
  74. package/ios/KerdlySDK/Logic/Context.swift +85 -0
  75. package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
  76. package/ios/KerdlySDK/Logic/DeferredLinks.swift +236 -0
  77. package/ios/KerdlySDK/Logic/Environment.swift +39 -0
  78. package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
  79. package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
  80. package/ios/KerdlySDK/Logic/Events.swift +102 -0
  81. package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
  82. package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
  83. package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
  84. package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
  85. package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
  86. package/ios/KerdlySDK/Logic/Skan.swift +343 -0
  87. package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
  88. package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
  89. package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
  90. package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
  91. package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
  92. package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
  93. package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
  94. package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
  95. package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
  96. package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
  97. package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
  98. package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
  99. package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +96 -0
  100. package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
  101. package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
  102. package/ios/KerdlySdk.podspec +45 -0
  103. package/ios/KerdlySdkModule.swift +332 -0
  104. package/package.json +96 -4
  105. package/plugin/withKerdly.js +163 -0
  106. package/src/Kerdly.ts +524 -0
  107. package/src/index.ts +23 -0
  108. package/src/log.ts +49 -0
  109. package/src/native.ts +150 -0
  110. package/src/normalize.ts +82 -0
  111. package/src/types.ts +182 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,85 @@
1
+ import Foundation
2
+
3
+ /// The persistent queue's in-memory model: events in `seq` order, at most 1,000 events
4
+ /// or 1 MB. When it is over either bound the oldest **custom** event is dropped; reserved `$` events
5
+ /// are never dropped (so the queue may exceed the bounds when it holds only reserved events).
6
+ struct EventQueue: Equatable, Sendable {
7
+ static let defaultMaxEvents = 1_000
8
+ static let defaultMaxBytes = 1_048_576
9
+
10
+ let maxEvents: Int
11
+ let maxBytes: Int
12
+ private(set) var events: [QueuedEvent]
13
+ private(set) var totalBytes: Int
14
+
15
+ init(events: [QueuedEvent] = [], maxEvents: Int = EventQueue.defaultMaxEvents,
16
+ maxBytes: Int = EventQueue.defaultMaxBytes) {
17
+ self.maxEvents = maxEvents
18
+ self.maxBytes = maxBytes
19
+ self.events = events.sorted { $0.seq < $1.seq }
20
+ self.totalBytes = events.reduce(0) { $0 + $1.size }
21
+ }
22
+
23
+ var count: Int { events.count }
24
+ var isEmpty: Bool { events.isEmpty }
25
+
26
+ func contains(id: String) -> Bool {
27
+ events.contains { $0.id == id }
28
+ }
29
+
30
+ /// Appends (or inserts by `seq`, for a replayed event) and enforces the bounds.
31
+ /// - Returns: the custom events dropped to make room (possibly `event` itself).
32
+ @discardableResult
33
+ mutating func append(_ event: QueuedEvent) -> [QueuedEvent] {
34
+ if let last = events.last, last.seq > event.seq {
35
+ let index = events.firstIndex { $0.seq > event.seq } ?? events.endIndex
36
+ events.insert(event, at: index)
37
+ } else {
38
+ events.append(event)
39
+ }
40
+ totalBytes += event.size
41
+ return enforceBounds()
42
+ }
43
+
44
+ /// Removes every event whose id is in `ids`. Returns how many were removed.
45
+ @discardableResult
46
+ mutating func remove(ids: Set<String>) -> Int {
47
+ guard !ids.isEmpty else { return 0 }
48
+ let before = events.count
49
+ events.removeAll { event in
50
+ if ids.contains(event.id) {
51
+ totalBytes -= event.size
52
+ return true
53
+ }
54
+ return false
55
+ }
56
+ return before - events.count
57
+ }
58
+
59
+ /// The next batch: up to `maxEvents` events in queue order whose encoded size, plus
60
+ /// `overheadBytes` for the envelope, stays within `maxBytes`. Always at least one event when the
61
+ /// queue is not empty (an oversized one is the server's to refuse with 413).
62
+ func nextBatch(maxEvents: Int, maxBytes: Int, overheadBytes: Int) -> [QueuedEvent] {
63
+ var batch: [QueuedEvent] = []
64
+ var bytes = overheadBytes
65
+ for event in events {
66
+ if batch.count >= max(1, maxEvents) { break }
67
+ let added = event.size + 1
68
+ if !batch.isEmpty && bytes + added > maxBytes { break }
69
+ batch.append(event)
70
+ bytes += added
71
+ }
72
+ return batch
73
+ }
74
+
75
+ private mutating func enforceBounds() -> [QueuedEvent] {
76
+ var dropped: [QueuedEvent] = []
77
+ while events.count > maxEvents || totalBytes > maxBytes {
78
+ guard let index = events.firstIndex(where: { !$0.isReserved }) else { break }
79
+ let removed = events.remove(at: index)
80
+ totalBytes -= removed.size
81
+ dropped.append(removed)
82
+ }
83
+ return dropped
84
+ }
85
+ }
@@ -0,0 +1,84 @@
1
+ import Foundation
2
+
3
+ /// Custom event rules: names and keys match `^[a-z][a-z0-9_]{0,39}$`, at most 25
4
+ /// props, values are strings (truncated to 256 characters), finite numbers or booleans. Anything
5
+ /// else is dropped before enqueue; the caller logs the issues at debug level.
6
+ enum EventValidator {
7
+ static let maxProps = 25
8
+ static let maxStringLength = 256
9
+ static let maxNameLength = 40
10
+
11
+ /// `^[a-z][a-z0-9_]{0,39}$`, checked byte by byte (no regex engine on the hot path).
12
+ static func isValidName(_ name: String) -> Bool {
13
+ let bytes = Array(name.utf8)
14
+ guard (1...maxNameLength).contains(bytes.count) else { return false }
15
+ guard let first = bytes.first, first >= 0x61, first <= 0x7A else { return false }
16
+ for b in bytes.dropFirst() {
17
+ let lower = b >= 0x61 && b <= 0x7A
18
+ let digit = b >= 0x30 && b <= 0x39
19
+ if !(lower || digit || b == 0x5F) { return false }
20
+ }
21
+ return true
22
+ }
23
+
24
+ struct Sanitized: Equatable {
25
+ var props: [String: JSONValue]
26
+ var issues: [String]
27
+ }
28
+
29
+ /// Keeps the valid props. Keys are visited in sorted order, so which ones survive is stable.
30
+ /// - Parameter limit: how many props may be kept (a standard event's typed props use up part of
31
+ /// the 25).
32
+ static func sanitize(_ properties: [String: Any], limit: Int = maxProps) -> Sanitized {
33
+ var props: [String: JSONValue] = [:]
34
+ var issues: [String] = []
35
+ for key in properties.keys.sorted() {
36
+ guard isValidName(key) else {
37
+ issues.append("prop key '\(key)' is invalid")
38
+ continue
39
+ }
40
+ guard let value = sanitizeValue(properties[key] as Any) else {
41
+ issues.append("prop '\(key)' has an unsupported value")
42
+ continue
43
+ }
44
+ if props.count >= limit {
45
+ issues.append("prop '\(key)' is over the \(maxProps)-prop limit")
46
+ continue
47
+ }
48
+ if case .string(let s) = value, let cut = truncated(s, to: maxStringLength) {
49
+ issues.append("prop '\(key)' truncated to \(maxStringLength) characters")
50
+ props[key] = .string(cut)
51
+ } else {
52
+ props[key] = value
53
+ }
54
+ }
55
+ return Sanitized(props: props, issues: issues)
56
+ }
57
+
58
+ /// A string, a finite number or a boolean; nil for anything else (nested values included).
59
+ static func sanitizeValue(_ value: Any) -> JSONValue? {
60
+ guard let v = JSONValue(any: value) else { return nil }
61
+ switch v {
62
+ case .string, .bool, .int:
63
+ return v
64
+ case .double(let d):
65
+ return d.isFinite ? v : nil
66
+ case .null, .array, .object:
67
+ return nil
68
+ }
69
+ }
70
+
71
+ /// `s` cut to at most `max` UTF-16 units (how the collector, Kotlin and JavaScript count string
72
+ /// length) without splitting a character; nil when it already fits.
73
+ static func truncated(_ s: String, to max: Int) -> String? {
74
+ guard s.utf16.count > max else { return nil }
75
+ var units = 0
76
+ var end = s.startIndex
77
+ for character in s {
78
+ units += character.utf16.count
79
+ if units > max { break }
80
+ end = s.index(after: end)
81
+ }
82
+ return String(s[..<end])
83
+ }
84
+ }
@@ -0,0 +1,102 @@
1
+ import Foundation
2
+
3
+ /// Reserved event names. Apps cannot `track` a `$` name.
4
+ enum ReservedEvent {
5
+ static let install = "$install"
6
+ static let open = "$open"
7
+ static let signal = "$signal"
8
+ static let deeplink = "$deeplink"
9
+ static let identify = "$identify"
10
+ static let consent = "$consent"
11
+ static let ids = "$ids"
12
+ static let purchaseLink = "$purchase_link"
13
+ static let skan = "$skan"
14
+ static let networkSend = "$network_send"
15
+
16
+ /// What is still enqueued with `analytics == false`. Everything else, custom
17
+ /// events included, is dropped before enqueue.
18
+ static let allowedWithoutAnalyticsConsent: Set<String> = [
19
+ install, open, signal, consent, identify, ids, purchaseLink, skan,
20
+ ]
21
+
22
+ static func isReserved(_ name: String) -> Bool { name.hasPrefix("$") }
23
+ }
24
+
25
+ /// One queued event: the wire envelope plus its encoded size, which the queue's
26
+ /// 1 MB bound and the batch's 256 KB bound are computed from.
27
+ struct QueuedEvent: Codable, Equatable, Sendable {
28
+ let id: String
29
+ let name: String
30
+ let ts: Int64
31
+ let seq: Int64
32
+ let userId: String?
33
+ let props: [String: JSONValue]
34
+ let size: Int
35
+
36
+ enum CodingKeys: String, CodingKey {
37
+ case id, name, ts, seq, props, size
38
+ case userId = "user_id"
39
+ }
40
+
41
+ init(id: String, name: String, ts: Int64, seq: Int64, userId: String?, props: [String: JSONValue]) {
42
+ self.init(id: id, name: name, ts: ts, seq: seq, userId: userId, props: props, size: nil)
43
+ }
44
+
45
+ private init(id: String, name: String, ts: Int64, seq: Int64, userId: String?,
46
+ props: [String: JSONValue], size: Int?) {
47
+ self.id = id
48
+ self.name = name
49
+ self.ts = ts
50
+ self.seq = seq
51
+ self.userId = userId
52
+ self.props = props
53
+ self.size = size ?? KerdlyJSON.encode(
54
+ WireEvent(id: id, name: name, ts: ts, seq: seq, userId: userId, props: props)
55
+ )?.count ?? 256
56
+ }
57
+
58
+ init(from decoder: Decoder) throws {
59
+ let c = try decoder.container(keyedBy: CodingKeys.self)
60
+ self.init(
61
+ id: try c.decode(String.self, forKey: .id),
62
+ name: try c.decode(String.self, forKey: .name),
63
+ ts: try c.decode(Int64.self, forKey: .ts),
64
+ seq: try c.decode(Int64.self, forKey: .seq),
65
+ userId: try c.decodeIfPresent(String.self, forKey: .userId),
66
+ props: try c.decodeIfPresent([String: JSONValue].self, forKey: .props) ?? [:],
67
+ size: try c.decodeIfPresent(Int.self, forKey: .size)
68
+ )
69
+ }
70
+
71
+ var isReserved: Bool { ReservedEvent.isReserved(name) }
72
+
73
+ var wire: WireEvent {
74
+ WireEvent(id: id, name: name, ts: ts, seq: seq, userId: userId, props: props)
75
+ }
76
+ }
77
+
78
+ /// The event as it goes on the wire: `user_id` is omitted when there is none.
79
+ struct WireEvent: Encodable, Equatable, Sendable {
80
+ let id: String
81
+ let name: String
82
+ let ts: Int64
83
+ let seq: Int64
84
+ let userId: String?
85
+ let props: [String: JSONValue]
86
+
87
+ enum CodingKeys: String, CodingKey {
88
+ case id, name, ts, seq, props
89
+ case userId = "user_id"
90
+ }
91
+ }
92
+
93
+ enum Clocks {
94
+ /// Milliseconds since the epoch.
95
+ static func ms(_ date: Date) -> Int64 {
96
+ Int64((date.timeIntervalSince1970 * 1000).rounded())
97
+ }
98
+
99
+ static func date(ms: Int64) -> Date {
100
+ Date(timeIntervalSince1970: TimeInterval(ms) / 1000)
101
+ }
102
+ }
@@ -0,0 +1,26 @@
1
+ import Foundation
2
+
3
+ /// The check the IPv6 echo's answer must pass before it is sent.
4
+ enum PublicIPv6 {
5
+ /// The canonical text (RFC 5952: lowercase, longest zero run as `::`) of a global unicast IPv6
6
+ /// address (2000::/3, the first three bits 001); nil for anything else: IPv4, IPv4-mapped,
7
+ /// loopback, link-local, unique-local, multicast, a zone id or garbage.
8
+ static func globalUnicast(_ text: String) -> String? {
9
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
10
+ // `inet_pton` reads a C string: an embedded NUL would cut it short.
11
+ guard !trimmed.isEmpty, trimmed.utf8.count < Int(INET6_ADDRSTRLEN), !trimmed.utf8.contains(0) else {
12
+ return nil
13
+ }
14
+ var address = in6_addr()
15
+ guard inet_pton(AF_INET6, trimmed, &address) == 1 else { return nil }
16
+ let first = withUnsafeBytes(of: &address) { $0[0] }
17
+ guard first & 0xE0 == 0x20 else { return nil }
18
+ var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
19
+ let canonical = buffer.withUnsafeMutableBufferPointer { out -> String? in
20
+ guard let base = out.baseAddress, inet_ntop(AF_INET6, &address, base, socklen_t(out.count)) != nil
21
+ else { return nil }
22
+ return String(cString: base)
23
+ }
24
+ return canonical?.lowercased()
25
+ }
26
+ }
@@ -0,0 +1,106 @@
1
+ import Foundation
2
+
3
+ /// The result of reading the Keychain copy of the install id.
4
+ enum KeychainRead: Equatable, Sendable {
5
+ case found(String)
6
+ case notFound
7
+ /// The item exists but the device has not been unlocked since boot
8
+ /// (`errSecInteractionNotAllowed`): nothing can be decided until it is.
9
+ case locked
10
+ /// Any other Keychain failure (e.g. a missing entitlement): the Keychain is unusable this launch.
11
+ case failed(Int32)
12
+ }
13
+
14
+ /// `install_state` of a `$install`.
15
+ enum InstallState: String, Sendable {
16
+ case fresh, reinstall, restore
17
+ }
18
+
19
+ struct InstallDecision: Equatable, Sendable {
20
+ let installId: String
21
+ /// nil for an ordinary launch; otherwise a `$install` is due.
22
+ let state: InstallState?
23
+ /// `restore` only: the id found in UserDefaults.
24
+ let restoredFrom: String?
25
+ let writeKeychain: Bool
26
+ let writeDefaults: Bool
27
+ }
28
+
29
+ /// The install-state matrix:
30
+ ///
31
+ /// | Keychain | UserDefaults | Meaning | Action |
32
+ /// |----------|-------------------|-------------------|--------------------------------------------------|
33
+ /// | present | present, equal | ordinary launch | none |
34
+ /// | absent | absent | fresh install | new id in both; `fresh` |
35
+ /// | present | absent | reinstall | keep the Keychain id; write UserDefaults; `reinstall` |
36
+ /// | absent | present | restore elsewhere | NEW id in both; `restore`, `restored_from` = UserDefaults id |
37
+ /// | present | present, different| restore here | keep the Keychain id; rewrite UserDefaults; `restore` |
38
+ ///
39
+ /// Two guards keep a broken Keychain from minting fake restores: a Keychain that cannot be read
40
+ /// (other than "not found"), or one whose last write failed, is not trusted, and UserDefaults alone
41
+ /// decides.
42
+ enum InstallIdentityResolver {
43
+ /// - Returns: nil when the Keychain is locked (before the first unlock): retry later.
44
+ static func decide(keychain: KeychainRead,
45
+ defaults rawDefaults: String?,
46
+ keychainWriteFailedBefore: Bool,
47
+ newId: () -> String) -> InstallDecision? {
48
+ let defaults = normalize(rawDefaults)
49
+ let kc: String?
50
+ let keychainUsable: Bool
51
+ switch keychain {
52
+ case .locked:
53
+ return nil
54
+ case .failed:
55
+ kc = nil
56
+ keychainUsable = false
57
+ case .found(let raw):
58
+ kc = normalize(raw)
59
+ keychainUsable = true
60
+ case .notFound:
61
+ kc = nil
62
+ keychainUsable = true
63
+ }
64
+
65
+ if !keychainUsable || (kc == nil && keychainWriteFailedBefore && defaults != nil) {
66
+ if let d = defaults {
67
+ return InstallDecision(installId: d, state: nil, restoredFrom: nil,
68
+ writeKeychain: true, writeDefaults: false)
69
+ }
70
+ return InstallDecision(installId: newId(), state: .fresh, restoredFrom: nil,
71
+ writeKeychain: true, writeDefaults: true)
72
+ }
73
+
74
+ switch (kc, defaults) {
75
+ case let (k?, d?) where k == d:
76
+ return InstallDecision(installId: k, state: nil, restoredFrom: nil,
77
+ writeKeychain: false, writeDefaults: false)
78
+ case (nil, nil):
79
+ return InstallDecision(installId: newId(), state: .fresh, restoredFrom: nil,
80
+ writeKeychain: true, writeDefaults: true)
81
+ case let (k?, nil):
82
+ return InstallDecision(installId: k, state: .reinstall, restoredFrom: nil,
83
+ writeKeychain: false, writeDefaults: true)
84
+ case let (nil, d?):
85
+ return InstallDecision(installId: newId(), state: .restore, restoredFrom: d,
86
+ writeKeychain: true, writeDefaults: true)
87
+ case let (k?, d?):
88
+ return InstallDecision(installId: k, state: .restore, restoredFrom: d,
89
+ writeKeychain: false, writeDefaults: true)
90
+ }
91
+ }
92
+
93
+ /// A lowercase UUID string, or nil for anything that is not a UUID (a corrupted copy is
94
+ /// treated as absent).
95
+ static func normalize(_ value: String?) -> String? {
96
+ guard let value, let uuid = UUID(uuidString: value.trimmingCharacters(in: .whitespaces)) else {
97
+ return nil
98
+ }
99
+ return uuid.uuidString.lowercased()
100
+ }
101
+
102
+ /// A new lowercase UUIDv4.
103
+ static func makeId() -> String {
104
+ UUID().uuidString.lowercased()
105
+ }
106
+ }
@@ -0,0 +1,198 @@
1
+ import Foundation
2
+
3
+ /// A JSON value. Every payload the SDK builds, sends or stores is one of these, so payloads are
4
+ /// `Sendable` and integers stay integers on the wire (`ts`, `seq`, ms timestamps).
5
+ enum JSONValue: Equatable, Sendable {
6
+ case null
7
+ case bool(Bool)
8
+ case int(Int64)
9
+ case double(Double)
10
+ case string(String)
11
+ case array([JSONValue])
12
+ case object([String: JSONValue])
13
+ }
14
+
15
+ extension JSONValue {
16
+ /// A number; integral doubles are stored as integers so `3.0` encodes as `3`.
17
+ static func number(_ value: Double) -> JSONValue {
18
+ if value.isFinite, value.rounded() == value, abs(value) < 9.0e15 {
19
+ return .int(Int64(value))
20
+ }
21
+ return .double(value)
22
+ }
23
+
24
+ static func string(_ value: String?) -> JSONValue {
25
+ value.map { JSONValue.string($0) } ?? .null
26
+ }
27
+
28
+ static func int(_ value: Int64?) -> JSONValue {
29
+ value.map { JSONValue.int($0) } ?? .null
30
+ }
31
+
32
+ var stringValue: String? {
33
+ if case .string(let s) = self { return s }
34
+ return nil
35
+ }
36
+
37
+ /// A string, or an integer rendered as one (ids the server might send as numbers).
38
+ var lenientStringValue: String? {
39
+ switch self {
40
+ case .string(let s): return s
41
+ case .int(let i): return String(i)
42
+ default: return nil
43
+ }
44
+ }
45
+
46
+ var boolValue: Bool? {
47
+ if case .bool(let b) = self { return b }
48
+ return nil
49
+ }
50
+
51
+ var int64Value: Int64? {
52
+ switch self {
53
+ case .int(let i): return i
54
+ case .double(let d) where d.isFinite && d.rounded() == d && abs(d) < 9.0e18: return Int64(d)
55
+ default: return nil
56
+ }
57
+ }
58
+
59
+ var doubleValue: Double? {
60
+ switch self {
61
+ case .int(let i): return Double(i)
62
+ case .double(let d): return d
63
+ default: return nil
64
+ }
65
+ }
66
+
67
+ var arrayValue: [JSONValue]? {
68
+ if case .array(let a) = self { return a }
69
+ return nil
70
+ }
71
+
72
+ var objectValue: [String: JSONValue]? {
73
+ if case .object(let o) = self { return o }
74
+ return nil
75
+ }
76
+
77
+ var isNull: Bool {
78
+ if case .null = self { return true }
79
+ return false
80
+ }
81
+
82
+ subscript(key: String) -> JSONValue? {
83
+ objectValue?[key]
84
+ }
85
+
86
+ /// Foundation form (`NSNull` for null), for the public `KerdlyAttribution.raw`.
87
+ var anyValue: Any {
88
+ switch self {
89
+ case .null: return NSNull()
90
+ case .bool(let b): return b
91
+ case .int(let i): return i
92
+ case .double(let d): return d
93
+ case .string(let s): return s
94
+ case .array(let a): return a.map { $0.anyValue }
95
+ case .object(let o): return o.mapValues { $0.anyValue }
96
+ }
97
+ }
98
+
99
+ /// Converts a Foundation value (from `JSONSerialization` or an app's `[String: Any]`).
100
+ /// `NSNumber` booleans are told apart from numbers; non-finite numbers and other types are nil.
101
+ init?(any value: Any) {
102
+ switch value {
103
+ case is NSNull:
104
+ self = .null
105
+ case let s as String:
106
+ self = .string(s)
107
+ case let n as NSNumber:
108
+ if CFGetTypeID(n) == CFBooleanGetTypeID() {
109
+ self = .bool(n.boolValue)
110
+ } else if CFNumberIsFloatType(n) {
111
+ let d = n.doubleValue
112
+ guard d.isFinite else { return nil }
113
+ self = .number(d)
114
+ } else {
115
+ self = .int(n.int64Value)
116
+ }
117
+ case let a as [Any]:
118
+ var out: [JSONValue] = []
119
+ out.reserveCapacity(a.count)
120
+ for item in a {
121
+ guard let v = JSONValue(any: item) else { return nil }
122
+ out.append(v)
123
+ }
124
+ self = .array(out)
125
+ case let o as [String: Any]:
126
+ var out: [String: JSONValue] = [:]
127
+ for (k, item) in o {
128
+ guard let v = JSONValue(any: item) else { return nil }
129
+ out[k] = v
130
+ }
131
+ self = .object(out)
132
+ default:
133
+ return nil
134
+ }
135
+ }
136
+
137
+ /// Parses JSON bytes. Fragments (a bare string or number) are allowed.
138
+ static func parse(_ data: Data) -> JSONValue? {
139
+ guard !data.isEmpty,
140
+ let obj = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
141
+ else { return nil }
142
+ return JSONValue(any: obj)
143
+ }
144
+ }
145
+
146
+ extension JSONValue: Codable {
147
+ init(from decoder: Decoder) throws {
148
+ let c = try decoder.singleValueContainer()
149
+ if c.decodeNil() {
150
+ self = .null
151
+ } else if let b = try? c.decode(Bool.self) {
152
+ self = .bool(b)
153
+ } else if let i = try? c.decode(Int64.self) {
154
+ self = .int(i)
155
+ } else if let d = try? c.decode(Double.self) {
156
+ self = .double(d)
157
+ } else if let s = try? c.decode(String.self) {
158
+ self = .string(s)
159
+ } else if let a = try? c.decode([JSONValue].self) {
160
+ self = .array(a)
161
+ } else if let o = try? c.decode([String: JSONValue].self) {
162
+ self = .object(o)
163
+ } else {
164
+ throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unsupported JSON value")
165
+ }
166
+ }
167
+
168
+ func encode(to encoder: Encoder) throws {
169
+ var c = encoder.singleValueContainer()
170
+ switch self {
171
+ case .null: try c.encodeNil()
172
+ case .bool(let b): try c.encode(b)
173
+ case .int(let i): try c.encode(i)
174
+ case .double(let d): try c.encode(d)
175
+ case .string(let s): try c.encode(s)
176
+ case .array(let a): try c.encode(a)
177
+ case .object(let o): try c.encode(o)
178
+ }
179
+ }
180
+ }
181
+
182
+ /// One encoder configuration for everything the SDK writes: sorted keys (stable output and stable
183
+ /// context hashes) and unescaped slashes (readable URLs).
184
+ enum KerdlyJSON {
185
+ static func encoder() -> JSONEncoder {
186
+ let e = JSONEncoder()
187
+ e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
188
+ return e
189
+ }
190
+
191
+ static func encode<T: Encodable>(_ value: T) -> Data? {
192
+ try? encoder().encode(value)
193
+ }
194
+
195
+ static func decode<T: Decodable>(_ type: T.Type, from data: Data) -> T? {
196
+ try? JSONDecoder().decode(type, from: data)
197
+ }
198
+ }
@@ -0,0 +1,84 @@
1
+ import Foundation
2
+
3
+ /// A verified StoreKit 2 transaction, reduced to what `$purchase_link` and the SKAN triggers need.
4
+ struct PurchaseInfo: Equatable, Sendable {
5
+ let originalTransactionId: String
6
+ let transactionId: String
7
+ let productId: String
8
+ /// Lowercase UUID string.
9
+ let appAccountToken: String?
10
+ let appTransactionId: String?
11
+ let purchaseDate: Date
12
+ let originalPurchaseDate: Date
13
+ /// `introductory` | `promotional` | `offer_code` | `win_back` | nil.
14
+ let offerType: String?
15
+ let isFreeTrial: Bool
16
+ /// `Production` | `Sandbox` | `Xcode`.
17
+ let environment: String?
18
+ let isRenewal: Bool?
19
+ let revoked: Bool
20
+
21
+ var facts: PurchaseFacts {
22
+ PurchaseFacts(isFreeTrial: isFreeTrial, purchaseDate: purchaseDate,
23
+ originalPurchaseDate: originalPurchaseDate, isRenewal: isRenewal, revoked: revoked)
24
+ }
25
+ }
26
+
27
+ /// Where a purchase link came from (`$purchase_link.source`).
28
+ enum PurchaseSource: String, Sendable {
29
+ case notify, entitlements, updates
30
+ }
31
+
32
+ /// The app's `notifyPurchase` ids, in Sendable form.
33
+ struct NotifiedPurchase: Equatable, Sendable {
34
+ var originalTransactionId: String?
35
+ var transactionId: String?
36
+ var productId: String?
37
+ var appAccountToken: String?
38
+
39
+ init(_ purchase: KerdlyPurchase) {
40
+ func clean(_ s: String?) -> String? {
41
+ guard let t = s?.trimmingCharacters(in: .whitespacesAndNewlines), !t.isEmpty else { return nil }
42
+ return t
43
+ }
44
+ originalTransactionId = clean(purchase.originalTransactionId)
45
+ transactionId = clean(purchase.transactionId)
46
+ productId = clean(purchase.productId)
47
+ appAccountToken = purchase.appAccountToken?.uuidString.lowercased()
48
+ }
49
+
50
+ var hasIds: Bool { originalTransactionId != nil || transactionId != nil }
51
+ }
52
+
53
+ enum PurchaseLinks {
54
+ /// The ids a link is deduplicated on: its original transaction id (one link per `originalID`),
55
+ /// plus its transaction id, which is all a notify without the original id is known by.
56
+ static func dedupeKeys(info: PurchaseInfo?, notified: NotifiedPurchase?) -> [String] {
57
+ var keys: [String] = []
58
+ for key in [notified?.originalTransactionId, info?.originalTransactionId,
59
+ notified?.transactionId, info?.transactionId] {
60
+ if let key, !keys.contains(key) { keys.append(key) }
61
+ }
62
+ return keys
63
+ }
64
+
65
+ static func isReported(_ keys: [String], in reported: [String]) -> Bool {
66
+ keys.contains { reported.contains($0) }
67
+ }
68
+
69
+ /// `$purchase_link` props for iOS. The app's notified ids win over what StoreKit reported.
70
+ static func props(info: PurchaseInfo?, notified: NotifiedPurchase?, source: PurchaseSource) -> [String: JSONValue] {
71
+ [
72
+ "store": .string("app_store"),
73
+ "original_transaction_id": .string(notified?.originalTransactionId ?? info?.originalTransactionId),
74
+ "transaction_id": .string(notified?.transactionId ?? info?.transactionId),
75
+ "product_id": .string(notified?.productId ?? info?.productId),
76
+ "app_account_token": .string(notified?.appAccountToken ?? info?.appAccountToken),
77
+ "app_transaction_id": .string(info?.appTransactionId),
78
+ "purchase_date": .int(info.map { Clocks.ms($0.purchaseDate) }),
79
+ "offer_type": .string(info?.offerType),
80
+ "environment": .string(info?.environment),
81
+ "source": .string(source.rawValue),
82
+ ]
83
+ }
84
+ }