Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteTestSupport/Transport/StubURLProtocol.swift10// Module : ClaudeRemoteTestSupport11// 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 ClaudeRemoteAPI89import ClaudeRemoteModels90import Foundation9192/// A recorded HTTP request (body captured even when it was streamed).93public struct RecordedRequest: Sendable {94 public var method: String95 public var url: URL96 public var path: String97 public var query: [String: String]98 public var headers: [String: String]99 public var body: Data100101 public func header(_ name: String) -> String? {102 headers.first { $0.key.lowercased() == name.lowercased() }?.value103 }104 public var bearer: String? { header("Authorization").flatMap { $0.hasPrefix("Bearer ") ? String($0.dropFirst(7)) : nil } }105 public var json: JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: body) }106}107108public struct StubResponse: Sendable {109 public var status: Int110 public var headers: [String: String]111 public var body: Data112 /// Simulated latency.113 public var delay: TimeInterval114 /// When set, the request fails at transport level with this `URLError` code.115 public var failure: URLError.Code?116117 public init(status: Int = 200, headers: [String: String] = [:], body: Data = Data(), delay: TimeInterval = 0, failure: URLError.Code? = nil) {118 self.status = status119 self.headers = headers120 self.body = body121 self.delay = delay122 self.failure = failure123 }124125 public static func json(_ json: String, status: Int = 200, headers: [String: String] = [:]) -> StubResponse {126 var h = headers127 h["Content-Type"] = "application/json; charset=utf-8"128 return StubResponse(status: status, headers: h, body: Data(json.utf8))129 }130131 public static func encoding<T: Encodable>(_ value: T, status: Int = 200) -> StubResponse {132 .json(String(decoding: (try? CRJSON.encode(value)) ?? Data(), as: UTF8.self), status: status)133 }134135 /// The server's error envelope.136 public static func error(_ status: Int, _ code: String, _ message: String = "error", details: String? = nil, headers: [String: String] = [:]) -> StubResponse {137 .json(#"{"error":{"code":"\#(code)","message":"\#(message)"\#(details.map { #","details":\#($0)"# } ?? "")}}"#, status: status, headers: headers)138 }139140 public static func bytes(_ data: Data, headers: [String: String] = [:]) -> StubResponse {141 var h = headers142 h["Content-Type"] = "application/octet-stream"143 return StubResponse(status: 200, headers: h, body: data)144 }145146 public static func transportFailure(_ code: URLError.Code = .notConnectedToInternet) -> StubResponse {147 StubResponse(failure: code)148 }149}150151/// A scripted HTTP server for one test. Create one per test: each has its own URLSession152/// configuration, so tests can run in parallel.153///154/// let server = StubServer()155/// server.on("GET", "/api/v1/sessions") { _ in .json("[]") }156/// let client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration)157public final class StubServer: @unchecked Sendable {158 public typealias Handler = @Sendable (RecordedRequest) -> StubResponse159160 private let lock = NSLock()161 private var routes: [(method: String, path: String, handler: Handler)] = []162 private var _requests: [RecordedRequest] = []163 private var fallback: Handler = { request in .error(404, "not_found", "no stub for \(request.method) \(request.path)") }164 public let id = UUID().uuidString165 public let baseURL: URL166167 public init(baseURL: URL = URL(string: "https://stub.test")!) {168 self.baseURL = baseURL169 StubURLProtocol.register(self)170 }171172 deinit { StubURLProtocol.unregister(id) }173174 /// URLSession configuration routed to this server (pass it to `APIClient`).175 public var configuration: URLSessionConfiguration {176 let c = URLSessionConfiguration.crAPI177 c.protocolClasses = [StubURLProtocol.self]178 c.httpAdditionalHeaders = [StubURLProtocol.serverHeader: id]179 return c180 }181182 /// Registers a handler for an exact method + path (`/api/v1/...`). The last registration wins.183 public func on(_ method: String, _ path: String, _ handler: @escaping Handler) {184 lock.withLock { routes.insert((method.uppercased(), path, handler), at: 0) }185 }186187 public func onUnmatched(_ handler: @escaping Handler) { lock.withLock { fallback = handler } }188189 public var requests: [RecordedRequest] { lock.withLock { _requests } }190 public func requests(_ method: String, _ path: String) -> [RecordedRequest] {191 requests.filter { $0.method == method.uppercased() && $0.path == path }192 }193 public func count(_ method: String, _ path: String) -> Int { requests(method, path).count }194195 fileprivate func respond(to request: RecordedRequest) -> StubResponse {196 let handler: Handler = lock.withLock {197 _requests.append(request)198 return routes.first { $0.method == request.method && $0.path == request.path }?.handler ?? fallback199 }200 return handler(request)201 }202}203204/// URLProtocol dispatching to the `StubServer` named by a private header.205public final class StubURLProtocol: URLProtocol, @unchecked Sendable {206 static let serverHeader = "X-Stub-Server"207 private static let lock = NSLock()208 nonisolated(unsafe) private static var servers: [String: StubServerBox] = [:]209 private struct StubServerBox { weak var server: StubServer? }210 private var cancelled = false211212 static func register(_ server: StubServer) { lock.withLock { servers[server.id] = StubServerBox(server: server) } }213 static func unregister(_ id: String) { lock.withLock { _ = servers.removeValue(forKey: id) } }214215 override public class func canInit(with request: URLRequest) -> Bool { request.value(forHTTPHeaderField: serverHeader) != nil }216 override public class func canonicalRequest(for request: URLRequest) -> URLRequest { request }217218 override public func startLoading() {219 let request = self.request220 guard let id = request.value(forHTTPHeaderField: Self.serverHeader),221 let server = Self.lock.withLock({ Self.servers[id]?.server }), let url = request.url else {222 client?.urlProtocol(self, didFailWithError: URLError(.cannotFindHost))223 return224 }225 var body = request.httpBody ?? Data()226 if let stream = request.httpBodyStream {227 stream.open()228 var buffer = [UInt8](repeating: 0, count: 64 * 1024)229 while stream.hasBytesAvailable {230 let n = stream.read(&buffer, maxLength: buffer.count)231 if n <= 0 { break }232 body.append(buffer, count: n)233 }234 stream.close()235 }236 let components = URLComponents(url: url, resolvingAgainstBaseURL: false)237 var headers = request.allHTTPHeaderFields ?? [:]238 headers.removeValue(forKey: Self.serverHeader)239 let recorded = RecordedRequest(240 method: (request.httpMethod ?? "GET").uppercased(), url: url, path: components?.path ?? url.path,241 query: Dictionary((components?.queryItems ?? []).map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { _, last in last }),242 headers: headers, body: body)243 let response = server.respond(to: recorded)244 let deliver: @Sendable () -> Void = { [weak self] in245 guard let self, !self.cancelled else { return }246 if let failure = response.failure {247 self.client?.urlProtocol(self, didFailWithError: URLError(failure))248 return249 }250 let http = HTTPURLResponse(url: url, statusCode: response.status, httpVersion: "HTTP/1.1", headerFields: response.headers)!251 self.client?.urlProtocol(self, didReceive: http, cacheStoragePolicy: .notAllowed)252 self.client?.urlProtocol(self, didLoad: response.body)253 self.client?.urlProtocolDidFinishLoading(self)254 }255 if response.delay > 0 {256 DispatchQueue.global().asyncAfter(deadline: .now() + response.delay, execute: deliver)257 } else {258 deliver()259 }260 }261262 override public func stopLoading() { cancelled = true }263}264265extension ClientInfo {266 public static let test = ClientInfo(platform: .macos, appVersion: "1.0-test")267}268