Files
public-sdks-score/Sources/ScoreTracker/ScoreClient.swift
2026-10-07 20:38:39 -04:00

215 lines
9.1 KiB
Swift

import Foundation
import ScoreTrackerKit
/// Idiomatic Swift facade over the Score Tracker KMP framework (#177). Wraps the
/// generated `ScoreTrackerKit` Obj-C API with Swift types, sensible defaults, and
/// `async`/`await`. Mirrors the web tracker's surface. The durable offline queue
/// and persistent `anonymousId` are handled natively (NSUserDefaults) — see #176.
public final class ScoreClient {
let tracker: ScoreTracker
private var autoFlushTask: Task<Void, Never>?
/// Set while `bindToAppLifecycle()` is in effect (AppLifecycle.swift, #484).
var appBindings: AppBindings?
/// - Parameters:
/// - endpoint: middleware base URL; events POST to `<endpoint>/api/tracking/website`.
/// - initialConsent: defaults to "none" — nothing fires until `setConsent(...)`.
/// - pii: field-level PII handling (#482), scrubbed before events are queued on the device.
/// - tokenRefreshTimeoutSeconds: how long a flush waits for the token provider (#483).
///
/// The envelope's `sdk.name` / `sdk.version` are baked into the framework
/// (#486); there is nothing to pass.
public init(
publishableKey: String,
siteId: String,
endpoint: String,
appVersion: String? = nil,
os: String? = nil,
device: String? = nil,
locale: String? = nil,
initialConsent: ConsentState? = nil,
privacy: PrivacyOptions? = nil,
pii: PiiOptions? = nil,
tokenRefreshTimeoutSeconds: Double = 5,
identifyReplayBufferSize: Int = 100
) {
let config = TrackerConfig(
publishableKey: publishableKey,
siteId: siteId,
endpoint: endpoint,
device: DeviceDescriptor(os: os, device: device, appVersion: appVersion, locale: locale),
privacy: privacy
)
tracker = IosPlatformKt.doNewScoreTracker(
config: config,
initialConsent: initialConsent,
pii: pii,
tokenRefreshTimeoutMs: Int64(tokenRefreshTimeoutSeconds * 1000),
identifyReplayBufferSize: Int32(identifyReplayBufferSize)
)
}
/// The pre-#486 signature. `sdkVersion` is ignored: the SDK reports the
/// version it was built as.
@available(*, deprecated, message: "The SDK reports its own version now (#486); sdkVersion is ignored. Drop the argument.")
public convenience init(
publishableKey: String,
siteId: String,
endpoint: String,
sdkVersion: String,
appVersion: String? = nil,
os: String? = nil,
device: String? = nil,
locale: String? = nil,
initialConsent: ConsentState = ConsentState.companion.NONE,
pii: PiiOptions? = nil
) {
self.init(
publishableKey: publishableKey, siteId: siteId, endpoint: endpoint,
appVersion: appVersion, os: os, device: device, locale: locale,
initialConsent: initialConsent, pii: pii
)
}
/// What this build reports as `sdk.name` / `sdk.version` — for support and logs.
public static var sdkName: String { SdkInfo.companion.CURRENT.name }
public static var sdkVersion: String { SdkInfo.companion.CURRENT.version }
// MARK: - Consent (wire to your CMP / OneTrust)
public func setConsent(analytics: Bool, personalization: Bool, advertising: Bool) {
tracker.setConsent(state: ConsentState(analytics: analytics, personalization: personalization, advertising: advertising))
}
public func grantAllConsent() { tracker.setConsent(state: ConsentState.companion.ALL) }
public func revokeConsent() { tracker.setConsent(state: ConsentState.companion.NONE) }
// MARK: - Identity / Auth0
/// Bind events to the fan (#488). Sends an `identify` event carrying
/// `traits` (consent-gated and PII-scrubbed like any props). With
/// `replayAnonymousEvents`, events already sent before sign-in are re-sent
/// with the fan attached, marked `_backfill`, so a vote cast while signed
/// out earns its karma. Events still queued need no replay: they go out
/// with the user on the next flush.
public func identify(
userId: String,
token: String? = nil,
traits: [String: Any] = [:],
replayAnonymousEvents: Bool = false
) {
tracker.identify(userId: userId, token: token, traits: traits, replayAnonymousEvents: replayAnonymousEvents)
}
public func setToken(_ token: String?) { tracker.setToken(token: token) }
/// Supply the fan's access token on demand — wire to Auth0's
/// `credentialsManager.credentials()` (#483). `async`, so a silent refresh
/// needs no blocking; a plain synchronous closure works too. Consulted
/// before each flush, single-flight. If it throws, returns nil or takes
/// longer than the tracker's timeout (5 s), the flush goes ahead with the
/// last known token — anonymous if there is none.
public func setTokenProvider(_ provider: @escaping () async throws -> String?) {
tracker.setCallbackTokenProvider { complete in
Task { complete(try? await provider()) } // a throw counts as "no token"
}
}
/// Stop consulting a provider; the last token set stays until replaced.
public func clearTokenProvider() {
tracker.setCallbackTokenProvider(provider: nil)
}
public var anonymousId: String { tracker.anonymousId }
public var pending: Int { Int(tracker.pending()) }
/// The tracker's state for support (#490): consent, queue depth and oldest
/// event, identity (the token only as `hasToken`), the last flush, and the
/// link and replay state. Attach `inspectJson()` to any bug report.
public func inspect() -> InspectSnapshot { tracker.inspect() }
/// `inspect()` as JSON, ready to paste into a bug report.
public func inspectJson() -> String { tracker.inspectJson() }
// MARK: - Tracking
/// Track a typed loyalty event — the preferred form (#485). `Events` is
/// generated from the same schemas as the web and Android trackers, so the
/// name and its consent contract (`requires`) are identical on every
/// platform. Returns false if dropped by the consent gate.
///
/// score.track(Events.shared.PollVote, props: ["pollId": "motm-r12", "choice": "player_7"])
@discardableResult
public func track(_ event: EventDefinition, props: [String: Any] = [:], delivery: DeliveryMode = .bestEffort) -> Bool {
tracker.track(event: event, props: props, delivery: delivery)
}
/// Track an app event by name, for events not in `Events`. `requires` gates
/// it on consent categories — it is dropped unless every one is granted.
/// Returns false if dropped by the consent gate.
@discardableResult
public func track(
_ name: String,
props: [String: Any] = [:],
requires: [ConsentCategory] = [],
delivery: DeliveryMode = .bestEffort
) -> Bool {
tracker.track(name: name, props: props, type: .track, requires: requires, delivery: delivery)
}
/// Track an event gated on advertising consent (dropped until granted).
/// Shorthand for `track(name, props:, requires: [.advertising])`.
@discardableResult
public func trackAdvertising(_ name: String, props: [String: Any] = [:]) -> Bool {
track(name, props: props, requires: [ConsentCategory.advertising])
}
/// Record an app-screen view.
@discardableResult
public func screen(_ name: String, props: [String: Any] = [:]) -> Bool {
tracker.screen(name: name, props: props)
}
// MARK: - Flush
/// Send the queued batch. Returns true on a 2xx ack.
@discardableResult
public func flush() async throws -> Bool {
try await tracker.flush().boolValue
}
/// Call when the app returns to the foreground.
public func onForeground() async throws { _ = try await tracker.onForeground() }
/// Call when network connectivity is regained.
public func onNetworkAvailable() async throws { _ = try await tracker.onNetworkAvailable() }
/// Best-effort flush as the app goes to the background (#484), bounded by
/// `budgetSeconds` so it cannot hold up suspension. Returns false if it ran
/// out of time; unsent events stay queued. `bindToAppLifecycle()` calls this
/// for you.
@discardableResult
public func onBackground(budgetSeconds: Double = 5) async throws -> Bool {
try await tracker.onBackground(budgetMs: Int64(budgetSeconds * 1000)).boolValue
}
public func shutdown() async throws {
stopAutoFlush()
await MainActor.run { unbindAppLifecycleFromAnyContext() }
try await tracker.shutdown()
}
// MARK: - Auto-flush (Swift-native; avoids passing a Kotlin CoroutineScope)
public func startAutoFlush(everySeconds: Double = 30) {
stopAutoFlush()
autoFlushTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: UInt64(everySeconds * 1_000_000_000))
_ = try? await self?.flush()
}
}
}
public func stopAutoFlush() {
autoFlushTask?.cancel()
autoFlushTask = nil
}
}