// The OS, scripted — so every gate in this app has a test with no device, no // prompt and no simulator. // // It ships in `CottonKit` rather than in a test bundle for the reason // ``ScriptedCore`` does: two test targets and three previews need it, and a // second copy is a second set of rules that can disagree with the first. // // It records WHAT WAS ASKED, which is the assertion most of these tests want: // "a decided capability is never re-prompted" is only expressible if something // counts the prompts that would have happened. import Foundation /// A stand-in authority with the answers written down in advance. /// /// A `final class` with a lock rather than an actor, because a test asserts /// what was asked SYNCHRONOUSLY after an `await` — and because an actor would /// make every read of ``asked`` another suspension point in a test that is /// trying to pin an order. public final class ScriptedCapabilityAuthority: CapabilityAuthority, @unchecked Sendable { private let lock = NSLock() private var statuses: [DeviceCapability: CapabilityAccess] private var grants: [DeviceCapability: CapabilityAccess] private var prompts: [DeviceCapability] = [] /// - Parameters: /// - statuses: where each capability stands before anything is asked. /// Anything unnamed is ``CapabilityAccess/notDetermined``. /// - grants: what a PROMPT turns a `notDetermined` capability into. /// Anything unnamed is refused, because a test that forgot to say is a /// test whose subject should take the unhappy path rather than silently /// the happy one. public init( statuses: [DeviceCapability: CapabilityAccess] = [:], grants: [DeviceCapability: CapabilityAccess] = [:] ) { self.statuses = statuses self.grants = grants } /// Every capability a PROMPT was actually raised for, in order. A /// capability that was already decided never lands here — which is the /// whole point. public var asked: [DeviceCapability] { lock.withLock { prompts } } public func status(_ capability: DeviceCapability) async -> CapabilityAccess { lock.withLock { statuses[capability] ?? .notDetermined } } public func ask(_ capability: DeviceCapability) async -> CapabilityAccess { lock.withLock { let standing = statuses[capability] ?? .notDetermined guard standing.canBeAsked else { return standing } prompts.append(capability) let answered = grants[capability] ?? .denied statuses[capability] = answered return answered } } }