// CrispStats iOS SDK 1.1.0 // // Add this file to your app target. It needs only Foundation and UIKit. // Download: https://crispstats.com/sdk/ios/CrispStats.swift import Foundation #if canImport(UIKit) import UIKit #endif /// App analytics for CrispStats. Screen views are pageviews on the same site /// as the website. A random install id is kept on the device and hashed by /// the collector before it is stored. No advertising id is read. /// /// Create one client and keep it for the life of the app. Every method can be /// called from any thread: it returns at once and the work runs on a private /// serial queue. Nothing throws. A client created with a wrong site key, app /// id or version does nothing and says why once in a debug build. public final class CrispStats: @unchecked Sendable { // Thread safety: every mutable property below is read and written only on // `work`, a serial queue. The only exception is `device`, written once // while `work` is suspended (see `init`). Constants are set in `init`. public static let version = "1.1.0" public enum Device: String, Sendable { case phone case tablet } /// The SDK the events come from. A wrapper (React Native, Flutter) that /// embeds this file passes its own name. The collector accepts only these. public enum SDK: String, Sendable { case ios case android case reactNative = "react-native" case flutter } // MARK: Limits shared with the other SDKs static let defaultAPI = "https://in.crispstats.com" static let queueLimit = 100 /// The collector starts a new session after 30 idle minutes. static let sessionGap: TimeInterval = 1800 static let requestTimeout: TimeInterval = 10 static let maxBackoff: TimeInterval = 60 static let maxCampaignPairs = 10 static let maxURLLength = 2048 // MARK: Injection points (internal, used by the tests) enum SendResult: Sendable, Equatable { case ok case retry case drop } /// Sends one JSON body and reports the result exactly once. typealias Transport = @Sendable (_ body: Data, _ done: @escaping @Sendable (SendResult) -> Void) -> Void typealias Clock = @Sendable () -> Date /// Runs the block once after the delay, on any queue. typealias Scheduler = @Sendable (_ delay: TimeInterval, _ block: @escaping @Sendable () -> Void) -> Void struct Config: Sendable { let site: String let appId: String let host: String let appVersion: String let appBuild: String? let osVersion: String let sdk: SDK } private struct Pending { let seq: Int let body: [String: Any] } private static let installKey = "cs.install" private static let queueKey = "cs.queue" private static let optOutKey = "cs.optout" let config: Config? private let work = DispatchQueue(label: "com.crispstats.sdk") private let defaults: UserDefaults private let transport: Transport private let clock: Clock private let scheduler: Scheduler private var device: Device = .phone private var installId: String? private var queue: [Pending] = [] private var nextSeq = 0 private var optedOut = false private var screenName: String? private var screenURL: String? private var shownAt: Date? private var backgroundAt: Date? private var accumulated = 0 private var inFlight: Int? private var failures = 0 private var timerToken = 0 private var idleWaiters: [@Sendable () -> Void] = [] private var observers: [NSObjectProtocol] = [] /// - Parameters: /// - site: The site's public key, `cs_pk_…`. /// - appId: The bundle id, for example `com.acme.app`. /// - appVersion: The marketing version, for example `1.4.0`. /// - appBuild: The build number. Optional. /// - osVersion: Leave it out: the system version is read for you. /// - device: Leave it out: an iPad counts as a tablet, everything else as a phone. /// - sdk: Leave it out unless a wrapper SDK embeds this file. /// - api: The collector origin. Leave it out. /// - defaults: Where the install id, the opt-out flag and the offline queue are kept. public convenience init( site: String, appId: String, appVersion: String, appBuild: String? = nil, osVersion: String? = nil, device: Device? = nil, sdk: SDK = .ios, api: String = "https://in.crispstats.com", defaults: UserDefaults = .standard ) { let endpoint = Self.endpoint(api) let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = Self.requestTimeout configuration.timeoutIntervalForResource = Self.requestTimeout configuration.httpCookieStorage = nil configuration.httpShouldSetCookies = false configuration.urlCache = nil let session = URLSession(configuration: configuration) self.init( site: site, appId: appId, appVersion: appVersion, appBuild: appBuild, osVersion: osVersion, device: device, sdk: sdk, defaults: defaults, transport: Self.urlSessionTransport(endpoint: endpoint, session: session), clock: { Date() }, scheduler: { delay, block in DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + delay, execute: block) }, observeApp: true ) } init( site: String, appId: String, appVersion: String, appBuild: String?, osVersion: String?, device: Device?, sdk: SDK, defaults: UserDefaults, transport: @escaping Transport, clock: @escaping Clock, scheduler: @escaping Scheduler, observeApp: Bool ) { self.defaults = defaults self.transport = transport self.clock = clock self.scheduler = scheduler let checked = Self.makeConfig( site: site, appId: appId, appVersion: appVersion, appBuild: appBuild, osVersion: osVersion, sdk: sdk ) switch checked { case .success(let config): self.config = config case .failure(let problem): self.config = nil #if DEBUG print("[CrispStats] Tracking is off: \(problem.message). Nothing will be sent.") #endif return } // The device class is read from UIKit on the main thread. Off the // main thread the work queue waits for it without blocking anybody. if let device { self.device = device } else { #if canImport(UIKit) if Thread.isMainThread { self.device = MainActor.assumeIsolated { Self.detectDevice() } } else { work.suspend() DispatchQueue.main.async { [self] in self.device = MainActor.assumeIsolated { Self.detectDevice() } self.work.resume() } } #endif } work.async { [self] in self.load() // Events saved by an earlier launch go out now. self.drain() } #if canImport(UIKit) if observeApp { observeLifecycle() } #endif } deinit { for observer in observers { NotificationCenter.default.removeObserver(observer) } } // MARK: Public API /// Counts a screen. The time spent on the previous screen is sent first. /// /// - Parameters: /// - name: One to eight segments separated by `/`, each made of letters, /// digits, spaces, `.`, `_` and `-`. An invalid name sends nothing. /// - campaign: Campaign pairs for this screen view only, such as /// `["utm_source": "newsletter"]`. See `campaign(from:)`. /// - referrer: Where the visitor came from, for this screen view only. /// - props: Custom properties on the screen view. public func screen( _ name: String, campaign: [String: String]? = nil, referrer: String? = nil, props: [String: Any]? = nil ) { let at = clock() guard config != nil, let path = Self.screenPath(name) else { return } let pairs = Self.campaignPairs(campaign ?? [:]) let ref = Self.cleanReferrer(referrer) let extra = Self.props(props) // The collector accepts 200 characters: a longer name with extra // slashes or spaces is sent in its tidy form. let sent = name.utf16.count <= 200 ? name : String(path.dropFirst()) work.async { [self] in guard let config = self.config, !self.optedOut else { return } self.pause(at: at) let base = "app://\(config.host)\(Self.encodePath(path))" self.screenName = sent self.screenURL = base self.accumulated = 0 self.shownAt = at self.backgroundAt = nil var fields: [String: Any] = [:] if let ref { fields["r"] = ref } self.enqueue(self.payload(type: "pageview", url: Self.withQuery(base, pairs), screen: sent, props: extra, fields: fields)) } } /// A custom event on the current screen. public func track(_ name: String, props: [String: Any]? = nil) { let trimmed = Self.clip(name.trimmingCharacters(in: .whitespacesAndNewlines), 120) guard config != nil, !trimmed.isEmpty else { return } let extra = Self.props(props) work.async { [self] in self.enqueue(self.payload(type: "event", url: self.currentURL(), screen: self.screenName, props: extra, fields: ["n": trimmed])) } } /// Ties this install to your own user id. public func identify(_ userId: String, traits: [String: Any]? = nil) { let trimmed = Self.clip(userId.trimmingCharacters(in: .whitespacesAndNewlines), 200) guard config != nil, !trimmed.isEmpty else { return } let extra = Self.props(traits) work.async { [self] in self.enqueue(self.payload(type: "identify", url: self.currentURL(), screen: self.screenName, props: extra, fields: ["i": trimmed])) } } /// Revenue in minor units (cents) with an ISO currency code. A negative amount is ignored. public func revenue(_ amount: Int, currency: String, props: [String: Any]? = nil) { let code = currency.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() guard config != nil, amount >= 0, Self.isCurrency(code) else { return } let extra = Self.props(props) work.async { [self] in self.enqueue(self.payload(type: "revenue", url: self.currentURL(), screen: self.screenName, props: extra, fields: ["a": amount, "c": code])) } } /// An app error. The message is grouped on the Errors page. public func recordError(_ message: String, source: String? = nil) { let text = Self.clip(message.trimmingCharacters(in: .whitespacesAndNewlines), 1000) guard config != nil, !text.isEmpty else { return } let origin = source.map { Self.clip($0.trimmingCharacters(in: .whitespacesAndNewlines), 500) } ?? "" work.async { [self] in var error: [String: Any] = ["message": text] if !origin.isEmpty { error["source"] = origin } self.enqueue(self.payload(type: "error", url: self.currentURL(), screen: self.screenName, props: nil, fields: ["e": error])) } } /// The app left the foreground: the time on the current screen is sent and /// the timer stops. Runs on its own from the background notification. public func leave() { let at = clock() guard config != nil else { return } work.async { [self] in self.pause(at: at) if self.backgroundAt == nil { self.backgroundAt = at } } } /// The app came back. After 30 minutes or more away the current screen is /// counted again, because the collector has started a new session. /// Otherwise the timer continues. Runs on its own from the foreground notification. public func resume() { let at = clock() guard config != nil else { return } work.async { [self] in let away = self.backgroundAt.map { at.timeIntervalSince($0) } ?? 0 self.backgroundAt = nil if !self.optedOut, let url = self.screenURL, let name = self.screenName, self.shownAt == nil { self.shownAt = at if away >= Self.sessionGap { self.accumulated = 0 self.enqueue(self.payload(type: "pageview", url: url, screen: name, props: nil, fields: [:])) } } self.drain() } } /// Stops sending and drops anything still queued. public func optOut() { setOptOut(true) } /// Starts sending again. public func optIn() { setOptOut(false) } /// Campaign pairs from a deep link's query, under the same rules as /// `screen(_:campaign:referrer:)`: lower-case keys of 1 to 32 letters, /// digits or `_`, values of 1 to 200 characters, at most 10 pairs. public static func campaign(from url: URL) -> [String: String] { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let items = components.percentEncodedQueryItems else { return [:] } var found: [String: String] = [:] for item in items { let key = decodeQuery(item.name).lowercased() guard isCampaignKey(key), found[key] == nil, let raw = item.value else { continue } let value = decodeQuery(raw).trimmingCharacters(in: .whitespacesAndNewlines) guard (1...200).contains(value.utf16.count) else { continue } found[key] = value } var out: [String: String] = [:] for key in found.keys.sorted().prefix(maxCampaignPairs) { out[key] = found[key] } return out } // MARK: Internal hooks for the tests /// Waits until every call made so far has been handled. Never call it on `work`. func waitUntilIdle() { work.sync {} } var pendingCount: Int { work.sync { queue.count } } var currentInstallId: String? { work.sync { installId } } /// Sends what is queued and calls `done` when the attempt stops: the queue /// is empty, a send failed, or tracking is off. func flush(_ done: @escaping @Sendable () -> Void) { work.async { [self] in self.idleWaiters.append(done) self.drain() } } // MARK: State (on `work` only) private func load() { optedOut = defaults.string(forKey: Self.optOutKey) == "1" if let saved = defaults.string(forKey: Self.installKey), Self.isInstallId(saved) { installId = saved } else if !optedOut { createInstallId() } if let data = defaults.data(forKey: Self.queueKey), let saved = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] { for body in saved.suffix(Self.queueLimit) where body["k"] is String && body["t"] is String && JSONSerialization.isValidJSONObject(body) { queue.append(Pending(seq: nextSeq, body: body)) nextSeq += 1 } } } private func createInstallId() { let created = UUID().uuidString.lowercased().replacingOccurrences(of: "-", with: "") installId = created defaults.set(created, forKey: Self.installKey) } private func setOptOut(_ out: Bool) { guard config != nil else { return } work.async { [self] in self.optedOut = out self.defaults.set(out ? "1" : "0", forKey: Self.optOutKey) if out { self.queue = [] self.screenName = nil self.screenURL = nil self.shownAt = nil self.backgroundAt = nil self.accumulated = 0 self.failures = 0 self.timerToken += 1 self.persist() self.notifyIdle() } else { if self.installId == nil { self.createInstallId() } self.drain() } } } private func pause(at: Date) { guard !optedOut, let url = screenURL, let name = screenName, let started = shownAt else { return } shownAt = nil let elapsed = at.timeIntervalSince(started) let seconds = elapsed.isFinite ? Int(min(86400, max(0, elapsed))) : 0 accumulated = min(86400, accumulated + seconds) guard accumulated > 0 else { return } enqueue(payload(type: "ping", url: url, screen: name, props: nil, fields: ["d": accumulated])) } private func currentURL() -> String { screenURL ?? "app://\(config?.host ?? "")/" } private func payload(type: String, url: String, screen: String?, props: [String: Value]?, fields: [String: Any]) -> [String: Any]? { guard let config, !optedOut, let installId else { return nil } var context: [String: Any] = [ "os": "ios", "id": config.appId, "v": config.appVersion, "ov": config.osVersion, "d": device.rawValue, "sdk": config.sdk.rawValue, "sv": Self.version, ] if let build = config.appBuild { context["b"] = build } if let screen { context["sn"] = screen } var body: [String: Any] = ["k": config.site, "t": type, "u": url, "vid": installId, "m": context] if let language = Self.language() { body["l"] = language } if let zone = Self.timeZone() { body["z"] = zone } if let props, !props.isEmpty { body["p"] = props.mapValues { $0.json } } for (key, value) in fields { body[key] = value } return body } private func enqueue(_ body: [String: Any]?) { guard let body, JSONSerialization.isValidJSONObject(body) else { return } queue.append(Pending(seq: nextSeq, body: body)) nextSeq += 1 if queue.count > Self.queueLimit { queue.removeFirst(queue.count - Self.queueLimit) } persist() drain() } private func drain() { if inFlight != nil { return } guard config != nil, !optedOut, let next = queue.first else { notifyIdle() return } guard let data = try? JSONSerialization.data(withJSONObject: next.body) else { queue.removeFirst() persist() drain() return } let seq = next.seq inFlight = seq transport(data) { [weak self] result in guard let self else { return } self.work.async { self.complete(seq, result) } } } private func complete(_ seq: Int, _ result: SendResult) { if inFlight == seq { inFlight = nil } switch result { case .ok, .drop: // Removed by identity: after an opt out the queue may hold other events. if let index = queue.firstIndex(where: { $0.seq == seq }) { queue.remove(at: index) persist() } if result == .ok { failures = 0 timerToken += 1 } drain() case .retry: if !optedOut, !queue.isEmpty { scheduleRetry() } notifyIdle() // An event queued while this one was in flight waits for the timer. } } private func scheduleRetry() { failures += 1 let delay = min(Self.maxBackoff, pow(2, Double(failures - 1))) timerToken += 1 let token = timerToken scheduler(delay) { [weak self] in guard let self else { return } self.work.async { guard token == self.timerToken else { return } self.drain() } } } private func notifyIdle() { guard inFlight == nil, !idleWaiters.isEmpty else { return } let waiters = idleWaiters idleWaiters = [] for waiter in waiters { waiter() } } private func persist() { let bodies = queue.map(\.body) guard JSONSerialization.isValidJSONObject(bodies), let data = try? JSONSerialization.data(withJSONObject: bodies) else { return } defaults.set(data, forKey: Self.queueKey) } // MARK: App lifecycle #if canImport(UIKit) private func observeLifecycle() { let center = NotificationCenter.default // The raw names avoid main-actor isolation differences between SDK versions. let background = Notification.Name("UIApplicationDidEnterBackgroundNotification") let foreground = Notification.Name("UIApplicationWillEnterForegroundNotification") observers.append(center.addObserver(forName: background, object: nil, queue: .main) { [weak self] _ in guard let self else { return } // A short background task so iOS does not suspend the app mid-send. let task = MainActor.assumeIsolated { BackgroundTask.begin() } self.leave() self.flush { task.end() } }) observers.append(center.addObserver(forName: foreground, object: nil, queue: .main) { [weak self] _ in self?.resume() }) } @MainActor private static func detectDevice() -> Device { UIDevice.current.userInterfaceIdiom == .pad ? .tablet : .phone } #endif // MARK: Validation and formatting (pure) struct Problem: Error { let message: String } static func makeConfig( site: String, appId: String, appVersion: String, appBuild: String?, osVersion: String?, sdk: SDK ) -> Result { let key = site.trimmingCharacters(in: .whitespacesAndNewlines) guard key.hasPrefix("cs_pk_"), key.utf16.count <= 64, key.utf16.count > 6 else { return .failure(Problem(message: "the site key must be the public key that starts with cs_pk_")) } let id = appId.trimmingCharacters(in: .whitespacesAndNewlines) guard isBundleId(id) else { return .failure(Problem(message: "the app id \"\(appId)\" must start with a letter or digit and use only letters, digits, '.', '_' and '-'")) } let version = clip(appVersion.trimmingCharacters(in: .whitespacesAndNewlines), 32) guard !version.isEmpty else { return .failure(Problem(message: "the app version is empty")) } let build = appBuild.map { clip($0.trimmingCharacters(in: .whitespacesAndNewlines), 32) } let os = clip((osVersion ?? "").trimmingCharacters(in: .whitespacesAndNewlines), 32) return .success(Config( site: key, appId: id, host: id.lowercased(), appVersion: version, appBuild: (build?.isEmpty ?? true) ? nil : build, osVersion: os.isEmpty ? systemVersion() : os, sdk: sdk )) } static func endpoint(_ api: String) -> URL { var root = api.trimmingCharacters(in: .whitespacesAndNewlines) while root.hasSuffix("/") { root.removeLast() } if let url = URL(string: root + "/e"), let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http", url.host != nil { return url } return URL(string: defaultAPI + "/e")! } static func urlSessionTransport(endpoint: URL, session: URLSession) -> Transport { return { body, done in var request = URLRequest(url: endpoint, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: requestTimeout) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("CrispStats-Mobile/\(version)", forHTTPHeaderField: "User-Agent") request.httpBody = body session.dataTask(with: request) { _, response, error in done(classify(status: (response as? HTTPURLResponse)?.statusCode, failed: error != nil)) }.resume() } } /// 2xx removes the event. 408, 429, 5xx and network errors keep it. Other 4xx drop it. static func classify(status: Int?, failed: Bool) -> SendResult { guard !failed, let status else { return .retry } if (200..<300).contains(status) { return .ok } if status == 408 || status == 429 || status >= 500 { return .retry } if (400..<500).contains(status) { return .drop } return .retry } /// The path a screen is stored under, exactly like `screenPath` in the /// shared package: "Settings/Account" becomes "/Settings/Account". static func screenPath(_ name: String) -> String? { let parts = name.split(separator: "/", omittingEmptySubsequences: false) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } guard !parts.isEmpty, parts.count <= 8 else { return nil } for part in parts { if part == "." || part == ".." || !isScreenSegment(part) { return nil } } let path = "/" + parts.joined(separator: "/") return path.utf16.count <= 200 ? path : nil } private static func isScreenSegment(_ part: String) -> Bool { let bytes = Array(part.utf8) guard (1...80).contains(bytes.count), bytes.count == part.utf16.count else { return false } for (index, byte) in bytes.enumerated() { let alnum = (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5A) || (byte >= 0x61 && byte <= 0x7A) if index == 0 { if !alnum { return false } } else if !(alnum || byte == 0x20 || byte == 0x2E || byte == 0x5F || byte == 0x2D) { return false } } return true } static func isBundleId(_ id: String) -> Bool { let bytes = Array(id.utf8) guard (1...200).contains(bytes.count) else { return false } for (index, byte) in bytes.enumerated() { let alnum = (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5A) || (byte >= 0x61 && byte <= 0x7A) if index == 0 { if !alnum { return false } } else if !(alnum || byte == 0x2E || byte == 0x5F || byte == 0x2D) { return false } } return true } static func isCampaignKey(_ key: String) -> Bool { let bytes = Array(key.utf8) guard (1...32).contains(bytes.count) else { return false } return bytes.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x7A) || $0 == 0x5F } } /// Valid pairs, keys sorted, at most 10. static func campaignPairs(_ raw: [String: String]) -> [(String, String)] { var found: [String: String] = [:] for original in raw.keys.sorted() { let key = original.lowercased() guard isCampaignKey(key), found[key] == nil, let rawValue = raw[original] else { continue } let value = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) guard (1...200).contains(value.utf16.count) else { continue } found[key] = value } return found.keys.sorted().prefix(maxCampaignPairs).map { ($0, found[$0]!) } } private static let queryAllowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") /// `base?k=v&…`. Pairs are dropped from the end if the URL would pass the collector's 2,048 limit. static func withQuery(_ base: String, _ pairs: [(String, String)]) -> String { var kept = pairs while !kept.isEmpty { let query = kept.map { "\($0.0)=\($0.1.addingPercentEncoding(withAllowedCharacters: queryAllowed) ?? "")" } .joined(separator: "&") let url = base + "?" + query if url.utf16.count <= maxURLLength { return url } kept.removeLast() } return base } /// Spaces in a screen name are written as %20 in the URL. The collector reads the name from `m.sn`. static func encodePath(_ path: String) -> String { path.replacingOccurrences(of: " ", with: "%20") } private static func decodeQuery(_ text: String) -> String { let spaced = text.replacingOccurrences(of: "+", with: " ") return spaced.removingPercentEncoding ?? spaced } static func cleanReferrer(_ referrer: String?) -> String? { guard let value = referrer?.trimmingCharacters(in: .whitespacesAndNewlines), (1...2000).contains(value.utf16.count) else { return nil } return value } private static func isCurrency(_ code: String) -> Bool { let bytes = Array(code.utf8) return bytes.count == 3 && bytes.allSatisfy { $0 >= 0x41 && $0 <= 0x5A } } static func isInstallId(_ value: String) -> Bool { let bytes = Array(value.utf8) return bytes.count == 32 && bytes.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) } } /// BCP-47, like the website and Android: `en-IN`, not `en_IN@rg=…`. static func language() -> String? { var tag = Locale.preferredLanguages.first ?? Locale.current.identifier if let at = tag.firstIndex(of: "@") { tag = String(tag[.. String? { let zone = TimeZone.current.identifier return zone.isEmpty ? nil : clip(zone, 64) } /// `18.2`, or `18.2.1` when there is a patch number, as `UIDevice.systemVersion` writes it. static func systemVersion() -> String { let v = ProcessInfo.processInfo.operatingSystemVersion return v.patchVersion > 0 ? "\(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" : "\(v.majorVersion).\(v.minorVersion)" } /// At most `max` UTF-16 units (the collector counts in JavaScript), never splitting a character. static func clip(_ text: String, _ max: Int) -> String { if text.utf16.count <= max { return text } var out = "" var used = 0 for character in text { let size = character.utf16.count if used + size > max { break } out.append(character) used += size } return out } // MARK: Properties enum Value: Sendable, Equatable { case string(String) case int(Int) case double(Double) case bool(Bool) case null var json: Any { switch self { case .string(let text): return text case .int(let number): return number case .double(let number): return number case .bool(let flag): return flag case .null: return NSNull() } } } private static let reserved: Set = ["app_version", "app_build", "os_version", "sdk", "sdk_version"] /// Flat properties: at most 30, keys up to 60 characters, text up to 500. /// Runs on the caller's thread so only plain values cross to the work queue. static func props(_ raw: [String: Any]?) -> [String: Value]? { guard let raw else { return nil } var out: [String: Value] = [:] for original in raw.keys.sorted() { if out.count >= 30 { break } let key = clip(original.trimmingCharacters(in: .whitespacesAndNewlines), 60) guard !key.isEmpty, !reserved.contains(key), let value = raw[original], let clean = propValue(value) else { continue } out[key] = clean } return out.isEmpty ? nil : out } private static func propValue(_ value: Any) -> Value? { if let text = value as? String { return .string(clip(text, 500)) } if value is NSNull { return .null } let mirror = Mirror(reflecting: value) if mirror.displayStyle == .optional { guard let wrapped = mirror.children.first?.value else { return nil } return propValue(wrapped) } if let number = value as? NSNumber { if CFGetTypeID(number) == CFBooleanGetTypeID() { return .bool(number.boolValue) } if CFNumberIsFloatType(number) { let double = number.doubleValue return double.isFinite ? .double(double) : nil } return .int(number.intValue) } return .string(clip(String(describing: value), 500)) } } #if canImport(UIKit) /// A short `beginBackgroundTask` around the flush that runs on entering the /// background. In an app extension there is no shared application, so this /// does nothing there. `UIApplication.shared` is looked up at run time /// because it is unavailable to code compiled for an extension. private final class BackgroundTask: @unchecked Sendable { private let lock = NSLock() private var identifier: UIBackgroundTaskIdentifier = .invalid private var application: UIApplication? @MainActor static func begin() -> BackgroundTask { let task = BackgroundTask() guard Bundle.main.bundleURL.pathExtension != "appex", let app = UIApplication.value(forKey: "sharedApplication") as? UIApplication else { return task } let identifier = app.beginBackgroundTask(withName: "CrispStats flush") { task.end() } task.lock.lock() task.application = app task.identifier = identifier task.lock.unlock() return task } /// Safe to call more than once and from any thread. func end() { lock.lock() let identifier = self.identifier let app = application self.identifier = .invalid application = nil lock.unlock() if identifier != .invalid { app?.endBackgroundTask(identifier) } } } #endif