@kerdly/expo 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +235 -2
- package/android/build.gradle +61 -0
- package/android/src/main/AndroidManifest.xml +19 -0
- package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
- package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
- package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
- package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +111 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
- package/app.plugin.js +2 -0
- package/build/Kerdly.d.ts +106 -0
- package/build/Kerdly.d.ts.map +1 -0
- package/build/Kerdly.js +494 -0
- package/build/Kerdly.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +2 -0
- package/build/index.js.map +1 -0
- package/build/log.d.ts +13 -0
- package/build/log.d.ts.map +1 -0
- package/build/log.js +45 -0
- package/build/log.js.map +1 -0
- package/build/native.d.ts +74 -0
- package/build/native.d.ts.map +1 -0
- package/build/native.js +56 -0
- package/build/native.js.map +1 -0
- package/build/normalize.d.ts +8 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +86 -0
- package/build/normalize.js.map +1 -0
- package/build/types.d.ts +134 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +3 -0
- package/build/types.js.map +1 -0
- package/build/validation.d.ts +70 -0
- package/build/validation.d.ts.map +1 -0
- package/build/validation.js +349 -0
- package/build/validation.js.map +1 -0
- package/build/version.d.ts +4 -0
- package/build/version.d.ts.map +1 -0
- package/build/version.js +5 -0
- package/build/version.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/KerdlySDK/.kerdly-sync.json +7 -0
- package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
- package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
- package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
- package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
- package/ios/KerdlySDK/Core/Support.swift +95 -0
- package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
- package/ios/KerdlySDK/Logic/Batch.swift +180 -0
- package/ios/KerdlySDK/Logic/Context.swift +85 -0
- package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
- package/ios/KerdlySDK/Logic/DeferredLinks.swift +239 -0
- package/ios/KerdlySDK/Logic/Environment.swift +39 -0
- package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
- package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
- package/ios/KerdlySDK/Logic/Events.swift +102 -0
- package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
- package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
- package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
- package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
- package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
- package/ios/KerdlySDK/Logic/Skan.swift +343 -0
- package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
- package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
- package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
- package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
- package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
- package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
- package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
- package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
- package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
- package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
- package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
- package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
- package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +95 -0
- package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
- package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
- package/ios/KerdlySdk.podspec +45 -0
- package/ios/KerdlySdkModule.swift +332 -0
- package/package.json +92 -4
- package/plugin/withKerdly.js +163 -0
- package/src/Kerdly.ts +524 -0
- package/src/index.ts +23 -0
- package/src/log.ts +49 -0
- package/src/native.ts +150 -0
- package/src/normalize.ts +82 -0
- package/src/types.ts +183 -0
- package/src/validation.ts +343 -0
- package/src/version.ts +5 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The fixed part of every batch.
|
|
4
|
+
struct BatchEnvelope: Equatable, Sendable {
|
|
5
|
+
var sdkName: String
|
|
6
|
+
var sdkVersion: String
|
|
7
|
+
var wrapper: String?
|
|
8
|
+
var bundle: String
|
|
9
|
+
var appVersion: String
|
|
10
|
+
var appBuild: String
|
|
11
|
+
var environment: String
|
|
12
|
+
var installId: String
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/// `POST /v1/sdk/batch` body. Optional members are omitted when nil (`context` when unchanged,
|
|
16
|
+
/// `sdk.wrapper` when there is no wrapper, an event's `user_id` when there is no user).
|
|
17
|
+
struct BatchRequest: Encodable, Sendable {
|
|
18
|
+
struct SDK: Encodable, Sendable {
|
|
19
|
+
let name: String
|
|
20
|
+
let version: String
|
|
21
|
+
let wrapper: String?
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
struct App: Encodable, Sendable {
|
|
25
|
+
let bundle: String
|
|
26
|
+
let version: String
|
|
27
|
+
let build: String
|
|
28
|
+
let environment: String
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let sdk: SDK
|
|
32
|
+
let app: App
|
|
33
|
+
let installId: String
|
|
34
|
+
let sentAt: Int64
|
|
35
|
+
let context: JSONValue?
|
|
36
|
+
let events: [WireEvent]
|
|
37
|
+
|
|
38
|
+
enum CodingKeys: String, CodingKey {
|
|
39
|
+
case sdk, app, context, events
|
|
40
|
+
case installId = "install_id"
|
|
41
|
+
case sentAt = "sent_at"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
enum BatchBuilder {
|
|
46
|
+
/// ≤ 50 events, ≤ 256 KB uncompressed body.
|
|
47
|
+
static let maxEvents = 50
|
|
48
|
+
static let maxBodyBytes = 256 * 1024
|
|
49
|
+
|
|
50
|
+
static func request(envelope: BatchEnvelope, sentAt: Int64, context: JSONValue?,
|
|
51
|
+
events: [QueuedEvent]) -> BatchRequest {
|
|
52
|
+
BatchRequest(
|
|
53
|
+
sdk: .init(name: envelope.sdkName, version: envelope.sdkVersion, wrapper: envelope.wrapper),
|
|
54
|
+
app: .init(bundle: envelope.bundle, version: envelope.appVersion, build: envelope.appBuild,
|
|
55
|
+
environment: envelope.environment),
|
|
56
|
+
installId: envelope.installId,
|
|
57
|
+
sentAt: sentAt,
|
|
58
|
+
context: context,
|
|
59
|
+
events: events.map(\.wire)
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
static func body(envelope: BatchEnvelope, sentAt: Int64, context: JSONValue?,
|
|
64
|
+
events: [QueuedEvent]) -> Data? {
|
|
65
|
+
KerdlyJSON.encode(request(envelope: envelope, sentAt: sentAt, context: context, events: events))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// Bytes the envelope (everything but the events) takes, for the batch size budget.
|
|
69
|
+
static func overheadBytes(envelope: BatchEnvelope, context: JSONValue?) -> Int {
|
|
70
|
+
body(envelope: envelope, sentAt: Int64.max, context: context, events: [])?.count ?? 2_048
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// A `rejected` entry of the batch response.
|
|
75
|
+
struct RejectedEvent: Equatable, Sendable {
|
|
76
|
+
let id: String
|
|
77
|
+
let reason: String
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// The 200 response of `POST /v1/sdk/batch`. Missing members read as empty.
|
|
81
|
+
struct BatchResponse: Equatable, Sendable {
|
|
82
|
+
var accepted: [String] = []
|
|
83
|
+
var rejected: [RejectedEvent] = []
|
|
84
|
+
var configEtag: String?
|
|
85
|
+
var attribution: [String: JSONValue]?
|
|
86
|
+
var needs: [String] = []
|
|
87
|
+
var cvHints: [JSONValue] = []
|
|
88
|
+
|
|
89
|
+
/// nil when the body is not a JSON object.
|
|
90
|
+
static func parse(_ data: Data) -> BatchResponse? {
|
|
91
|
+
guard let object = JSONValue.parse(data)?.objectValue else { return nil }
|
|
92
|
+
var response = BatchResponse()
|
|
93
|
+
response.accepted = object["accepted"]?.arrayValue?.compactMap(\.stringValue) ?? []
|
|
94
|
+
response.rejected = object["rejected"]?.arrayValue?.compactMap { item -> RejectedEvent? in
|
|
95
|
+
guard let id = item["id"]?.stringValue else { return nil }
|
|
96
|
+
return RejectedEvent(id: id, reason: item["reason"]?.stringValue ?? "unknown")
|
|
97
|
+
} ?? []
|
|
98
|
+
response.configEtag = object["config_etag"]?.stringValue
|
|
99
|
+
response.attribution = object["attribution"]?.objectValue
|
|
100
|
+
response.needs = object["needs"]?.arrayValue?.compactMap(\.stringValue) ?? []
|
|
101
|
+
response.cvHints = object["cv_hints"]?.arrayValue ?? []
|
|
102
|
+
return response
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// Every id the response settles: accepted (stored, or a duplicate) and rejected (permanent).
|
|
106
|
+
var settledIds: Set<String> {
|
|
107
|
+
Set(accepted).union(rejected.map(\.id))
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/// What to do with a batch after the collector answered (status table).
|
|
112
|
+
enum DeliveryOutcome: Equatable, Sendable {
|
|
113
|
+
/// 200: remove every accepted and rejected id; ids in neither list stay queued.
|
|
114
|
+
case success(BatchResponse)
|
|
115
|
+
/// 400 and unlisted 4xx: drop the batch. 401/403 also stop sending until the next launch.
|
|
116
|
+
case drop(code: String, stopUntilNextLaunch: Bool)
|
|
117
|
+
/// 408, 429, 404, 5xx, network errors, an unreadable 200: retry later. `retryAfter` is the
|
|
118
|
+
/// server's `Retry-After`, which wins over the back-off.
|
|
119
|
+
case retry(retryAfter: TimeInterval?)
|
|
120
|
+
/// 413: split the batch in half and retry; a single event still too large is dropped.
|
|
121
|
+
case split
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
enum DeliveryPolicy {
|
|
125
|
+
/// - Parameters:
|
|
126
|
+
/// - status: the HTTP status, nil for a network error.
|
|
127
|
+
static func classify(status: Int?, headers: [String: String], body: Data, now: Date) -> DeliveryOutcome {
|
|
128
|
+
guard let status else { return .retry(retryAfter: nil) }
|
|
129
|
+
let code = errorCode(body) ?? "http_\(status)"
|
|
130
|
+
switch status {
|
|
131
|
+
case 200..<300:
|
|
132
|
+
guard let response = BatchResponse.parse(body) else { return .retry(retryAfter: nil) }
|
|
133
|
+
return .success(response)
|
|
134
|
+
case 401, 403:
|
|
135
|
+
return .drop(code: code, stopUntilNextLaunch: true)
|
|
136
|
+
case 408, 429:
|
|
137
|
+
return .retry(retryAfter: retryAfter(headers: headers, now: now))
|
|
138
|
+
case 413:
|
|
139
|
+
return .split
|
|
140
|
+
case 404:
|
|
141
|
+
// A missing route is a deployment or endpoint problem, not a bad batch: keep the events.
|
|
142
|
+
return .retry(retryAfter: retryAfter(headers: headers, now: now))
|
|
143
|
+
case 400..<500:
|
|
144
|
+
return .drop(code: code, stopUntilNextLaunch: false)
|
|
145
|
+
default:
|
|
146
|
+
return .retry(retryAfter: retryAfter(headers: headers, now: now))
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/// The `code` of an error body `{"error": …, "code": …}`.
|
|
151
|
+
static func errorCode(_ body: Data) -> String? {
|
|
152
|
+
JSONValue.parse(body)?["code"]?.stringValue
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// `Retry-After` in seconds (delta-seconds or an HTTP date), clamped to [0, 1 h]. Header names
|
|
156
|
+
/// are expected lowercased.
|
|
157
|
+
static func retryAfter(headers: [String: String], now: Date) -> TimeInterval? {
|
|
158
|
+
guard let raw = headers["retry-after"]?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else {
|
|
159
|
+
return nil
|
|
160
|
+
}
|
|
161
|
+
let seconds: TimeInterval
|
|
162
|
+
if let value = Double(raw) {
|
|
163
|
+
seconds = value
|
|
164
|
+
} else if let date = httpDate(raw) {
|
|
165
|
+
seconds = date.timeIntervalSince(now)
|
|
166
|
+
} else {
|
|
167
|
+
return nil
|
|
168
|
+
}
|
|
169
|
+
guard seconds.isFinite else { return nil }
|
|
170
|
+
return min(max(seconds, 0), 3_600)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private static func httpDate(_ value: String) -> Date? {
|
|
174
|
+
let formatter = DateFormatter()
|
|
175
|
+
formatter.locale = Locale(identifier: "en_US_POSIX")
|
|
176
|
+
formatter.timeZone = TimeZone(identifier: "GMT")
|
|
177
|
+
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
|
|
178
|
+
return formatter.date(from: value)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// App identity from the main bundle.
|
|
4
|
+
struct AppInfo: Equatable, Sendable {
|
|
5
|
+
var bundle: String
|
|
6
|
+
var version: String
|
|
7
|
+
var build: String
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/// Device facts that need the main thread (UIKit), captured once and refreshed on activation.
|
|
11
|
+
struct DeviceSnapshot: Equatable, Sendable {
|
|
12
|
+
var idfv: String?
|
|
13
|
+
var screenWidth: Int
|
|
14
|
+
var screenHeight: Int
|
|
15
|
+
var screenScale: Double
|
|
16
|
+
/// `applicationState != .background`.
|
|
17
|
+
var isForeground: Bool
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// Device facts readable from any thread.
|
|
21
|
+
struct DeviceFacts: Equatable, Sendable {
|
|
22
|
+
var os: String
|
|
23
|
+
var model: String
|
|
24
|
+
var locale: String
|
|
25
|
+
var languages: [String]
|
|
26
|
+
var timeZone: String
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
enum ContextBuilder {
|
|
30
|
+
/// The batch `context`: the device fields plus `consent`. `lat` is Android-only.
|
|
31
|
+
static func context(facts: DeviceFacts, snapshot: DeviceSnapshot?, att: KerdlyAttStatus,
|
|
32
|
+
analytics: Bool, ads: Bool, app: AppInfo) -> JSONValue {
|
|
33
|
+
var object = deviceFields(facts: facts, snapshot: snapshot, att: att, app: app)
|
|
34
|
+
object["consent"] = .object(["analytics": .bool(analytics), "ads": .bool(ads)])
|
|
35
|
+
return .object(object)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// `$install`'s `device`: the context's fields without `consent`, built by the
|
|
39
|
+
/// same code so the two never differ.
|
|
40
|
+
static func device(facts: DeviceFacts, snapshot: DeviceSnapshot?, att: KerdlyAttStatus,
|
|
41
|
+
app: AppInfo) -> JSONValue {
|
|
42
|
+
.object(deviceFields(facts: facts, snapshot: snapshot, att: att, app: app))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// `screen` and `idfv` come from the UIKit snapshot and are omitted while there is none; `idfv`
|
|
46
|
+
/// also when UIKit does not know it yet.
|
|
47
|
+
private static func deviceFields(facts: DeviceFacts, snapshot: DeviceSnapshot?, att: KerdlyAttStatus,
|
|
48
|
+
app: AppInfo) -> [String: JSONValue] {
|
|
49
|
+
var object: [String: JSONValue] = [
|
|
50
|
+
"platform": .string("ios"),
|
|
51
|
+
"os": .string(facts.os),
|
|
52
|
+
"model": .string(facts.model),
|
|
53
|
+
"manufacturer": .string("Apple"),
|
|
54
|
+
"locale": .string(facts.locale),
|
|
55
|
+
"languages": .array(facts.languages.prefix(5).map { .string($0) }),
|
|
56
|
+
"tz": .string(facts.timeZone),
|
|
57
|
+
"att": .string(att.rawValue),
|
|
58
|
+
"app_version": .string(app.version),
|
|
59
|
+
"app_build": .string(app.build),
|
|
60
|
+
]
|
|
61
|
+
if let snapshot {
|
|
62
|
+
object["screen"] = .object([
|
|
63
|
+
"w": .int(Int64(snapshot.screenWidth)),
|
|
64
|
+
"h": .int(Int64(snapshot.screenHeight)),
|
|
65
|
+
"scale": .number(snapshot.screenScale),
|
|
66
|
+
])
|
|
67
|
+
if let idfv = snapshot.idfv {
|
|
68
|
+
object["idfv"] = .string(idfv)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return object
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// `Locale.current.identifier` without `@…` keywords (e.g. `en_US@calendar=japanese` → `en_US`).
|
|
75
|
+
static func localeIdentifier(_ identifier: String) -> String {
|
|
76
|
+
String(identifier.split(separator: "@", maxSplits: 1).first ?? Substring(identifier))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// "26.0.1"; the patch is omitted when 0, as `UIDevice.systemVersion` does.
|
|
80
|
+
static func osVersion(_ v: OperatingSystemVersion) -> String {
|
|
81
|
+
v.patchVersion > 0
|
|
82
|
+
? "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
|
|
83
|
+
: "\(v.majorVersion).\(v.minorVersion)"
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The params `handleUrl` reads. They come from the query string whatever the
|
|
4
|
+
/// scheme, host or path, e.g. `myapp://onboarding?cpp=<slug>`.
|
|
5
|
+
struct ParsedDeepLink: Equatable, Sendable {
|
|
6
|
+
/// The URL as given, truncated to `DeepLinkParser.maxUrlLength`.
|
|
7
|
+
let url: String
|
|
8
|
+
let cpp: String?
|
|
9
|
+
let ppid: String?
|
|
10
|
+
/// A Kerdly link's click id (`kerdly_c`).
|
|
11
|
+
let clickId: String?
|
|
12
|
+
/// The web visit the link continues (`kerdly_v`).
|
|
13
|
+
let visitId: String?
|
|
14
|
+
let campaignIds: String?
|
|
15
|
+
|
|
16
|
+
/// Carries an attribution tag, so it is kept pending until a batch containing it is accepted.
|
|
17
|
+
var isAttributionBearing: Bool {
|
|
18
|
+
cpp != nil || ppid != nil || clickId != nil || visitId != nil
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
var props: [String: JSONValue] {
|
|
22
|
+
[
|
|
23
|
+
"url": .string(url),
|
|
24
|
+
"cpp": .string(cpp),
|
|
25
|
+
"ppid": .string(ppid),
|
|
26
|
+
"kerdly_c": .string(clickId),
|
|
27
|
+
"kerdly_v": .string(visitId),
|
|
28
|
+
"campaign_ids": .string(campaignIds),
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
enum DeepLinkParser {
|
|
34
|
+
static let maxUrlLength = 4_096
|
|
35
|
+
|
|
36
|
+
static func parse(_ url: URL) -> ParsedDeepLink? {
|
|
37
|
+
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
|
|
38
|
+
?? URLComponents(string: url.absoluteString)
|
|
39
|
+
else { return nil }
|
|
40
|
+
let items = components.queryItems ?? []
|
|
41
|
+
func value(_ name: String) -> String? {
|
|
42
|
+
for item in items where item.name == name {
|
|
43
|
+
if let v = item.value?.trimmingCharacters(in: .whitespacesAndNewlines), !v.isEmpty {
|
|
44
|
+
return v
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return nil
|
|
48
|
+
}
|
|
49
|
+
return ParsedDeepLink(
|
|
50
|
+
url: String(url.absoluteString.prefix(maxUrlLength)),
|
|
51
|
+
cpp: value("cpp"),
|
|
52
|
+
ppid: value("ppid"),
|
|
53
|
+
// Links made before 0.1.0 spell these `afr_c` and `afr_v`.
|
|
54
|
+
clickId: value("kerdly_c") ?? value("afr_c"),
|
|
55
|
+
visitId: value("kerdly_v") ?? value("afr_v"),
|
|
56
|
+
campaignIds: value("campaign_ids")
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Decides `$deeplink.source`. A caller that knows it (the Expo bridge: React Native's initial URL
|
|
62
|
+
/// vs its `url` events) passes `"initial"` or `"runtime"`, which wins. Otherwise it is inferred: the
|
|
63
|
+
/// first URL handled in this process, within a minute of `configure` and before the app has gone to
|
|
64
|
+
/// the background, is the launch URL (`initial`); everything else is `runtime`. Any handled URL, an
|
|
65
|
+
/// explicit `"initial"` included, uses up the inferred initial.
|
|
66
|
+
struct DeepLinkSourceTracker: Sendable {
|
|
67
|
+
static let initialWindow: TimeInterval = 60
|
|
68
|
+
static let sources: Set<String> = ["initial", "runtime"]
|
|
69
|
+
|
|
70
|
+
private(set) var handledAny = false
|
|
71
|
+
private(set) var backgroundedSinceConfigure = false
|
|
72
|
+
let configuredAt: Date
|
|
73
|
+
|
|
74
|
+
init(configuredAt: Date) {
|
|
75
|
+
self.configuredAt = configuredAt
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
mutating func didEnterBackground() {
|
|
79
|
+
backgroundedSinceConfigure = true
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// - Parameter explicit: the caller's `source`; any value other than `"initial"` / `"runtime"`
|
|
83
|
+
/// (or nil) falls back to the inference.
|
|
84
|
+
mutating func source(at now: Date, explicit: String? = nil) -> String {
|
|
85
|
+
defer { handledAny = true }
|
|
86
|
+
if let explicit, Self.sources.contains(explicit) {
|
|
87
|
+
return explicit
|
|
88
|
+
}
|
|
89
|
+
let initial = !handledAny && !backgroundedSinceConfigure
|
|
90
|
+
&& now.timeIntervalSince(configuredAt) <= Self.initialWindow
|
|
91
|
+
return initial ? "initial" : "runtime"
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Deferred deep links: the networks' own requests, sent from the device, so a network can say
|
|
4
|
+
/// which of its ads an install came from. Each request mirrors the network SDK's own, field for
|
|
5
|
+
/// field: Meta from FBSDKCoreKit 18.1.1 (`FBSDKAppLinkUtility fetchDeferredAppLink`), TikTok from
|
|
6
|
+
/// TikTokBusinessSDK 1.7.1 (`fetchDeferredDeeplinkWithConfig`).
|
|
7
|
+
///
|
|
8
|
+
/// Pure: the core gathers the device facts and sends the request.
|
|
9
|
+
|
|
10
|
+
/// What the requests need from the device.
|
|
11
|
+
struct DdlDeviceFacts: Equatable, Sendable {
|
|
12
|
+
var bundleId: String
|
|
13
|
+
var appName: String
|
|
14
|
+
var appVersion: String
|
|
15
|
+
var appBuild: String
|
|
16
|
+
var os: String
|
|
17
|
+
var model: String
|
|
18
|
+
/// `Locale.current.identifier`, e.g. `en_US` (Meta's `extinfo`).
|
|
19
|
+
var localeIdentifier: String
|
|
20
|
+
/// The first preferred language, e.g. `en-US` (TikTok's `locale`).
|
|
21
|
+
var preferredLanguage: String
|
|
22
|
+
var regionCode: String
|
|
23
|
+
var timeZoneName: String
|
|
24
|
+
var timeZoneAbbrev: String
|
|
25
|
+
/// Screen size in points.
|
|
26
|
+
var screenWidth: Int
|
|
27
|
+
var screenHeight: Int
|
|
28
|
+
var screenScale: Double
|
|
29
|
+
var coreCount: Int
|
|
30
|
+
/// Empty unless tracking is authorized.
|
|
31
|
+
var idfa: String
|
|
32
|
+
var idfv: String?
|
|
33
|
+
/// The app's `CFBundleURLSchemes`.
|
|
34
|
+
var urlSchemes: [String]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// One network's answer.
|
|
38
|
+
struct DdlAnswer: Equatable, Sendable {
|
|
39
|
+
enum Status: String, Sendable {
|
|
40
|
+
case link, none, error
|
|
41
|
+
case skippedAtt = "skipped_att"
|
|
42
|
+
case skippedConsent = "skipped_consent"
|
|
43
|
+
case notConfigured = "not_configured"
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
var network: String
|
|
47
|
+
var status: Status
|
|
48
|
+
var url: String?
|
|
49
|
+
/// As the network gave it (Meta: `click_time`).
|
|
50
|
+
var clickTime: String?
|
|
51
|
+
var httpStatus: Int?
|
|
52
|
+
/// The error, or the start of an unexpected body.
|
|
53
|
+
var detail: String?
|
|
54
|
+
|
|
55
|
+
static func skipped(_ network: String, _ status: Status, _ detail: String? = nil) -> DdlAnswer {
|
|
56
|
+
DdlAnswer(network: network, status: status, url: nil, clickTime: nil, httpStatus: nil, detail: detail)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
extension DdlAnswer {
|
|
61
|
+
/// No answer, a 429 or a 5xx: worth asking again. Any other answer, a refusal included, is final.
|
|
62
|
+
var isTransient: Bool {
|
|
63
|
+
guard status == .error else { return false }
|
|
64
|
+
guard let code = httpStatus else { return true }
|
|
65
|
+
return code == 429 || code >= 500
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// The network's click time in ms. Meta gives Unix seconds, as a string or a number.
|
|
69
|
+
var clickTimeMs: Int64? {
|
|
70
|
+
guard let raw = clickTime?.trimmingCharacters(in: .whitespaces), let value = Double(raw),
|
|
71
|
+
value.isFinite, value > 0 else { return nil }
|
|
72
|
+
return Int64(value < 100_000_000_000 ? value * 1_000 : value)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
enum MetaDdl {
|
|
77
|
+
static let network = "meta"
|
|
78
|
+
/// The hosts FBSDKCoreKit's default domain config routes `/activities` to: `ep1` with tracking
|
|
79
|
+
/// authorized, `ep2` without. Only `ep1` is a tracking domain in the privacy manifest (FBSDK
|
|
80
|
+
/// refuses `ep2` as one), so iOS lets the `ep2` request through for a user who denied tracking.
|
|
81
|
+
static let trackingHost = "ep1.facebook.com"
|
|
82
|
+
static let noTrackingHost = "ep2.facebook.com"
|
|
83
|
+
/// FBSDKCoreKit 18.1.1's `FBSDK_DEFAULT_GRAPH_API_VERSION`.
|
|
84
|
+
static let defaultGraphVersion = "v26.0"
|
|
85
|
+
|
|
86
|
+
/// FBSDKAppEventsDeviceInfo's 16-slot `extinfo`, version `i2`. Carrier is empty since iOS 16;
|
|
87
|
+
/// slots 13–14 (disk) are -1, as the SDK sends them.
|
|
88
|
+
static func extinfo(_ f: DdlDeviceFacts) -> String {
|
|
89
|
+
let density = f.screenScale > 0 ? String(format: "%.02f", f.screenScale) : ""
|
|
90
|
+
let slots: [Any] = [
|
|
91
|
+
"i2", f.bundleId, f.appBuild, f.appVersion, f.os, f.model, f.localeIdentifier,
|
|
92
|
+
f.timeZoneAbbrev, "", f.screenWidth, f.screenHeight, density, f.coreCount, -1, -1, f.timeZoneName,
|
|
93
|
+
]
|
|
94
|
+
return json(slots) ?? "[]"
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// `POST https://<host>/<version>/<app id>/activities`, form-encoded, signed with the app's
|
|
98
|
+
/// public client token. With tracking authorized: `ep1`, the IDFA and
|
|
99
|
+
/// `advertiser_tracking_enabled=1`. Without: `ep2`, no IDFA and `0`, as FBSDKCoreKit sends it.
|
|
100
|
+
/// `application_tracking_enabled` and `advertiser_id_collection_enabled` are app settings in
|
|
101
|
+
/// FBSDKCoreKit, not the ATT status, so both stay `1`.
|
|
102
|
+
static func request(appId: String, clientToken: String, anonId: String, facts: DdlDeviceFacts,
|
|
103
|
+
trackingAuthorized: Bool, graphVersion: String = defaultGraphVersion) -> HTTPRequest? {
|
|
104
|
+
let host = trackingAuthorized ? trackingHost : noTrackingHost
|
|
105
|
+
guard !appId.isEmpty, !clientToken.isEmpty,
|
|
106
|
+
let url = URL(string: "https://\(host)/\(graphVersion)/\(appId)/activities") else { return nil }
|
|
107
|
+
var fields: [(String, String)] = [("event", "DEFERRED_APP_LINK")]
|
|
108
|
+
if trackingAuthorized { fields.append(("advertiser_id", facts.idfa)) }
|
|
109
|
+
fields += [
|
|
110
|
+
("anon_id", anonId),
|
|
111
|
+
("advertiser_tracking_enabled", trackingAuthorized ? "1" : "0"),
|
|
112
|
+
("ud", "{}"),
|
|
113
|
+
("application_tracking_enabled", "1"),
|
|
114
|
+
("advertiser_id_collection_enabled", "1"),
|
|
115
|
+
("extinfo", extinfo(facts)),
|
|
116
|
+
]
|
|
117
|
+
if !facts.urlSchemes.isEmpty, let schemes = json(facts.urlSchemes) {
|
|
118
|
+
fields.append(("url_schemes", schemes))
|
|
119
|
+
}
|
|
120
|
+
fields += [("format", "json"), ("sdk", "ios"), ("include_headers", "false"),
|
|
121
|
+
("access_token", "\(appId)|\(clientToken)")]
|
|
122
|
+
let body = fields.map { "\(formEncode($0.0))=\(formEncode($0.1))" }.joined(separator: "&")
|
|
123
|
+
return HTTPRequest(method: "POST", url: url,
|
|
124
|
+
headers: ["Content-Type": "application/x-www-form-urlencoded"],
|
|
125
|
+
body: Data(body.utf8))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// `{"applink_url": …, "click_time": …}` when Meta has a link for this device; `{}` otherwise.
|
|
129
|
+
static func parse(_ result: HTTPResult) -> DdlAnswer {
|
|
130
|
+
switch result {
|
|
131
|
+
case .failure(let reason):
|
|
132
|
+
return DdlAnswer(network: network, status: .error, url: nil, clickTime: nil, httpStatus: nil, detail: reason)
|
|
133
|
+
case .response(let status, _, let body):
|
|
134
|
+
let object = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
|
|
135
|
+
guard status == 200, let object else {
|
|
136
|
+
let error = (object?["error"] as? [String: Any]).map { "\($0["code"] ?? "")/\($0["error_subcode"] ?? "") \($0["message"] ?? "")" }
|
|
137
|
+
return DdlAnswer(network: network, status: .error, url: nil, clickTime: nil, httpStatus: status,
|
|
138
|
+
detail: error ?? preview(body))
|
|
139
|
+
}
|
|
140
|
+
if let link = object["applink_url"] as? String, !link.isEmpty {
|
|
141
|
+
return DdlAnswer(network: network, status: .link, url: link,
|
|
142
|
+
clickTime: object["click_time"].map { "\($0)" }, httpStatus: status, detail: nil)
|
|
143
|
+
}
|
|
144
|
+
return DdlAnswer(network: network, status: .none, url: nil, clickTime: nil, httpStatus: status, detail: preview(body))
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
enum TikTokDdl {
|
|
150
|
+
static let network = "tiktok"
|
|
151
|
+
/// TikTokBusinessSDK's default `apiDomain`.
|
|
152
|
+
static let defaultHost = "analytics.us.tiktok.com"
|
|
153
|
+
static let path = "/api/v1/app_sdk/ddl"
|
|
154
|
+
|
|
155
|
+
/// The SDK's `fallbackUserAgent`: app/version, model, OS, resolution.
|
|
156
|
+
static func userAgent(_ f: DdlDeviceFacts) -> String {
|
|
157
|
+
"\(f.appName)/\(f.appVersion) \(f.model) iOS/\(f.os) Resolution/\(f.screenWidth)*\(f.screenHeight)"
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/// TikTokBusinessSDK's `att_status` names.
|
|
161
|
+
static func attStatus(_ status: KerdlyAttStatus) -> String {
|
|
162
|
+
switch status {
|
|
163
|
+
case .authorized: return "AUTHORIZED"
|
|
164
|
+
case .denied: return "DENIED"
|
|
165
|
+
case .restricted: return "RESTRICTED"
|
|
166
|
+
case .notDetermined: return "NOT_DETERMINED"
|
|
167
|
+
case .notApplicable: return "NOT_APPLICABLE"
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// `POST https://<host>/api/v1/app_sdk/ddl`, unsigned JSON. `storeAppId` is the App Store id the
|
|
172
|
+
/// app passes TikTok as `appId`. The host is the same whatever the ATT status; the request
|
|
173
|
+
/// carries the status and, only when it is authorized, the IDFA (empty otherwise).
|
|
174
|
+
static func request(tiktokAppId: String, storeAppId: String?, facts: DdlDeviceFacts, att: KerdlyAttStatus,
|
|
175
|
+
now: Date, host: String = defaultHost) -> HTTPRequest? {
|
|
176
|
+
guard !tiktokAppId.isEmpty, let url = URL(string: "https://\(host)\(path)") else { return nil }
|
|
177
|
+
var app: [String: Any] = [
|
|
178
|
+
"name": facts.appName, "namespace": facts.bundleId, "version": facts.appVersion,
|
|
179
|
+
"build": facts.appBuild, "app_session_id": "", "last_app_session_id": "",
|
|
180
|
+
"last_app_session_start_time": "", "tiktok_app_id": tiktokAppId,
|
|
181
|
+
]
|
|
182
|
+
if let storeAppId, !storeAppId.isEmpty { app["id"] = storeAppId }
|
|
183
|
+
let ua = userAgent(facts)
|
|
184
|
+
let device: [String: Any] = [
|
|
185
|
+
"att_status": attStatus(att), "platform": "ios", "idfa": att == .authorized ? facts.idfa : "",
|
|
186
|
+
"idfv": facts.idfv ?? "",
|
|
187
|
+
"ip": "", "user_agent": ua, "locale": "\(facts.preferredLanguage)/\(facts.regionCode)",
|
|
188
|
+
"model": facts.model, "os_version": facts.os,
|
|
189
|
+
]
|
|
190
|
+
let body: [String: Any] = [
|
|
191
|
+
"context": ["app": app, "device": device, "user": [String: Any]()],
|
|
192
|
+
"ip": "", "tiktok_app_id": tiktokAppId, "user_agent": ua,
|
|
193
|
+
"timestamp": iso8601(now),
|
|
194
|
+
]
|
|
195
|
+
guard let data = try? JSONSerialization.data(withJSONObject: body, options: [.sortedKeys]) else { return nil }
|
|
196
|
+
return HTTPRequest(method: "POST", url: url, headers: ["Content-Type": "application/json"], body: data)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// `{"code": 0, "data": {"ddl": "<url>"}}`; any other code is an error.
|
|
200
|
+
static func parse(_ result: HTTPResult) -> DdlAnswer {
|
|
201
|
+
switch result {
|
|
202
|
+
case .failure(let reason):
|
|
203
|
+
return DdlAnswer(network: network, status: .error, url: nil, clickTime: nil, httpStatus: nil, detail: reason)
|
|
204
|
+
case .response(let status, _, let body):
|
|
205
|
+
let object = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
|
|
206
|
+
let code = (object?["code"] as? NSNumber)?.intValue
|
|
207
|
+
guard status == 200, code == 0 else {
|
|
208
|
+
let message = object?["message"].map { "\(code.map(String.init) ?? "?") \($0)" }
|
|
209
|
+
return DdlAnswer(network: network, status: .error, url: nil, clickTime: nil, httpStatus: status,
|
|
210
|
+
detail: message ?? preview(body))
|
|
211
|
+
}
|
|
212
|
+
if let link = (object?["data"] as? [String: Any])?["ddl"] as? String, !link.isEmpty {
|
|
213
|
+
return DdlAnswer(network: network, status: .link, url: link, clickTime: nil, httpStatus: status, detail: nil)
|
|
214
|
+
}
|
|
215
|
+
return DdlAnswer(network: network, status: .none, url: nil, clickTime: nil, httpStatus: status, detail: preview(body))
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private func json(_ value: Any) -> String? {
|
|
221
|
+
guard let data = try? JSONSerialization.data(withJSONObject: value, options: [.withoutEscapingSlashes]) else { return nil }
|
|
222
|
+
return String(data: data, encoding: .utf8)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private func formEncode(_ s: String) -> String {
|
|
226
|
+
var allowed = CharacterSet.alphanumerics
|
|
227
|
+
allowed.insert(charactersIn: "-._~")
|
|
228
|
+
return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private func preview(_ body: Data) -> String {
|
|
232
|
+
String(String(decoding: body.prefix(300), as: UTF8.self))
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private func iso8601(_ date: Date) -> String {
|
|
236
|
+
let f = ISO8601DateFormatter()
|
|
237
|
+
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
238
|
+
return f.string(from: date)
|
|
239
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What `environment: .auto` is decided from.
|
|
4
|
+
struct EnvironmentInputs: Equatable, Sendable {
|
|
5
|
+
var isSimulator: Bool
|
|
6
|
+
/// The SDK was compiled in a debug configuration (`DEBUG`); SPM and CocoaPods build it from
|
|
7
|
+
/// source with the app's configuration.
|
|
8
|
+
var isDebugBuild: Bool
|
|
9
|
+
/// The app is development-signed: its `embedded.mobileprovision` grants `get-task-allow`
|
|
10
|
+
/// (a build run from Xcode, debug or not).
|
|
11
|
+
var isDevelopmentSigned: Bool
|
|
12
|
+
/// `Bundle.main.appStoreReceiptURL?.lastPathComponent`.
|
|
13
|
+
var receiptName: String?
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
enum EnvironmentResolver {
|
|
17
|
+
/// `development` for a debug build or the simulator; else `sandbox` for a sandbox receipt
|
|
18
|
+
/// (TestFlight); else `production`. An explicit option wins.
|
|
19
|
+
static func resolve(option: KerdlyEnvironment, inputs: EnvironmentInputs) -> String {
|
|
20
|
+
if option != .auto { return option.rawValue }
|
|
21
|
+
if inputs.isSimulator || inputs.isDebugBuild || inputs.isDevelopmentSigned {
|
|
22
|
+
return KerdlyEnvironment.development.rawValue
|
|
23
|
+
}
|
|
24
|
+
if inputs.receiptName == "sandboxReceipt" {
|
|
25
|
+
return KerdlyEnvironment.sandbox.rawValue
|
|
26
|
+
}
|
|
27
|
+
return KerdlyEnvironment.production.rawValue
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Whether provisioning-profile bytes grant `get-task-allow`. The profile is a CMS envelope around
|
|
31
|
+
/// a plain-text plist, so the entitlement can be found without decoding the signature.
|
|
32
|
+
static func profileAllowsDebugging(_ profile: Data) -> Bool {
|
|
33
|
+
guard let text = String(data: profile, encoding: .isoLatin1),
|
|
34
|
+
let key = text.range(of: "<key>get-task-allow</key>")
|
|
35
|
+
else { return false }
|
|
36
|
+
let rest = text[key.upperBound...].drop(while: { $0.isWhitespace })
|
|
37
|
+
return rest.hasPrefix("<true/>")
|
|
38
|
+
}
|
|
39
|
+
}
|