SPB Git

Repository Public

JSONValue.swift 8.7 KB 203 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteModels/JSONValue.swift10// Module           : ClaudeRemoteModels11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation8990/// A lossless JSON value, used for the open-ended fields of the API (`Project.settings`,91/// `UserSettings.layout`, `AuditEvent.detail`, `APIError.details`).92public enum JSONValue: Hashable, Sendable, Codable {93    case null94    case bool(Bool)95    case number(Double)96    case string(String)97    case array([JSONValue])98    case object([String: JSONValue])99100    public init(from decoder: Decoder) throws {101        let c = try decoder.singleValueContainer()102        if c.decodeNil() { self = .null }103        else if let v = try? c.decode(Bool.self) { self = .bool(v) }104        else if let v = try? c.decode(Double.self) { self = .number(v) }105        else if let v = try? c.decode(String.self) { self = .string(v) }106        else if let v = try? c.decode([JSONValue].self) { self = .array(v) }107        else { self = .object(try c.decode([String: JSONValue].self)) }108    }109110    public func encode(to encoder: Encoder) throws {111        var c = encoder.singleValueContainer()112        switch self {113        case .null: try c.encodeNil()114        case .bool(let v): try c.encode(v)115        case .number(let v):116            if v.rounded() == v, abs(v) < 9e15 { try c.encode(Int64(v)) } else { try c.encode(v) }117        case .string(let v): try c.encode(v)118        case .array(let v): try c.encode(v)119        case .object(let v): try c.encode(v)120        }121    }122123    public var stringValue: String? { if case .string(let v) = self { v } else { nil } }124    public var numberValue: Double? { if case .number(let v) = self { v } else { nil } }125    public var intValue: Int? { numberValue.flatMap { Int(exactly: $0.rounded()) } }126    public var boolValue: Bool? { if case .bool(let v) = self { v } else { nil } }127    public var arrayValue: [JSONValue]? { if case .array(let v) = self { v } else { nil } }128    public var objectValue: [String: JSONValue]? { if case .object(let v) = self { v } else { nil } }129    public subscript(key: String) -> JSONValue? { objectValue?[key] }130}131132extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral,133    ExpressibleByFloatLiteral, ExpressibleByNilLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {134    public init(stringLiteral value: String) { self = .string(value) }135    public init(booleanLiteral value: Bool) { self = .bool(value) }136    public init(integerLiteral value: Int) { self = .number(Double(value)) }137    public init(floatLiteral value: Double) { self = .number(value) }138    public init(nilLiteral: ()) { self = .null }139    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }140    public init(dictionaryLiteral elements: (String, JSONValue)...) {141        self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last }))142    }143}144145/// JSON coders of the API: ISO-8601 timestamps (with or without fractional seconds) as `Date`.146public enum CRJSON {147    public static func decoder() -> JSONDecoder {148        let d = JSONDecoder()149        d.dateDecodingStrategy = .custom { decoder in150            let raw = try decoder.singleValueContainer().decode(String.self)151            guard let date = parseDate(raw) else {152                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "not an ISO-8601 timestamp"))153            }154            return date155        }156        return d157    }158159    public static func encoder() -> JSONEncoder {160        let e = JSONEncoder()161        e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]162        e.dateEncodingStrategy = .custom { date, encoder in163            var c = encoder.singleValueContainer()164            try c.encode(formatDate(date))165        }166        return e167    }168169    public static func parseDate(_ raw: String) -> Date? {170        if let d = try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(raw) { return d }171        return try? Date.ISO8601FormatStyle().parse(raw)172    }173174    /// Same shape as JavaScript's `toISOString()` (`2026-11-20T02:25:00.000Z`).175    public static func formatDate(_ date: Date) -> String {176        date.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true))177    }178179    public static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) throws -> T {180        try decoder().decode(type, from: data)181    }182183    public static func decode<T: Decodable>(_ type: T.Type = T.self, from json: String) throws -> T {184        try decoder().decode(type, from: Data(json.utf8))185    }186187    public static func encode<T: Encodable>(_ value: T) throws -> Data { try encoder().encode(value) }188}189190/// Base64url without padding (WebAuthn, refresh challenges).191public enum Base64URL {192    public static func encode(_ data: Data) -> String {193        data.base64EncodedString().replacingOccurrences(of: "+", with: "-")194            .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")195    }196197    public static func decode(_ string: String) -> Data? {198        var s = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")199        while s.count % 4 != 0 { s.append("=") }200        return Data(base64Encoded: s)201    }202}203
Files main
Menu

Theme