/* * Copyright (c) 2026 Ping Identity Corporation. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import Foundation import PingDavinci import PingDavinciPlugin import PingLogger import PingOrchestrate import RNPingCore /// Maps native iOS DaVinci nodes and collectors to React Native bridge payloads. enum DaVinciNodeMapper { private static let logTag = "DaVinciNodeMapper" private static let qrCode = "QR_CODE" private static let socialLoginButton = "SOCIAL_LOGIN_BUTTON" private static let image = "IMAGE" private static let metadataType = "METADATA" /// Converts a native DaVinci node to a bridge-friendly dictionary payload. /// /// - Parameters: /// - node: Native DaVinci node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized node payload. static func mapNode( _ node: Node, logger: Logger? = nil ) -> NSDictionary { return JsonBridgeMapper.encodeJsonObject(mapNodePayload(node, logger: logger)) } /// Builds a plain dictionary payload for a native node. /// /// - Parameters: /// - node: Native DaVinci node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serializable node payload map. static func mapNodePayload( _ node: Node, logger: Logger? = nil ) -> [String: Any] { var payload = [String: Any]() switch node { case let continueNode as ContinueNode: payload["type"] = "ContinueNode" payload["id"] = continueNode.id payload["name"] = continueNode.name payload["description"] = continueNode.description payload["category"] = continueNode.category payload["collectors"] = mapCollectors(continueNode, logger: logger) payload["input"] = JsonBridgeMapper.encodeJsonObject(continueNode.input) let unsupported = unsupportedFields(continueNode, logger: logger) if !unsupported.isEmpty { payload["unsupportedFields"] = unsupported } case let successNode as SuccessNode: payload["type"] = "SuccessNode" payload["session"] = ["value": successNode.session.value] case let errorNode as ErrorNode: payload["type"] = "ErrorNode" payload["message"] = errorNode.message payload["input"] = JsonBridgeMapper.encodeJsonObject(errorNode.input) if let status = errorNode.status { payload["status"] = status } case let failureNode as FailureNode: let causeMessage = failureNode.cause.localizedDescription payload["type"] = "FailureNode" payload["message"] = causeMessage payload["cause"] = causeMessage if case let ApiError.error(status, _, _) = failureNode.cause { payload["status"] = status } default: payload["type"] = "FailureNode" payload["message"] = "Unsupported node type: \(String(describing: type(of: node)))" } return payload } /// Maps a native `ValidationError` to the stable JS-facing error code contract. /// /// - Parameter error: Native validation error produced by a collector's `validate()`. /// - Returns: Serialized `{code, ...}` error payload. static func encodeValidationError(_ error: ValidationError) -> [String: Any] { switch error { case .required: return ["code": "REQUIRED"] case .regexError(let message): return ["code": "REGEX_ERROR", "message": message] case .invalidLength(let min, let max): return ["code": "INVALID_LENGTH", "min": min, "max": max] case .uniqueCharacter(let min): return ["code": "UNIQUE_CHARACTER", "min": min] case .maxRepeat(let max): return ["code": "MAX_REPEAT", "max": max] case .minCharacters(let character, let min): return ["code": "MIN_CHARACTERS", "character": character, "min": min] } } /// Maps a list of native `ValidationError`s captured from a submitted collector. /// /// - Parameter errors: Native validation errors from a collector's `validate()` call. /// - Returns: Serialized list of `{code, ...}` error payloads. static func encodeValidationErrors(_ errors: [ValidationError]) -> [[String: Any]] { return errors.map(encodeValidationError) } /// Serializes all `Collector` instances from a `ContinueNode` into an array. /// /// Unknown collector subtypes are skipped gracefully. /// /// - Parameters: /// - node: Active continue node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized collectors array. private static func mapCollectors(_ node: ContinueNode, logger: Logger?) -> [[String: Any]] { var output = [[String: Any]]() for collector in node.collectors { if let map = mapCollector(collector, node: node, logger: logger) { output.append(map) } } return output } /// Diffs the raw form fields against the collectors the native SDK instantiated. /// /// Surfaces field entries from `node.input.form.components.fields[]` whose /// `inputType`/`type` was not registered with the native `CollectorFactory` — these /// are silently dropped by the SDK and would otherwise be invisible to JS consumers. /// /// The resolution order (`inputType` preferred over `type`) mirrors /// `CollectorFactory.collector(daVinci:from:)` in the iOS DaVinci SDK. /// /// - Parameters: /// - node: Active continue node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Array of `{ key, type }` entries describing dropped fields. private static func unsupportedFields(_ node: ContinueNode, logger: Logger?) -> [[String: Any]] { guard let fields = formFields(node, logger: logger) else { return [] } let registeredKeys = Set(node.collectors.map { $0.id }) // TODO-SDK-PARITY: IdpCollector.id (PingExternalIdP 2.2.0) falls back to a fresh // random UUID per call — it never matches the server field's real `key`. Excluding // SOCIAL_LOGIN_BUTTON here avoids reporting a field the SDK *did* instantiate a // collector for (and that the registered plugin serializer serialized) as // dropped/unsupported. Remove this exclusion once the native SDK reads `key`. let hasSerializedIdp = node.collectors.contains { collector in guard CoreRuntime.serializeDaVinciCollector(collector)?["type"] as? String == socialLoginButton else { return false } return true } var entries = [[String: Any]]() for field in fields { guard let key = field["key"] as? String else { continue } // Mirrors CollectorFactory.collector(daVinci:from:): inputType takes precedence over type. guard let resolvedType = (field["inputType"] as? String) ?? (field["type"] as? String) else { continue } if resolvedType == socialLoginButton && hasSerializedIdp { continue } // A field is supported when the SDK instantiated a collector for its key. guard !registeredKeys.contains(key) else { continue } entries.append(["key": key, "type": resolvedType]) } return entries } // MARK: - Form-field JSON navigation helpers /// Reads `node.input.form.components.fields[]` as a flat array of field dictionaries. /// /// - Parameters: /// - node: Active continue node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: The fields array, or `nil` when the path is absent or malformed. private static func formFields(_ node: ContinueNode, logger: Logger?) -> [[String: Any]]? { guard let form = node.input["form"] as? [String: Any], let components = form["components"] as? [String: Any], let fields = components["fields"] as? [[String: Any]] else { return nil } return fields } /// Locates the field-level dictionary whose `key` matches `collectorKey`. /// /// - Parameters: /// - collectorKey: The collector key to match against field entries. /// - node: Active continue node. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: The matching field dictionary, or `nil` when not present. private static func findFieldJson( _ collectorKey: String, node: ContinueNode, logger: Logger? ) -> [String: Any]? { return formFields(node, logger: logger)?.first { ($0["key"] as? String) == collectorKey } } /// Resolves the server-declared type for a collector whose class is not a known compile-time /// type, by reading `inputType` (preferred) or `type` from the matching form field in /// `node.input.form.components.fields[]`. /// /// Used to detect collectors from optional SDK packages without importing those packages. /// The field type is what the server sent, so this remains correct regardless of SDK renames /// or package restructuring. /// /// - Parameters: /// - collector: Collector whose class was not matched by the primary switch cases. /// - node: Active continue node providing form field context. /// - logger: Optional Ping logger for non-fatal navigation warnings. /// - Returns: The resolved field type string, or `nil` if the field is absent. static func resolvedFormFieldType( for collector: any Collector, node: ContinueNode, logger: Logger? ) -> String? { let fieldJson = findFieldJson(collector.id, node: node, logger: logger) return (fieldJson?["inputType"] as? String) ?? (fieldJson?["type"] as? String) } /// Looks up the field-level JSON for a collector and emits it as `raw` on the collector map. /// /// Collectors whose key has no matching field entry (e.g. action buttons) have `raw` omitted. /// /// - Parameters: /// - map: Mutable collector map to annotate with the raw field JSON. /// - collectorKey: The collector key used to look up the matching field entry. /// - node: Active continue node. /// - logger: Optional Ping logger for non-fatal mapping warnings. private static func applyRawField( _ map: inout [String: Any], collectorKey: String, node: ContinueNode, logger: Logger? ) { guard let field = findFieldJson(collectorKey, node: node, logger: logger) else { return } map["raw"] = JsonBridgeMapper.encodeJsonObject(field) } /// Serializes a single collector to a bridge map. /// /// - Parameters: /// - collector: Native collector instance to serialize. /// - node: Active continue node providing form field context. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized collector map, or `nil` for unknown collector subtypes. private static func mapCollector( _ collector: any Collector, node: ContinueNode, logger: Logger? ) -> [String: Any]? { var map: [String: Any]? switch collector { case let textCollector as TextCollector: map = mapTextCollector(textCollector, node: node) case let passwordCollector as PasswordCollector: map = mapPasswordCollector(passwordCollector, logger: logger) case let submitCollector as SubmitCollector: map = mapBaseFieldCollector(submitCollector) case let flowCollector as FlowCollector: map = mapBaseFieldCollector(flowCollector) case let labelCollector as LabelCollector: map = mapLabelCollector(labelCollector) case let singleSelectCollector as SingleSelectCollector: map = mapSingleSelectCollector(singleSelectCollector) case let multiSelectCollector as MultiSelectCollector: map = mapMultiSelectCollector(multiSelectCollector) case let phoneNumberCollector as PhoneNumberCollector: map = mapPhoneNumberCollector(phoneNumberCollector) case let registrationCollector as DeviceRegistrationCollector: map = mapDeviceRegistrationCollector(registrationCollector) case let authenticationCollector as DeviceAuthenticationCollector: map = mapDeviceAuthenticationCollector(authenticationCollector) case let booleanCollector as BooleanCollector: map = mapBooleanCollector(booleanCollector) case let readOnlyCollector as ReadOnlyTextCollector: map = mapReadOnlyTextCollector(readOnlyCollector) case let pollingCollector as PollingCollector: map = mapPollingCollector(pollingCollector) case let qrCodeCollector as QRCodeCollector: // QRCodeCollector's `key` is parsed natively but it does not // extend FieldCollector — no `label`/`required` — so it's fully serialized here and // returned early rather than routed through `applyRawField` below. return mapQRCodeCollector(qrCodeCollector, node: node, logger: logger) case let imageCollector as ImageCollector: map = mapImageCollector(imageCollector, node: node, logger: logger) case let metadataCollector as MetadataCollector: map = mapMetadataCollector(metadataCollector, node: node, logger: logger) default: // Try registered plugin serializers before generic server-type fallback. if let serialized = CoreRuntime.serializeDaVinciCollector(collector) { let fieldKey = (serialized["key"] as? String) ?? "" var mutableMap = serialized applyRawField(&mutableMap, collectorKey: fieldKey, node: node, logger: logger) return mutableMap } if let resolvedType = resolvedFormFieldType(for: collector, node: node, logger: logger) { // No registered serializer handled this collector, so it falls back to the // generic {key, type} payload (top-level fields like `action` are dropped). // This is the exact failure mode diagnosed in SDKS-5302: an integration // collector type whose native serializer never registered. logger?.w( "[\(logTag)] No serializer registered for collector type=\(resolvedType) (key=\(collector.id)); " + "falling back to generic {key, type} payload", error: nil ) map = ["key": collector.id, "type": resolvedType] } else { logger?.w( "[\(logTag)] Skipping unsupported collector type: \(String(describing: type(of: collector)))", error: nil ) return nil } } guard var collectorMap = map else { return nil } applyRawField(&collectorMap, collectorKey: collector.id, node: node, logger: logger) return collectorMap } // MARK: - Field collector helpers /// Serializes base FieldCollector fields (key, type, label, required) into a map. /// /// - Parameter collector: FieldCollector instance. /// - Returns: Base collector map. private static func baseFieldCollectorMap(_ collector: FieldCollector) -> [String: Any] { return [ "key": collector.key, "type": collector.type, "label": collector.label, "required": collector.required ] } /// Serializes base FieldCollector fields into a map without additional specialization. /// /// - Parameter collector: FieldCollector instance. /// - Returns: Base collector map. private static func mapBaseFieldCollector(_ collector: FieldCollector) -> [String: Any] { return baseFieldCollectorMap(collector) } /// Serializes a `TextCollector` to a bridge map, including value and optional validation regex. /// /// - Parameters: /// - collector: TextCollector instance. /// - node: Active continue node providing form field context. /// - Returns: Serialized text collector map. private static func mapTextCollector(_ collector: TextCollector, node: ContinueNode) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["value"] = collector.value if let validation = collector.validation, let regex = validation.regex { map["validation"] = ["regex": regex.pattern] } return map } /// Serializes a `PasswordCollector` to a bridge map. /// /// - Note: The `value` field is always emitted as `""` and never reflects the native /// collector's current value. Password fields are treated as write-only across the /// bridge — JS may push a value into the collector via `next()`, but the bridge /// never round-trips the entered password back to JS. This matches the /// `PasswordCollector.value` contract in the public TypeScript types and aligns /// with the Android bridge's emission. /// /// - Note: `passwordPolicy` is read through the native `passwordPolicy()` accessor, /// which resolves the field-level policy first and falls back to the node-root policy. private static func mapPasswordCollector( _ collector: PasswordCollector, logger: Logger? ) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["value"] = "" map["clearPassword"] = collector.clearPassword if let validation = collector.validation, let regex = validation.regex { map["validation"] = ["regex": regex.pattern] } if let policy = collector.passwordPolicy(), let encoded = encodePasswordPolicy(policy, logger: logger) { map["passwordPolicy"] = encoded } return map } /// Serializes a native `PasswordPolicy` into its bridge payload shape. /// /// - Parameters: /// - policy: Native password policy value. /// - logger: Optional Ping logger for non-fatal encoding warnings. /// - Returns: Bridge-encoded password policy dictionary, or `nil` on encoding failure. private static func encodePasswordPolicy(_ policy: PasswordPolicy, logger: Logger?) -> NSDictionary? { do { let encoded = try JSONEncoder().encode(policy) if let object = try JSONSerialization.jsonObject(with: encoded) as? [String: Any] { return JsonBridgeMapper.encodeJsonObject(object) } return nil } catch { logger?.w("[\(logTag)] Failed to encode password policy", error: error) return nil } } /// Serializes a `LabelCollector` to a bridge map. /// /// - Parameter collector: LabelCollector instance. /// - Returns: Serialized label collector map. private static func mapLabelCollector(_ collector: LabelCollector) -> [String: Any] { var map: [String: Any] = [ "key": collector.key, "type": "LABEL", "content": collector.content ] if let rc = collector.richContent { map["richContent"] = encodeRichContent(rc) } return map } /// Serializes a native `RichContent` into its bridge payload shape. /// /// - Parameter rc: Native rich-content payload. /// - Returns: Serialized `{content, replacements}` map. private static func encodeRichContent(_ rc: RichContent) -> [String: Any] { return [ "content": rc.content, "replacements": Dictionary( uniqueKeysWithValues: rc.replacements.map { (k, r) in (k, [ "value": r.value, "href": r.href ?? "", "type": r.type, "target": r.target ?? "" ] as [String: Any]) } ) ] } /// Serializes a `SingleSelectCollector` to a bridge map, including value and options. /// /// - Parameter collector: SingleSelectCollector instance. /// - Returns: Serialized single-select collector map. private static func mapSingleSelectCollector(_ collector: SingleSelectCollector) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["value"] = collector.value map["options"] = mapOptions(collector.options) if let validation = collector.validation, let regex = validation.regex { map["validation"] = ["regex": regex.pattern] } return map } /// Serializes a `MultiSelectCollector` to a bridge map, including value and options. /// /// - Parameter collector: MultiSelectCollector instance. /// - Returns: Serialized multi-select collector map. private static func mapMultiSelectCollector(_ collector: MultiSelectCollector) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["value"] = collector.value map["options"] = mapOptions(collector.options) return map } /// Serializes a `PhoneNumberCollector` to a bridge map. /// /// - Parameter collector: PhoneNumberCollector instance. /// - Returns: Serialized phone number collector map. private static func mapPhoneNumberCollector(_ collector: PhoneNumberCollector) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["defaultCountryCode"] = collector.defaultCountryCode map["validatePhoneNumber"] = collector.validatePhoneNumber map["countryCode"] = collector.countryCode map["phoneNumber"] = collector.phoneNumber map["extension"] = collector.extension map["showExtension"] = collector.showExtension map["extensionLabel"] = collector.extensionLabel return map } /// Serializes a `DeviceRegistrationCollector` to a bridge map, including available devices. /// /// - Parameter collector: DeviceRegistrationCollector instance. /// - Returns: Serialized device registration collector map. private static func mapDeviceRegistrationCollector( _ collector: DeviceRegistrationCollector ) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["devices"] = mapDevices(collector.devices) return map } /// Serializes a `DeviceAuthenticationCollector` to a bridge map, including available devices. /// /// - Parameter collector: DeviceAuthenticationCollector instance. /// - Returns: Serialized device authentication collector map. private static func mapDeviceAuthenticationCollector( _ collector: DeviceAuthenticationCollector ) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["devices"] = mapDevices(collector.devices) return map } /// Serializes a `BooleanCollector` to a bridge map. /// /// - Parameter collector: BooleanCollector instance. /// - Returns: Serialized boolean collector map. /// - Note: `errorMessage` is nullable on iOS — emitted as `""` when absent to match the Android non-null contract. private static func mapBooleanCollector(_ collector: BooleanCollector) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["value"] = collector.value map["appearance"] = collector.appearance.rawValue map["errorMessage"] = collector.errorMessage ?? "" if let rc = collector.richContent { map["richContent"] = encodeRichContent(rc) } return map } /// Serializes a `PollingCollector` to a bridge map. /// /// - Note: `pollInterval`/`pollRetries` are native `Int` on iOS — Android's native /// collector types them as `String`; the bridge normalizes both to `number` in TS. /// /// - Parameter collector: PollingCollector instance. /// - Returns: Serialized polling collector map. private static func mapPollingCollector(_ collector: PollingCollector) -> [String: Any] { var map = baseFieldCollectorMap(collector) map["pollInterval"] = collector.pollInterval map["pollRetries"] = collector.pollRetries map["pollChallengeStatus"] = collector.pollChallengeStatus map["challenge"] = collector.challenge return map } /// Serializes a `QRCodeCollector` to a bridge map. /// /// - Note: Native SDK 2.2.0's `QRCodeCollector.content` retains the complete data URI /// as received from the server, so the bridge passes it through directly. Android's /// native `content` getter behaves the same way. The bridge no longer needs to /// reconstruct the data URI from decoded `imageData` bytes. /// /// - Parameters: /// - collector: QRCodeCollector instance. /// - node: Active continue node providing form field context for the `raw` field lookup. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized QR code collector map. private static func mapQRCodeCollector( _ collector: QRCodeCollector, node: ContinueNode, logger: Logger? ) -> [String: Any] { let field = findFieldJson(collector.key, node: node, logger: logger) var map: [String: Any] = [ "key": collector.key, "type": qrCode, "content": collector.content, "fallbackText": collector.fallbackText ] if let field { map["raw"] = JsonBridgeMapper.encodeJsonObject(field) } return map } /// Serializes an `ImageCollector` to a bridge map. /// /// - Note: The collector is display-only: native `payload()` always returns /// `nil`, and the bridge never applies values to it. `hyperlinkUrl` is /// omitted from the payload when the native collector holds `nil`, matching /// the optional TS field. iOS `ImageCollector.id` returns the stable `key`, /// so the shared `raw` lookup applies. /// /// - Parameters: /// - collector: ImageCollector instance. /// - node: Active continue node providing form field context for the `raw` lookup. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized image collector map. private static func mapImageCollector( _ collector: ImageCollector, node: ContinueNode, logger: Logger? ) -> [String: Any] { if collector.imageUrl.isEmpty { // No-silent-failure: native init coerces a missing/non-string imageUrl // to "" (native 2.2 default). Surface the offending raw server value. let rawUrl = findFieldJson(collector.key, node: node, logger: logger)?["imageUrl"] logger?.w( "[\(logTag)] IMAGE collector key='\(collector.key)' has no usable imageUrl after " + "native init (server value: \(rawUrl.map { String(describing: $0) } ?? "absent")); " + "emitting empty string", error: nil ) } var map: [String: Any] = [ "key": collector.key, "type": image, "imageUrl": collector.imageUrl, "description": collector.description ] if let hyperlinkUrl = collector.hyperlinkUrl { map["hyperlinkUrl"] = hyperlinkUrl } return map } /// Serializes a `MetadataCollector` to a bridge map. /// /// The collector is a resume-capable pause point: JS reads `metadata`, performs /// on-device work, and POSTs a result back through `next()` (applied by /// `DaVinciCollectorValueApplier`). /// /// - Note: iOS's native `MetadataCollector` is an `AnyFieldCollector` — it does not /// extend `FieldCollector` and therefore has no native `label`/`required` (unlike /// Android's `FieldCollector` subtype, which exposes both natively). /// The bridge synthesizes `label` (`""` default) and `required` (`false` default) /// from the matching raw form field JSON so the serialized shape matches Android's. /// Actual submission gating is result-set-based (native `validate()` returns /// `.required` until `setResult`/`setError` is called), independent of the /// server `required` flag. /// TODO-PARITY (SDKS-5546): synthesize `label`/`required` here only until the iOS /// `MetadataCollector` exposes them natively. /// /// - Note: The server's `payload` is the connector's contract with the app; it is /// serialized as `metadata` as-is (no transformation, no filtering). A `payload` /// present but not a dictionary is unreachable on Android — native `init` throws /// before the bridge ever sees the collector — so the warning + `[:]` fallback /// here is iOS-only behavior. /// TODO-PARITY (SDKS-5546): iOS init silently defaults a non-object `payload` to /// empty metadata while Android throws; drop the fallback once the SDKs align. /// /// - Parameters: /// - collector: MetadataCollector instance. /// - node: Active continue node providing form field context for the synthesized /// `label`/`required` and the `raw` lookup. /// - logger: Optional Ping logger for non-fatal mapping warnings. /// - Returns: Serialized metadata collector map. private static func mapMetadataCollector( _ collector: MetadataCollector, node: ContinueNode, logger: Logger? ) -> [String: Any] { let field = findFieldJson(collector.key, node: node, logger: logger) var metadata = collector.metadata if let payload = field?["payload"], !(payload is [String: Any]) { // No-silent-failure: native init coerces a non-dictionary payload to [:] // (native 2.2 default). Surface the offending server value before emitting // the documented default. Android never reaches this state: native init // throws on a non-object payload, so the collector never exists to map. logger?.w( "[\(logTag)] METADATA collector key='\(collector.key)' has non-dictionary payload " + "(server value: \(payload)); emitting empty metadata", error: nil ) metadata = [:] } var map: [String: Any] = [ "key": collector.key, "type": metadataType, "label": (field?["label"] as? String) ?? "", "required": (field?["required"] as? Bool) ?? false, "metadata": JsonBridgeMapper.encodeJsonObject(metadata) ] if let field { map["raw"] = JsonBridgeMapper.encodeJsonObject(field) } return map } /// Serializes a `ReadOnlyTextCollector` to a bridge map. /// /// The `type` field is normalized to `"READ_ONLY_TEXT"` (the stable inputType) rather /// than emitting the server-varying `collector.type` (e.g. `"AGREEMENT"`). /// /// - Parameter collector: ReadOnlyTextCollector instance. /// - Returns: Serialized read-only text collector map. private static func mapReadOnlyTextCollector(_ collector: ReadOnlyTextCollector) -> [String: Any] { return [ "key": collector.key, "type": "READ_ONLY_TEXT", "content": collector.content, "title": collector.title, "titleEnabled": collector.titleEnabled, "enabled": collector.enabled, "agreementId": collector.agreementId, "useDynamicAgreement": collector.useDynamicAgreement ] } /// Converts an array of `Option` values to serializable bridge maps. /// /// - Parameter options: Native option values from a select collector. /// - Returns: Array of `{ label, value }` dictionaries. private static func mapOptions(_ options: [Option]) -> [[String: Any]] { return options.map { option in ["label": option.label, "value": option.value] } } /// Converts an array of `Device` values to serializable bridge maps. /// /// - Parameter devices: Native device entries from a device collector. /// - Returns: Array of device dictionaries with type, title, iconSrc, isDefault, and optional id and description. private static func mapDevices(_ devices: [Device]) -> [[String: Any]] { return devices.map { device in var map: [String: Any] = [ "type": device.type, "title": device.title, "iconSrc": device.iconSrc.absoluteString, "isDefault": device.isDefault ?? false ] if let id = device.id { map["id"] = id } if let description = device.description { map["description"] = description } return map } } }