SPB Git

Repository Public

ThemeCodec.swift 6.9 KB 168 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/ThemeEngine/ThemeCodec.swift10// Description      : Validated, versioned JSON import/export of themes. Imports11//                    are size-bounded, normalised, never carry a photo path or12//                    a secret, and can never replace a built-in theme.13// Module           : ThemeEngine14// Repository       : https://git.spboucher.ai/sp-keyboard15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192public enum ThemeCodecError: Error, Equatable, Sendable {93    case tooLarge94    case notJSON95    case wrongFormat96    case unsupportedVersion(Int)97    case malformed(String)98}99100public enum ThemeCodec {101    /// Marker of the exchange envelope.102    public static let format = "sp-keyboard-theme"103    public static let maxImportBytes = 64 * 1024104105    struct Envelope: Codable {106        var format: String107        var schemaVersion: Int108        var theme: Theme109    }110111    private struct Probe: Decodable {112        var format: String?113        var schemaVersion: Int?114    }115116    public static func export(_ theme: Theme) throws -> Data {117        var exported = theme.normalized()118        exported.backgroundImage = nil // photos stay on the device119        let encoder = JSONEncoder()120        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]121        return try encoder.encode(Envelope(format: format, schemaVersion: Theme.currentSchemaVersion, theme: exported))122    }123124    /// Decodes an exchanged theme. The result always has a fresh `custom-…` identifier.125    public static func `import`(_ data: Data, newID: () -> String = { "custom-" + UUID().uuidString.lowercased() }) throws -> Theme {126        guard data.count <= maxImportBytes else { throw ThemeCodecError.tooLarge }127        let decoder = JSONDecoder()128        guard let probe = try? decoder.decode(Probe.self, from: data) else { throw ThemeCodecError.notJSON }129        guard probe.format == format, let version = probe.schemaVersion else { throw ThemeCodecError.wrongFormat }130        guard (1...Theme.currentSchemaVersion).contains(version) else { throw ThemeCodecError.unsupportedVersion(version) }131        let envelope: Envelope132        do {133            envelope = try decoder.decode(Envelope.self, from: try migrate(data, from: version))134        } catch let error as DecodingError {135            throw ThemeCodecError.malformed(Self.describe(error))136        }137        var theme = envelope.theme138        theme.backgroundImage = nil139        theme.id = newID()140        return theme.normalized()141    }142143    /// Schema upgrades. Version 1 is the first one; the hook exists so a later version has one place to grow.144    static func migrate(_ data: Data, from version: Int) throws -> Data {145        data146    }147148    /// Decodes a stored theme (settings blob). Returns `nil` instead of throwing: callers fall back to a built-in.149    public static func decodeStored(_ data: Data?) -> Theme? {150        guard let data, data.count <= maxImportBytes * 2, let theme = try? JSONDecoder().decode(Theme.self, from: data),151              theme.schemaVersion <= Theme.currentSchemaVersion else { return nil }152        return theme.normalized()153    }154155    public static func encodeStored(_ theme: Theme) -> Data? {156        try? JSONEncoder().encode(theme.normalized())157    }158159    private static func describe(_ error: DecodingError) -> String {160        switch error {161        case .keyNotFound(let key, _): "missing field \(key.stringValue)"162        case .typeMismatch(_, let context), .valueNotFound(_, let context), .dataCorrupted(let context):163            "invalid value at \(context.codingPath.map(\.stringValue).joined(separator: "."))"164        @unknown default: "invalid theme"165        }166    }167}168
Files main
Menu

Theme