@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,117 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// The public API's work, on any thread: validate here, then hop onto `queue` through `run`.
|
|
4
|
+
// `Kerdly` forwards to these on `KerdlyCore.shared`; tests call them on a core built with fakes.
|
|
5
|
+
extension KerdlyCore {
|
|
6
|
+
func apiSetUserId(_ userId: String?) {
|
|
7
|
+
let value = userId?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
8
|
+
let normalized = (value?.isEmpty ?? true) ? nil : value.map { String($0.prefix(Self.maxIdLength)) }
|
|
9
|
+
let at = now
|
|
10
|
+
run { [self] in setUserId(normalized, at: at) }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
func apiTrack(_ name: String, properties: [String: Any]) {
|
|
14
|
+
if ReservedEvent.isReserved(name) {
|
|
15
|
+
log.debug("track: '\(name)' is a reserved name; dropped")
|
|
16
|
+
return
|
|
17
|
+
}
|
|
18
|
+
guard EventValidator.isValidName(name) else {
|
|
19
|
+
log.debug("track: '\(name)' is not a valid event name; dropped")
|
|
20
|
+
return
|
|
21
|
+
}
|
|
22
|
+
// A standard event's typed props are checked here too.
|
|
23
|
+
let sanitized = StandardEvent.sanitize(name, properties)
|
|
24
|
+
for issue in sanitized.issues {
|
|
25
|
+
log.debug("track(\(name)): \(issue)")
|
|
26
|
+
}
|
|
27
|
+
let props = sanitized.props
|
|
28
|
+
let at = now
|
|
29
|
+
run { [self] in track(name, props: props, at: at) }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
func apiTrackRegistration(method: String?, properties: [String: Any]) {
|
|
33
|
+
apiTrackStandard(StandardEvent.registration, StandardEvent.arguments(method: method), properties)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
func apiTrackStartTrial(productId: String?, value: Double?, currency: String?, transactionId: String?,
|
|
37
|
+
properties: [String: Any]) {
|
|
38
|
+
apiTrackStandard(StandardEvent.startTrial, StandardEvent.arguments(
|
|
39
|
+
productId: productId, value: value, currency: currency, transactionId: transactionId), properties)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
func apiTrackSubscribe(productId: String?, value: Double?, currency: String?, transactionId: String?,
|
|
43
|
+
properties: [String: Any]) {
|
|
44
|
+
apiTrackStandard(StandardEvent.subscribe, StandardEvent.arguments(
|
|
45
|
+
productId: productId, value: value, currency: currency, transactionId: transactionId), properties)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
func apiTrackPurchase(productId: String?, value: Double?, currency: String?, quantity: Int?,
|
|
49
|
+
transactionId: String?, properties: [String: Any]) {
|
|
50
|
+
apiTrackStandard(StandardEvent.purchase, StandardEvent.arguments(
|
|
51
|
+
productId: productId, value: value, currency: currency, quantity: quantity,
|
|
52
|
+
transactionId: transactionId), properties)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// A typed method: its arguments win over `properties`; then the same checks as `track`.
|
|
56
|
+
private func apiTrackStandard(_ name: String, _ arguments: [String: Any], _ properties: [String: Any]) {
|
|
57
|
+
let merged = StandardEvent.merge(arguments, properties)
|
|
58
|
+
for key in merged.ignored {
|
|
59
|
+
log.debug("track(\(name)): prop '\(key)' ignored: an argument sets it")
|
|
60
|
+
}
|
|
61
|
+
let sanitized = StandardEvent.sanitize(name, merged.props)
|
|
62
|
+
for issue in sanitized.issues {
|
|
63
|
+
log.debug("track(\(name)): \(issue)")
|
|
64
|
+
}
|
|
65
|
+
let props = sanitized.props
|
|
66
|
+
let at = now
|
|
67
|
+
run { [self] in track(name, props: props, at: at) }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
func apiSetConsent(analytics: Bool?, ads: Bool?) {
|
|
71
|
+
let at = now
|
|
72
|
+
run { [self] in setConsent(analytics: analytics, ads: ads, at: at) }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
func apiHandleUrl(_ url: URL, source: String? = nil) -> KerdlyDeepLink? {
|
|
76
|
+
guard let parsed = DeepLinkParser.parse(url) else { return nil }
|
|
77
|
+
let at = now
|
|
78
|
+
run { [self] in handleDeepLink(parsed, source: source, at: at) }
|
|
79
|
+
return KerdlyDeepLink(url: url, cpp: parsed.cpp, ppid: parsed.ppid, clickId: parsed.clickId,
|
|
80
|
+
visitId: parsed.visitId, campaignIds: parsed.campaignIds)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
func apiSetAppAccountToken(_ token: UUID?) {
|
|
84
|
+
let value = token?.uuidString.lowercased()
|
|
85
|
+
let at = now
|
|
86
|
+
run { [self] in setAppAccountToken(value, at: at) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
func apiSetPartnerIds(_ ids: [String: String]) {
|
|
90
|
+
var cleaned: [String: String] = [:]
|
|
91
|
+
for (key, value) in ids.sorted(by: { $0.key < $1.key }).prefix(50) {
|
|
92
|
+
let k = key.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
93
|
+
guard !k.isEmpty else { continue }
|
|
94
|
+
cleaned[String(k.prefix(64))] = String(value.prefix(1_024))
|
|
95
|
+
}
|
|
96
|
+
let clean = cleaned
|
|
97
|
+
let at = now
|
|
98
|
+
run { [self] in setPartnerIds(clean, at: at) }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
func apiNotifyPurchase(_ purchase: KerdlyPurchase?) {
|
|
102
|
+
run { [self] in notifyPurchase(purchase) }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
func apiRecordNetworkSend(_ send: KerdlyNetworkSend) {
|
|
106
|
+
let at = now
|
|
107
|
+
run { [self] in recordNetworkSend(send, at: at) }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
var apiAttribution: KerdlyAttribution? {
|
|
111
|
+
attributionBox.get().map { KerdlyAttribution(json: $0) }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
func apiFlush() {
|
|
115
|
+
run { [self] in flushNow(explicit: true) }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// Background collectors, the SKAN glue and app lifecycle. Everything here
|
|
4
|
+
// runs on `queue`.
|
|
5
|
+
extension KerdlyCore {
|
|
6
|
+
static let maxAsaAttempts = 3
|
|
7
|
+
/// Failed token requests per round (a launch or a foreground) before the round gives up.
|
|
8
|
+
static let maxAsaFailures = 3
|
|
9
|
+
static let asaRetryDelay: TimeInterval = 15
|
|
10
|
+
/// How long after the first launch the SDK keeps asking for the token.
|
|
11
|
+
static let asaWindow: TimeInterval = 48 * 3_600
|
|
12
|
+
static let notifyLookupTimeout: TimeInterval = 5
|
|
13
|
+
|
|
14
|
+
// MARK: - Launch pipeline
|
|
15
|
+
|
|
16
|
+
/// The config for this app version first: when none is cached (a fresh install, or the first
|
|
17
|
+
/// launch after an update) everything waits for its fetch, the launch batch included, and the
|
|
18
|
+
/// fetch is retried until it arrives (`afterConfigFetch`). Then the public IPv6, the SKAN
|
|
19
|
+
/// baseline, the AdServices token and the other collectors; nothing at all when Kerdly is off for
|
|
20
|
+
/// this version.
|
|
21
|
+
func runLaunchPipeline() {
|
|
22
|
+
guard !launchPipelineStarted else { return }
|
|
23
|
+
launchPipelineStarted = true
|
|
24
|
+
guard configReady else { return fetchConfig() }
|
|
25
|
+
if configCache?.isStale(now: now) == true { fetchConfig() }
|
|
26
|
+
if config.off { return switchOff() }
|
|
27
|
+
launchConfigReady()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
func launchConfigReady() {
|
|
31
|
+
guard !launchConfigResolved, configReady, !config.off else { return }
|
|
32
|
+
launchConfigResolved = true
|
|
33
|
+
// Before the SKAN baseline, and after the replayed calls, so a `setConsent` made before
|
|
34
|
+
// `configure` applies.
|
|
35
|
+
collectPublicIp()
|
|
36
|
+
skanReady = true
|
|
37
|
+
// The baseline goes first: writes it BEFORE the AdServices token.
|
|
38
|
+
skanTrigger(.launch)
|
|
39
|
+
let buffered = pendingSkanTriggers
|
|
40
|
+
pendingSkanTriggers = []
|
|
41
|
+
buffered.forEach { skanTrigger($0) }
|
|
42
|
+
skan.whenIdle { [self] in startLaunchCollectors() }
|
|
43
|
+
scheduler.schedule(after: SkanCoordinator.writeTimeout * 2 + 1) { [self] in startLaunchCollectors() }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
func startLaunchCollectors() {
|
|
47
|
+
guard !launchCollectorsStarted else { return }
|
|
48
|
+
launchCollectorsStarted = true
|
|
49
|
+
retryAsaToken(launch: true)
|
|
50
|
+
collectAppTransaction()
|
|
51
|
+
collectAdvertisingId()
|
|
52
|
+
askDeferredLinks()
|
|
53
|
+
startPurchaseObservation()
|
|
54
|
+
scheduleAttributionPolls()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// MARK: - AdServices token
|
|
58
|
+
|
|
59
|
+
/// A round of token tries while a token is still wanted: each launch, and each foreground once
|
|
60
|
+
/// the last round gave up. A launch is a fresh process, so its round starts from zero.
|
|
61
|
+
func retryAsaToken(launch: Bool) {
|
|
62
|
+
guard state.asaDue else { return }
|
|
63
|
+
if launch || state.asaFailures >= Self.maxAsaFailures {
|
|
64
|
+
state.asaFailures = 0
|
|
65
|
+
}
|
|
66
|
+
requestAsaToken()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// From the `$install` launch until a token is sent, within `asaWindow` of the first launch,
|
|
70
|
+
/// and when a response's `needs` asks; at most 3 token signals per install.
|
|
71
|
+
/// `AAAttribution.attributionToken()` blocks, so it runs on the work queue.
|
|
72
|
+
func requestAsaToken() {
|
|
73
|
+
guard launchCollectorsStarted, state.asaDue, !asaInFlight else { return }
|
|
74
|
+
guard config.collectAsaToken else { return }
|
|
75
|
+
guard state.asaAttempts < Self.maxAsaAttempts, !asaWindowClosed else {
|
|
76
|
+
state.asaDue = false
|
|
77
|
+
saveState()
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
asaInFlight = true
|
|
81
|
+
let provider = deps.adServices
|
|
82
|
+
deps.workQueue.async { [self] in
|
|
83
|
+
let result: Result<String, KerdlyAdapterError>
|
|
84
|
+
do {
|
|
85
|
+
result = .success(try provider.attributionToken())
|
|
86
|
+
} catch {
|
|
87
|
+
result = .failure(KerdlyAdapterError(String(describing: error)))
|
|
88
|
+
}
|
|
89
|
+
queue.async { self.asaTokenFinished(result) }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
func asaTokenFinished(_ result: Result<String, KerdlyAdapterError>) {
|
|
94
|
+
asaInFlight = false
|
|
95
|
+
switch result {
|
|
96
|
+
case .success(let token) where !token.isEmpty:
|
|
97
|
+
let attempt = state.asaAttempts + 1
|
|
98
|
+
guard enqueue(ReservedEvent.signal, [
|
|
99
|
+
"kind": .string("asa_token"),
|
|
100
|
+
"token": .string(token),
|
|
101
|
+
"attempt": .int(Int64(attempt)),
|
|
102
|
+
]) != nil else { return }
|
|
103
|
+
state.asaAttempts = attempt
|
|
104
|
+
state.asaDue = false
|
|
105
|
+
saveState()
|
|
106
|
+
log.info("AdServices token \(Redact.short(token)) sent (attempt \(attempt))")
|
|
107
|
+
case .success, .failure:
|
|
108
|
+
state.asaFailures += 1
|
|
109
|
+
if case .failure(let error) = result {
|
|
110
|
+
log.info("AdServices token unavailable: \(error)")
|
|
111
|
+
}
|
|
112
|
+
if state.asaFailures >= Self.maxAsaFailures {
|
|
113
|
+
log.info("AdServices token: \(state.asaFailures) failures; trying again at the next launch or foreground")
|
|
114
|
+
} else {
|
|
115
|
+
scheduler.schedule(after: Self.asaRetryDelay) { [self] in requestAsaToken() }
|
|
116
|
+
}
|
|
117
|
+
saveState()
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// The install's attribution is settled (`asaWindow` after its first launch).
|
|
122
|
+
var asaWindowClosed: Bool {
|
|
123
|
+
guard let first = state.firstLaunchAt else { return false }
|
|
124
|
+
return Clocks.ms(now) - first > Int64(Self.asaWindow * 1_000)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// MARK: - AppTransaction
|
|
128
|
+
|
|
129
|
+
/// iOS 16+: `AppTransaction.shared`, retried on later launches until one succeeds.
|
|
130
|
+
func collectAppTransaction() {
|
|
131
|
+
guard !state.appTransactionSent, !appTransactionInFlight, config.collectAppTransaction else { return }
|
|
132
|
+
appTransactionInFlight = true
|
|
133
|
+
deps.storeKit.appTransaction { [self] result in
|
|
134
|
+
queue.async { self.appTransactionFinished(result) }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
func appTransactionFinished(_ result: Result<AppTransactionInfo, KerdlyAdapterError>) {
|
|
139
|
+
appTransactionInFlight = false
|
|
140
|
+
switch result {
|
|
141
|
+
case .success(let info):
|
|
142
|
+
guard enqueue(ReservedEvent.signal, [
|
|
143
|
+
"kind": .string("app_transaction"),
|
|
144
|
+
"jws": .string(info.jws),
|
|
145
|
+
"app_transaction_id": .string(info.appTransactionId),
|
|
146
|
+
"original_purchase_date": .int(Clocks.ms(info.originalPurchaseDate)),
|
|
147
|
+
"original_app_version": .string(info.originalAppVersion),
|
|
148
|
+
"environment": .string(info.environment),
|
|
149
|
+
"device_verification_nonce": .string(info.deviceVerificationNonce),
|
|
150
|
+
"device_verification": .string(info.deviceVerification),
|
|
151
|
+
]) != nil else { return }
|
|
152
|
+
state.appTransactionSent = true
|
|
153
|
+
saveState()
|
|
154
|
+
log.info("AppTransaction sent (\(info.environment))")
|
|
155
|
+
case .failure(let error):
|
|
156
|
+
log.info("AppTransaction unavailable (retried next launch): \(error)")
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// MARK: - IDFA
|
|
161
|
+
|
|
162
|
+
/// Only with ATT = authorized, `ads` consent, `collectAdvertisingId` and the config's
|
|
163
|
+
/// `collect.advertising_id`; signalled when it changes.
|
|
164
|
+
func collectAdvertisingId() {
|
|
165
|
+
guard advertisingIdAllowed, !advertisingIdInFlight, launchCollectorsStarted else { return }
|
|
166
|
+
advertisingIdInFlight = true
|
|
167
|
+
let provider = deps.advertisingId
|
|
168
|
+
deps.workQueue.async { [self] in
|
|
169
|
+
let idfa = provider.advertisingId()
|
|
170
|
+
queue.async { self.advertisingIdFinished(idfa) }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
var advertisingIdAllowed: Bool {
|
|
175
|
+
(options?.collectAdvertisingId ?? false) && config.collectAdvertisingId && state.consentAds
|
|
176
|
+
&& deps.tracking.status() == .authorized
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
func advertisingIdFinished(_ idfa: String?) {
|
|
180
|
+
advertisingIdInFlight = false
|
|
181
|
+
guard advertisingIdAllowed, let idfa, !idfa.isEmpty,
|
|
182
|
+
idfa.contains(where: { $0 != "0" && $0 != "-" })
|
|
183
|
+
else { return }
|
|
184
|
+
let hash = Hashing.sha256(idfa.uppercased())
|
|
185
|
+
guard hash != state.idfaHash else { return }
|
|
186
|
+
guard enqueue(ReservedEvent.signal, ["kind": .string("advertising_ids"), "idfa": .string(idfa)]) != nil
|
|
187
|
+
else { return }
|
|
188
|
+
state.idfaHash = hash
|
|
189
|
+
saveState()
|
|
190
|
+
log.info("IDFA \(Redact.short(idfa)) sent")
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// MARK: - Public IPv6
|
|
194
|
+
|
|
195
|
+
/// Once per install, on the launch that enqueued `$install`, started at once
|
|
196
|
+
/// rather than behind the SKAN baseline and the launch collectors. A failure is never retried.
|
|
197
|
+
func collectPublicIp() {
|
|
198
|
+
guard launchEnqueuedInstall, publicIpAllowed else { return }
|
|
199
|
+
let provider = deps.publicIp
|
|
200
|
+
let url = config.ipv6EchoUrl
|
|
201
|
+
deps.workQueue.async { [self] in
|
|
202
|
+
provider.lookup(url) { [self] answer in
|
|
203
|
+
queue.async { self.publicIpFinished(answer) }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
var publicIpAllowed: Bool {
|
|
209
|
+
config.collectPublicIp && state.consentAds
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
func publicIpFinished(_ answer: String?) {
|
|
213
|
+
guard publicIpAllowed else { return }
|
|
214
|
+
guard let answer else {
|
|
215
|
+
log.info("public IPv6 unavailable (not retried)")
|
|
216
|
+
return
|
|
217
|
+
}
|
|
218
|
+
guard let ipv6 = PublicIPv6.globalUnicast(answer) else {
|
|
219
|
+
log.info("public IPv6: the echo's answer is not a global IPv6 address; dropped")
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
guard enqueue(ReservedEvent.signal, ["kind": .string("public_ip"), "ipv6": .string(ipv6)]) != nil
|
|
223
|
+
else { return }
|
|
224
|
+
log.info("public IPv6 \(Redact.short(ipv6)) sent")
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// MARK: - Purchases
|
|
228
|
+
|
|
229
|
+
/// `$purchase_link` (config `collect.purchases`) and the SKAN purchase triggers both need the
|
|
230
|
+
/// StoreKit observation.
|
|
231
|
+
var purchaseObservationWanted: Bool {
|
|
232
|
+
config.collectPurchases || skanEnabled
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
func startPurchaseObservation() {
|
|
236
|
+
guard purchaseObservationWanted else { return }
|
|
237
|
+
if !updatesObserved {
|
|
238
|
+
updatesObserved = true
|
|
239
|
+
deps.storeKit.observeUpdates { [self] info in
|
|
240
|
+
queue.async { self.handlePurchase(info, notified: nil, source: .updates) }
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
sweepEntitlements()
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// `Transaction.currentEntitlements`, on launch, every foreground and `notifyPurchase()`.
|
|
247
|
+
func sweepEntitlements() {
|
|
248
|
+
guard launchCollectorsStarted, purchaseObservationWanted, !sweepInFlight else { return }
|
|
249
|
+
sweepInFlight = true
|
|
250
|
+
deps.storeKit.currentEntitlements { [self] infos in
|
|
251
|
+
queue.async {
|
|
252
|
+
self.sweepInFlight = false
|
|
253
|
+
for info in infos {
|
|
254
|
+
self.handlePurchase(info, notified: nil, source: .entitlements)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
func notifyPurchase(_ purchase: KerdlyPurchase?) {
|
|
261
|
+
guard purchaseObservationWanted else { return }
|
|
262
|
+
guard let purchase, NotifiedPurchase(purchase).hasIds else {
|
|
263
|
+
if launchCollectorsStarted { sweepEntitlements() }
|
|
264
|
+
return
|
|
265
|
+
}
|
|
266
|
+
let notified = NotifiedPurchase(purchase)
|
|
267
|
+
notifyLookupCounter += 1
|
|
268
|
+
let token = notifyLookupCounter
|
|
269
|
+
notifyLookups[token] = notified
|
|
270
|
+
deps.storeKit.findTransaction(transactionId: notified.transactionId,
|
|
271
|
+
originalTransactionId: notified.originalTransactionId,
|
|
272
|
+
productId: notified.productId) { [self] info in
|
|
273
|
+
queue.async { self.notifyLookupFinished(token, info: info) }
|
|
274
|
+
}
|
|
275
|
+
scheduler.schedule(after: Self.notifyLookupTimeout) { [self] in
|
|
276
|
+
notifyLookupFinished(token, info: nil)
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
func notifyLookupFinished(_ token: Int, info: PurchaseInfo?) {
|
|
281
|
+
guard let notified = notifyLookups.removeValue(forKey: token) else { return }
|
|
282
|
+
handlePurchase(info, notified: notified, source: .notify)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// One `$purchase_link` per original transaction id; then the SKAN purchase / sweep trigger.
|
|
286
|
+
func handlePurchase(_ info: PurchaseInfo?, notified: NotifiedPurchase?, source: PurchaseSource) {
|
|
287
|
+
if config.collectPurchases {
|
|
288
|
+
let keys = PurchaseLinks.dedupeKeys(info: info, notified: notified)
|
|
289
|
+
if !keys.isEmpty {
|
|
290
|
+
if PurchaseLinks.isReported(keys, in: state.reportedPurchaseIds) {
|
|
291
|
+
if keys.contains(where: { !state.reportedPurchaseIds.contains($0) }) {
|
|
292
|
+
state.markReported(keys)
|
|
293
|
+
saveState()
|
|
294
|
+
}
|
|
295
|
+
} else if enqueue(ReservedEvent.purchaseLink,
|
|
296
|
+
PurchaseLinks.props(info: info, notified: notified, source: source)) != nil {
|
|
297
|
+
state.markReported(keys)
|
|
298
|
+
saveState()
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if let info {
|
|
303
|
+
skanTrigger(source == .entitlements ? .sweep(info.facts) : .purchase(info.facts))
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// MARK: - SKAN
|
|
308
|
+
|
|
309
|
+
/// Hands a trigger to the writer when SKAN writing is on. Triggers that arrive
|
|
310
|
+
/// before the launch's config is resolved wait for it.
|
|
311
|
+
func skanTrigger(_ trigger: SkanTrigger) {
|
|
312
|
+
guard options?.skanWriter == true else { return }
|
|
313
|
+
guard skanReady else {
|
|
314
|
+
if pendingSkanTriggers.count < 50 { pendingSkanTriggers.append(trigger) }
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
guard skanEnabled, let schema = config.skan, let first = state.firstLaunchAt else { return }
|
|
318
|
+
let timeline = SkanTimeline(firstLaunchAt: Clocks.date(ms: first),
|
|
319
|
+
installedAt: state.installedAt.map { Clocks.date(ms: $0) })
|
|
320
|
+
skan.submit(.init(trigger: trigger, schema: schema, timeline: timeline))
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// MARK: - ATT
|
|
324
|
+
|
|
325
|
+
/// Emits `$consent` when the ATT status differs from the last one seen (the first observation
|
|
326
|
+
/// is recorded silently).
|
|
327
|
+
func checkAttStatus(persist: Bool = true) {
|
|
328
|
+
let status = deps.tracking.status().rawValue
|
|
329
|
+
guard let last = state.lastAttStatus else {
|
|
330
|
+
state.lastAttStatus = status
|
|
331
|
+
if persist { saveState() }
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
guard status != last else { return }
|
|
335
|
+
state.lastAttStatus = status
|
|
336
|
+
if persist { saveState() }
|
|
337
|
+
enqueueConsent()
|
|
338
|
+
if status == KerdlyAttStatus.authorized.rawValue {
|
|
339
|
+
collectAdvertisingId()
|
|
340
|
+
}
|
|
341
|
+
askDeferredLinks()
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// MARK: - Lifecycle
|
|
345
|
+
|
|
346
|
+
func observeLifecycleOnce() {
|
|
347
|
+
guard !lifecycleObserved else { return }
|
|
348
|
+
lifecycleObserved = true
|
|
349
|
+
let device = deps.device
|
|
350
|
+
let lifecycle = deps.lifecycle
|
|
351
|
+
lifecycle.observe { [self] event in
|
|
352
|
+
let wantsSnapshot = Thread.isMainThread && (event == .didBecomeActive || event == .willEnterForeground)
|
|
353
|
+
let fresh: DeviceSnapshot? = wantsSnapshot ? MainActor.assumeIsolated { device.snapshot() } : nil
|
|
354
|
+
let backgroundTask = event == .didEnterBackground ? lifecycle.beginBackgroundTask() : nil
|
|
355
|
+
queue.async { self.handleLifecycle(event, snapshot: fresh, backgroundTask: backgroundTask) }
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
func handleLifecycle(_ event: LifecycleEvent, snapshot fresh: DeviceSnapshot?, backgroundTask: Int?) {
|
|
360
|
+
if let fresh {
|
|
361
|
+
snapshot = fresh
|
|
362
|
+
}
|
|
363
|
+
let at = now
|
|
364
|
+
switch event {
|
|
365
|
+
case .protectedDataAvailable:
|
|
366
|
+
if waitingForProtectedData, options != nil {
|
|
367
|
+
resolveInstall(at: at)
|
|
368
|
+
}
|
|
369
|
+
case .willEnterForeground:
|
|
370
|
+
guard started else { return }
|
|
371
|
+
isForeground = true
|
|
372
|
+
facts = deps.device.facts()
|
|
373
|
+
if let background = lastBackgroundAt, at.timeIntervalSince(background) >= Self.foregroundOpenThreshold {
|
|
374
|
+
enqueue(ReservedEvent.open, ["reason": .string("foreground")], at: at)
|
|
375
|
+
}
|
|
376
|
+
lastBackgroundAt = nil
|
|
377
|
+
retryConfigNowIfMissing()
|
|
378
|
+
sweepEntitlements()
|
|
379
|
+
retryAsaToken(launch: false)
|
|
380
|
+
askDeferredLinks()
|
|
381
|
+
startForegroundTimer()
|
|
382
|
+
scheduleFlush()
|
|
383
|
+
case .didBecomeActive:
|
|
384
|
+
guard started else { return }
|
|
385
|
+
isForeground = true
|
|
386
|
+
if snapshot != nil { releaseLaunchFlush() }
|
|
387
|
+
checkAttStatus()
|
|
388
|
+
startForegroundTimer()
|
|
389
|
+
case .didEnterBackground:
|
|
390
|
+
if let previous = backgroundTaskToken {
|
|
391
|
+
deps.lifecycle.endBackgroundTask(previous)
|
|
392
|
+
}
|
|
393
|
+
backgroundTaskToken = backgroundTask
|
|
394
|
+
guard started else { return endBackgroundTaskIfIdle() }
|
|
395
|
+
isForeground = false
|
|
396
|
+
lastBackgroundAt = at
|
|
397
|
+
deepLinkSources.didEnterBackground()
|
|
398
|
+
stopForegroundTimer()
|
|
399
|
+
flushNow(explicit: false)
|
|
400
|
+
endBackgroundTaskIfIdle()
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/// The app's ATT request settled (through `Kerdly.requestTrackingAuthorization`).
|
|
405
|
+
func trackingDecided() {
|
|
406
|
+
guard started else { return }
|
|
407
|
+
checkAttStatus()
|
|
408
|
+
scheduleFlush()
|
|
409
|
+
}
|
|
410
|
+
}
|