public import Foundation public enum IPCProtocol { public static let version = 1 public static let maximumMessageBytes = 1_048_576 public static func parseWindowID(_ argument: String) -> UInt32? { guard !argument.isEmpty, argument.utf8.allSatisfy({ (48...57).contains($0) }), let window = UInt32(argument), window != 0 else { return nil } return window } } public enum JSONValue: Sendable, Equatable, Codable { case null case bool(Bool) case integer(Int64) case number(Double) case string(String) case array([JSONValue]) case object([String: JSONValue]) public init(from decoder: any Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .null } else { do { self = .bool(try container.decode(Bool.self)) } catch DecodingError.typeMismatch { self = try Self.decodeRemaining(container) } } } private static func decodeRemaining(_ container: any SingleValueDecodingContainer) throws -> Self { do { let number = try container.decode(Double.self) if number.rounded() == number, number >= Double(Int64.min), number <= Double(Int64.max) { do { return .integer(try container.decode(Int64.self)) } catch DecodingError.dataCorrupted { return .number(number) } } return .number(number) } catch DecodingError.typeMismatch {} do { return .string(try container.decode(String.self)) } catch DecodingError.typeMismatch {} do { return .array(try container.decode([JSONValue].self)) } catch DecodingError.typeMismatch {} return .object(try container.decode([String: JSONValue].self)) } public func encode(to encoder: any Encoder) throws { var container = encoder.singleValueContainer() switch self { case .null: try container.encodeNil() case .bool(let value): try container.encode(value) case .integer(let value): try container.encode(value) case .number(let value): try container.encode(value) case .string(let value): try container.encode(value) case .array(let value): try container.encode(value) case .object(let value): try container.encode(value) } } } public enum IPCRequestID: Sendable, Equatable, Hashable, Codable { case string(String) case integer(Int64) public init(from decoder: any Decoder) throws { let container = try decoder.singleValueContainer() do { self = .string(try container.decode(String.self)) } catch DecodingError.typeMismatch { self = .integer(try container.decode(Int64.self)) } } public func encode(to encoder: any Encoder) throws { var container = encoder.singleValueContainer() switch self { case .string(let value): try container.encode(value) case .integer(let value): try container.encode(value) } } } public struct IPCRequest: Sendable, Equatable, Codable { // pi-lens-ignore: identifier_name public var v: Int public var id: IPCRequestID public var command: String public var args: [String] public init( id: IPCRequestID = .string(UUID().uuidString), command: String, args: [String] = [], // pi-lens-ignore: identifier_name v: Int = IPCProtocol.version ) { self.v = v self.id = id self.command = command self.args = args } } public struct IPCError: Error, Sendable, Equatable, Codable, LocalizedError { public var code: String public var message: String public init(code: String, message: String) { self.code = code self.message = message } public var errorDescription: String? { message } } public struct IPCResponse: Sendable, Equatable, Codable { // pi-lens-ignore: identifier_name public let v: Int public let id: IPCRequestID? public let ok: Bool public let result: JSONValue? public let error: IPCError? // pi-lens-ignore: identifier_name public init(id: IPCRequestID?, result: JSONValue, v: Int = IPCProtocol.version) { self.v = v self.id = id self.ok = true self.result = result self.error = nil } // pi-lens-ignore: identifier_name public init(id: IPCRequestID?, error: IPCError, v: Int = IPCProtocol.version) { self.v = v self.id = id self.ok = false self.result = nil self.error = error } // pi-lens-ignore: identifier_name private enum CodingKeys: String, CodingKey { case v, id, ok, result, error } public init(from decoder: any Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) v = try container.decode(Int.self, forKey: .v) id = try container.decodeIfPresent(IPCRequestID.self, forKey: .id) ok = try container.decode(Bool.self, forKey: .ok) if ok { guard container.contains(.result), !container.contains(.error) else { throw DecodingError.dataCorruptedError( forKey: .result, in: container, debugDescription: "A successful response must contain only a result.") } result = try container.decode(JSONValue.self, forKey: .result) error = nil } else { guard !container.contains(.result) else { throw DecodingError.dataCorruptedError( forKey: .error, in: container, debugDescription: "A failed response must contain only an error.") } result = nil error = try container.decode(IPCError.self, forKey: .error) } } public func encode(to encoder: any Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(v, forKey: .v) try container.encode(id, forKey: .id) try container.encode(ok, forKey: .ok) if ok { try container.encode(result, forKey: .result) } else { try container.encode(error, forKey: .error) } } } public enum IPCQuery: String, Sendable, Codable, CaseIterable { case windows, workspaces, spaces, displays, config, setups } public enum IPCTopic: String, Sendable, Codable, CaseIterable { case focus, layout, workspace, window } public struct IPCEvent: Sendable, Equatable, Codable { // pi-lens-ignore: identifier_name public var v: Int public var topic: IPCTopic public var data: JSONValue // pi-lens-ignore: identifier_name public init(topic: IPCTopic, data: JSONValue, v: Int = IPCProtocol.version) { self.v = v self.topic = topic self.data = data } } public protocol IPCHandler: Sendable { func query(_ query: IPCQuery) async throws -> JSONValue func run(command: String, args: [String]) async throws -> JSONValue func reloadConfig() async throws -> JSONValue func why(window: UInt32) async throws -> JSONValue func diagnostics() async throws -> IPCDiagnostics func responseDidSend(request: IPCRequest, response: IPCResponse) async } extension IPCHandler { public func responseDidSend(request: IPCRequest, response: IPCResponse) async {} public func diagnostics() async throws -> IPCDiagnostics { throw IPCError( code: "unsupported_command", message: String(localized: "Diagnostics are not supported by this server.", bundle: .module)) } public func why(window: UInt32) async throws -> JSONValue { throw IPCError( code: "unsupported_command", message: String(localized: "Window explanations are not supported by this server.", bundle: .module)) } } public enum IPCCodec { public static func encode(_ message: Message) throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] var data = try encoder.encode(message) guard data.count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } data.append(0x0A) return data } public static func decode(_ type: Message.Type, from data: Data) throws -> Message { let payload = data.last == 0x0A ? data.dropLast() : data[...] guard payload.count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } return try JSONDecoder().decode(type, from: payload) } }