Repository Public
1// Drives the TypeScript client engine in a Node subprocess (Tests/Tools/ts-device.ts), JSON lines over stdin/stdout.2import Foundation3import XCTest4@testable import SharedVaultKit56struct TSError: Error, CustomStringConvertible {7 let message: String, code: String?, status: Int?8 var description: String { "TS helper error: \(message) [\(code ?? "-") \(status.map(String.init) ?? "-")]" }9}1011final class TSHelper: @unchecked Sendable {12 static let shared = TSHelper()13 private let lock = NSLock()14 private var process: Process?15 private var input: FileHandle?16 private var output: FileHandle?17 private var buffer = Data()18 private var nextId = 01920 private func ensureStarted() throws {21 if let p = process, p.isRunning { return }22 let p = Process()23 p.executableURL = URL(fileURLWithPath: "/usr/bin/env")24 p.arguments = ["node", "--import", "tsx", "apple/SharedVaultKit/Tests/Tools/ts-device.ts"]25 p.currentDirectoryURL = TestEnv.repoRoot26 p.environment = TestEnv.environment.merging(["SPV_TEST_PORT": String(TestEnv.port), "SPV_TEST_DB": TestEnv.databaseURL]) { $1 }27 let inp = Pipe(), out = Pipe()28 p.standardInput = inp; p.standardOutput = out; p.standardError = FileHandle.nullDevice29 try p.run()30 process = p; input = inp.fileHandleForWriting; output = out.fileHandleForReading; buffer = Data()31 }3233 private func readLine() throws -> Data {34 while true {35 if let nl = buffer.firstIndex(of: 0x0a) {36 let line = Data(buffer[buffer.startIndex..<nl])37 buffer = Data(buffer[(nl + 1)...])38 return line39 }40 guard let chunk = output?.availableData, !chunk.isEmpty else { throw ShellError(description: "the TypeScript helper exited") }41 buffer.append(chunk)42 }43 }4445 private func callSync(_ cmd: String, _ args: JSONValue) throws -> JSONValue {46 lock.lock(); defer { lock.unlock() }47 try ensureStarted()48 nextId += 149 let msg: JSONValue = ["id": .number(Double(nextId)), "cmd": .string(cmd), "args": args]50 try input?.write(contentsOf: msg.serialized() + Data([0x0a]))51 let reply = try JSONValue.parse(try readLine())52 guard reply["ok"] == .bool(true) else {53 throw TSError(message: reply["error"]?["message"]?.stringValue ?? "unknown", code: reply["error"]?["code"]?.stringValue, status: reply["error"]?["status"]?.intValue)54 }55 return reply["result"] ?? .null56 }5758 /// Sends one command and waits for its answer (commands are strictly sequential).59 @discardableResult60 func call(_ cmd: String, _ args: JSONValue = .object(JSONObject())) async throws -> JSONValue {61 try await withCheckedThrowingContinuation { c in62 DispatchQueue.global().async {63 do { c.resume(returning: try self.callSync(cmd, args)) } catch { c.resume(throwing: error) }64 }65 }66 }6768 func stop() {69 lock.lock(); defer { lock.unlock() }70 try? input?.close() // stdin EOF: the helper closes its connections and exits by itself71 if let p = process {72 let deadline = Date().addingTimeInterval(5)73 while p.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.05) }74 if p.isRunning { p.terminate() }75 }76 process = nil; input = nil; output = nil77 }78}79