SPB Git

Repository Public MIT

GlassThemeCodec.swift 6.9 KB 163 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassThemes/GlassThemeCodec.swift8// Module           : SPGlassThemes9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassCore43import SPGlassTokens4445public enum GlassThemeError: Error, Equatable, Sendable, CustomStringConvertible {46    case tooLarge(bytes: Int, limit: Int)47    case notAnObject48    case tooDeep(limit: Int)49    case unsupportedSchema(Int)50    case malformed(String)51    case invalid([String])5253    public var description: String {54        switch self {55        case .tooLarge(let bytes, let limit): "The theme file is \(bytes) bytes; the limit is \(limit)."56        case .notAnObject: "The theme file is not a JSON object."57        case .tooDeep(let limit): "The theme file nests more than \(limit) levels."58        case .unsupportedSchema(let version): "Schema version \(version) is newer than this version of GlassKit (\(GlassKitInfo.schemaVersion))."59        case .malformed(let detail): "The theme file cannot be read: \(detail)"60        case .invalid(let messages): "The theme is invalid: " + messages.joined(separator: " ")61        }62    }63}6465/// Reads and writes theme files. Input is bounded, migrated to the current schema and validated.66public enum GlassThemeCodec {67    public static let maximumBytes = 256 * 102468    public static let maximumDepth = 66970    /// Decodes a theme from JSON. Older schema versions are migrated; a newer version is refused.71    public static func decode(_ data: Data) throws(GlassThemeError) -> GlassTheme {72        guard data.count <= maximumBytes else {73            throw .tooLarge(bytes: data.count, limit: maximumBytes)74        }75        let object: Any76        do {77            object = try JSONSerialization.jsonObject(with: data)78        } catch {79            throw .malformed("it is not valid JSON.")80        }81        guard var dictionary = object as? [String: Any] else { throw .notAnObject }82        guard depth(of: dictionary) <= maximumDepth else { throw .tooDeep(limit: maximumDepth) }8384        dictionary = try migrate(dictionary)8586        let theme: GlassTheme87        do {88            let migrated = try JSONSerialization.data(withJSONObject: dictionary)89            theme = try JSONDecoder().decode(GlassTheme.self, from: migrated)90        } catch let error as DecodingError {91            throw .malformed(describe(error))92        } catch {93            throw .malformed("unexpected structure.")94        }95        let errors = GlassThemeValidator.validate(theme).filter { $0.severity == .error }96        guard errors.isEmpty else { throw .invalid(errors.map(\.message)) }97        return theme98    }99100    /// Encodes a theme as stable, human-readable JSON (sorted keys, two-space indentation).101    public static func encode(_ theme: GlassTheme) throws(GlassThemeError) -> Data {102        let encoder = JSONEncoder()103        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]104        do {105            return try encoder.encode(theme)106        } catch {107            throw .malformed("the theme could not be encoded.")108        }109    }110111    /// Brings a decoded JSON object to the current schema.112    ///113    /// Version 0 (files written before the schema was versioned) stored a single `colors` object, used for114    /// both appearances, and a `cornerRadius` number.115    static func migrate(_ input: [String: Any]) throws(GlassThemeError) -> [String: Any] {116        var dictionary = input117        let version: Int118        switch dictionary["schemaVersion"] {119        case nil: version = dictionary["colors"] != nil ? 0 : GlassKitInfo.schemaVersion120        case let number as Int: version = number121        default: throw .malformed("schemaVersion is not an integer.")122        }123        guard version <= GlassKitInfo.schemaVersion else { throw .unsupportedSchema(version) }124        guard version >= 0 else { throw .malformed("schemaVersion is negative.") }125126        if version == 0 {127            if let colors = dictionary.removeValue(forKey: "colors") {128                if dictionary["light"] == nil { dictionary["light"] = colors }129                if dictionary["dark"] == nil { dictionary["dark"] = colors }130            }131            if let radius = dictionary.removeValue(forKey: "cornerRadius") as? Double, dictionary["radii"] == nil {132                dictionary["radii"] = ["small": radius / 2, "medium": radius, "large": radius * 1.5, "extraLarge": radius * 2]133            }134        }135        dictionary["schemaVersion"] = GlassKitInfo.schemaVersion136        return dictionary137    }138139    private static func depth(of value: Any) -> Int {140        if let dictionary = value as? [String: Any] {141            return 1 + (dictionary.values.map(depth(of:)).max() ?? 0)142        }143        if let array = value as? [Any] {144            return 1 + (array.map(depth(of:)).max() ?? 0)145        }146        return 0147    }148149    private static func describe(_ error: DecodingError) -> String {150        func path(_ context: DecodingError.Context) -> String {151            let keys = context.codingPath.map(\.stringValue).joined(separator: ".")152            return keys.isEmpty ? "root" : keys153        }154        switch error {155        case .keyNotFound(let key, _): return "missing field \"\(key.stringValue)\"."156        case .typeMismatch(_, let context): return "wrong type at \(path(context))."157        case .valueNotFound(_, let context): return "missing value at \(path(context))."158        case .dataCorrupted(let context): return "\(path(context)): \(context.debugDescription)"159        @unknown default: return "unexpected structure."160        }161    }162}163
Files main
Menu

Theme