From 1c96bef97a007a342aa803ce42b04ee3d46d8805 Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:00:26 +0900 Subject: [PATCH] Move preview definition discovery and product staging out of NativePreviewTool Co-Authored-By: Claude Opus 5.5 --- .../NativePreviewBuild.swift | 4 +- .../NativePreviewDefinitions.swift | 290 +++++ .../NativePreviewProductSignature.swift | 4 +- .../NativePreviewStaging.swift | 794 ++++++++++++ .../NativePreviewTool.swift | 1142 +---------------- .../NativePreviewDiscoveryTests.swift | 16 +- .../NativePreviewLocationTests.swift | 4 +- .../NativePreviewToolTests.swift | 138 +- 8 files changed, 1204 insertions(+), 1188 deletions(-) create mode 100644 Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift create mode 100644 Sources/XcodeMCPNativeRuntime/NativePreviewStaging.swift diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift index 9c67067b..3613f5ad 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift @@ -664,7 +664,7 @@ final class NativePreviewBuild { var result = records.map(\.target) var previewRoots: [Target] = [] if let platform { - let selection = try NativePreviewTool.selectTarget(result, source: source, platform: platform) + let selection = try NativePreviewStaging.selectTarget(result, source: source, platform: platform) if let index = result.firstIndex(where: { $0.outputURL == selection.host.outputURL && $0.sdkRoot == selection.host.sdkRoot && $0.sdkVariant == selection.host.sdkVariant && $0.architecture == selection.host.architecture @@ -681,7 +681,7 @@ final class NativePreviewBuild { result[index].compileCommandLine = try await compileCommandLine(for: records[index], priorBuild: priorBuild, workspace: workspace, source: source, image: image) } - if let hostOutput = selection.host.outputURL, NativePreviewTool.productBundle(containing: hostOutput) == nil { + if let hostOutput = selection.host.outputURL, NativePreviewStaging.productBundle(containing: hostOutput) == nil { let sourceRecord = (buildable: records[index].buildable, native: records[index].native, target: result[index]) let dependencies = try await dependencies(for: sourceRecord, records: records, buildables: buildables, image: image, priorBuild: priorBuild, workspace: workspace, scheme: scheme, destination: destination) diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift new file mode 100644 index 00000000..35795839 --- /dev/null +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift @@ -0,0 +1,290 @@ +import ABIBridge +import Foundation + +/// Reads preview definitions from a source file and builds the specifications that native preview services expect. +@MainActor +struct NativePreviewDefinitions { + let installation: NativeXcodeInstallation + + func sourceURL(_ path: String, workspace: AnyObject) async throws -> URL { + do { + let action = try await ABIRuntime.shared.resolve( + .swift(.type("PreviewsXcode.AgenticAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) + let resolve = try await action.resolve(.swift(.staticMethod( + "projectRelativeSourceFileURL(at: Swift.String, in: __C.IDEWorkspace) async throws -> Foundation.URL", + as: (@concurrent (String, AnyObject) async throws -> PreviewURL).self))) + return try unsafe await resolve.unsafeInvoke(path, workspace).value + } catch is ABIResolutionError { + return try await legacySourceURL(path, workspace: workspace) + } + } + + private func legacySourceURL(_ path: String, workspace: AnyObject) async throws -> URL { + let type = try await ABIRuntime.shared.resolve( + .swift(.type("PreviewsXcode.RenderPreviewAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) + let resolve = try await type.resolve( + .swift( + .staticMethod( + "(resolveSourceFileURL in _FEA7E13ECD12FBA8521281D73C9764CE)(at: Swift.String, in: __C.IDEWorkspace) async throws -> Foundation.URL", + as: (@concurrent (String, AnyObject) async throws -> PreviewURL).self))) + return try unsafe await resolve.unsafeInvoke(path, workspace).value + } + + struct Definition { + let line: Int + let column: Int + let displayName: String + let providerPath: NativeSwiftValue? + let registry: NativeSwiftValue? + let source: NativePreviewBuild.Source + } + + func definition(in source: URL, at index: Int) async throws -> Definition { + let runtime = ABIRuntime.shared + let action = try await runtime.resolve( + .swift(.type("PreviewsXcode.RenderPreviewAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) + let unit = try await runtime.resolve( + .swift(.type("PreviewsPipeline.PreviewTranslationUnit")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let parsed: NativeSwiftValue + do { + let parse = try await action.resolve(.swift(.staticMethod( + "parseTranslationUnit(sourceFileURL: Foundation.URL) async throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.RenderPreviewType])", + as: (@concurrent (PreviewURL) async throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) + parsed = try unsafe await parse.unsafeInvoke(PreviewURL(value: source)) + } catch is ABIResolutionError { + do { + let parse = try await action.resolve(.swift(.staticMethod( + "parseTranslationUnit(sourceFileURL: Foundation.URL) throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.RenderPreviewType])", + as: ((PreviewURL) throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) + parsed = try unsafe parse.unsafeInvoke(PreviewURL(value: source)) + } catch is ABIResolutionError { + let parse = try await action.resolve(.swift(.staticMethod( + "(parseTranslationUnit in _FEA7E13ECD12FBA8521281D73C9764CE)(sourceFileURL: Foundation.URL) throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.(RenderPreviewType in _FEA7E13ECD12FBA8521281D73C9764CE)])", + as: ((PreviewURL) throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) + parsed = try unsafe parse.unsafeInvoke(PreviewURL(value: source)) + } + } + let translationUnit = try parsed.copyTupleElement(at: 0) + let array = try parsed.copyTupleElement(at: 1) + let previews = try array.withCopy { value -> [Any] in + guard let values = value as? [Any] else { + throw NativeRuntimeError.unsupportedContract("Native preview definitions are not an array") + } + return values + } + guard previews.indices.contains(index) else { + throw NativeRuntimeError.invalidRequest("Preview index \(index) is outside the \(previews.count) definitions in \(source.lastPathComponent)") + } + func own(_ value: T) async throws -> NativeSwiftValue { + let identity = try await runtime.resolve( + .swift(.function("XcodeMCPNativeRuntime.nativePreviewValue(A) -> A", as: ((T) -> NativeSwiftValue).self, genericArguments: [.type(T.self)]))) + return try unsafe identity.unsafeInvoke(value) + } + let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) + let locationType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceLocation")), in: model) + let boundType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceLocation.Bound")), in: model) + let pathType = try await runtime.resolve(.swift(.type("PreviewsModel.MangleableTypePath")), in: model) + let syntaxType = try await runtime.resolve(.swift(.type("PreviewsModel.SyntaxLocation")), in: model) + let contents = try String(contentsOf: source, encoding: .utf8) + var definitions: [Definition] = [] + for value in previews { + let definition = try await _openExistential(value, do: own) + let record: NativeSwiftValue + let location: NativeSwiftValue + let displayName: String + let providerPath: NativeSwiftValue? + let registryRecord: NativeSwiftValue? + if let provider = try await definition.copyEnumPayload(forCase: "previewProvider") { + record = provider + registryRecord = nil + let getPath = try await provider.type.resolve( + .swift( + .getter( + "path", as: (() -> NativeSwiftValue).self, valueABIs: [pathType: .opaque(named: pathType.name)], + receiverABI: .opaque(named: provider.type.name)))) + providerPath = try unsafe getPath.unsafeInvoke(on: provider) + let getSyntax = try await provider.type.resolve( + .swift( + .getter( + "location", as: (() -> NativeSwiftValue).self, valueABIs: [syntaxType: .opaque(named: syntaxType.name)], + receiverABI: .opaque(named: provider.type.name)))) + let syntax = try unsafe getSyntax.unsafeInvoke(on: provider) + let getLocation = try await syntax.type.resolve( + .swift( + .getter( + "locationExcludingTrivia", as: (() -> NativeSwiftValue).self, valueABIs: [locationType: .opaque(named: locationType.name)], + receiverABI: .opaque(named: syntax.type.name)))) + location = try unsafe getLocation.unsafeInvoke(on: syntax) + let getName = try await provider.type.resolve( + .swift(.getter("displayName", as: (() -> String).self, receiverABI: .opaque(named: provider.type.name)))) + displayName = try unsafe getName.unsafeInvoke(on: provider) + } else if let registry = try await definition.copyEnumPayload(forCase: "registryPreview") { + record = registry + registryRecord = registry + providerPath = nil + let getName = try await registry.type.resolve( + .swift( + .getter( + "(extension in PreviewsPipeline):PreviewsModel.RegistryDefinition.defaultDisplayName.getter : Swift.String", + as: (() -> String).self, receiverABI: .opaque(named: registry.type.name)))) + displayName = try unsafe getName.unsafeInvoke(on: registry) + let getLocation = try await registry.type.resolve( + .swift( + .getter( + "fullSourceLocation", as: (() -> NativeSwiftValue).self, valueABIs: [locationType: .opaque(named: locationType.name)], + receiverABI: .opaque(named: registry.type.name)))) + location = try unsafe getLocation.unsafeInvoke(on: registry) + } else { throw NativePipelineRequired() } + let getLine = try await record.type.resolve(.swift(.getter("lineNumber", as: (() -> Int).self, receiverABI: .opaque(named: record.type.name)))) + let line = try unsafe getLine.unsafeInvoke(on: record) + let getBound = try await location.type.resolve( + .swift( + .getter( + "lowerBound", as: (() -> NativeSwiftValue).self, valueABIs: [boundType: .opaque(named: boundType.name)], + receiverABI: .opaque(named: location.type.name)))) + let bound = try unsafe getBound.unsafeInvoke(on: location) + let getColumn = try await bound.type.resolve(.swift(.getter("column", as: (() -> Int).self, receiverABI: .opaque(named: bound.type.name)))) + let column = try unsafe getColumn.unsafeInvoke(on: bound) + definitions.append(Definition(line: line, column: try Self.registryColumn(in: contents, line: line, utf16Column: column), + displayName: displayName, providerPath: providerPath, registry: registryRecord, + source: .init(translationUnit: translationUnit, definition: definition))) + } + // The parser returns providers and registries in separate batches. The + // native tool selects definitions in source order, including mixed files. + return definitions.sorted { ($0.line, $0.column) < ($1.line, $1.column) }[index] + } + + func registrySpecification(registry: NativeSwiftValue, moduleName: String) async throws -> Data { + let runtime = ABIRuntime.shared + let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) + let messaging = ImageSelector.path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks")) + let optionalUUID = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(UUID.self)]))) + let getSidecar = try await registry.type.resolve( + .swift( + .getter( + "sidecarIdentifier.getter : Swift.Optional", as: (() -> NativeSwiftValue).self, + valueABIs: [optionalUUID: .opaque(named: optionalUUID.name)], receiverABI: .opaque(named: registry.type.name)))) + let sidecar = try unsafe getSidecar.unsafeInvoke(on: registry) + guard try await sidecar.copyEnumPayload(forCase: "some") == nil else { throw NativePipelineRequired() } + let idType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.RegistryID")), in: messaging) + let getID = try await registry.type.resolve( + .swift( + .getter( + "id.getter : PreviewsMessagingHost.RegistryID", as: (() -> NativeSwiftValue).self, valueABIs: [idType: .opaque(named: idType.name)], + receiverABI: .opaque(named: registry.type.name)))) + let id = try unsafe getID.unsafeInvoke(on: registry) + let moduleType = try await runtime.resolve(.swift(.type("PreviewsModel.Module")), in: model) + let initializeModule = try await moduleType.resolve( + .swift( + .initializer( + "init(name: Swift.String) -> PreviewsModel.Module", as: ((String) -> NativeSwiftValue).self, + valueABIs: [moduleType: .opaque(named: moduleType.name)]))) + let module = try unsafe initializeModule.unsafeInvoke(moduleName) + let locationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.RuntimeRegistryLocation")), in: messaging) + let locate = try await registry.type.resolve( + .swift( + .method( + "runtimeLocation(in: PreviewsModel.Module) -> PreviewsMessagingHost.RuntimeRegistryLocation", + as: ((NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [moduleType: .opaque(named: moduleType.name), locationType: .opaque(named: locationType.name)], + receiverABI: .opaque(named: registry.type.name)))) + let location = try unsafe locate.unsafeInvoke(on: registry, module) + let specificationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewSpecification")), in: messaging) + let makeSpecification = try await specificationType.resolve( + .swift( + .staticMethod( + "registryPreview(stableID: PreviewsMessagingHost.RegistryID, location: PreviewsMessagingHost.RuntimeRegistryLocation) -> PreviewsMessagingHost.PreviewSpecification", + as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [ + idType: .opaque(named: idType.name), locationType: .opaque(named: locationType.name), + specificationType: .opaque(named: specificationType.name), + ]))) + let specification = try unsafe makeSpecification.unsafeInvoke(id, location) + return try await previewSpecificationData(specification) + } + + func providerSpecification(name: String, description: NativeSwiftValue) async throws -> Data { + let runtime = ABIRuntime.shared + let messaging = ImageSelector.path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks")) + let providerType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.ProviderPayload")), in: messaging) + let makeProvider = try await providerType.resolve( + .swift( + .initializer( + "init(providerName: Swift.String) -> PreviewsMessagingHost.ProviderPayload", as: ((String) -> NativeSwiftValue).self, + valueABIs: [providerType: .opaque(named: providerType.name)]))) + let provider = try unsafe makeProvider.unsafeInvoke(name) + let getIndex = try await description.type.resolve( + .swift(.getter("index.getter : Swift.Int", as: (() -> Int).self, receiverABI: .opaque(named: description.type.name)))) + let index = try unsafe getIndex.unsafeInvoke(on: description) + let specificationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewSpecification")), in: messaging) + let makeSpecification = try await specificationType.resolve( + .swift( + .staticMethod( + "providerPreview(provider: PreviewsMessagingHost.ProviderPayload, indexInProvider: Swift.Int) -> PreviewsMessagingHost.PreviewSpecification", + as: ((NativeSwiftValue, Int) -> NativeSwiftValue).self, + valueABIs: [providerType: .opaque(named: providerType.name), specificationType: .opaque(named: specificationType.name)]))) + let specification = try unsafe makeSpecification.unsafeInvoke(provider, index) + return try await previewSpecificationData(specification) + } + + private func previewSpecificationData(_ specification: NativeSwiftValue) async throws -> Data { + let runtime = ABIRuntime.shared + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let propertyListType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.PropertyList")), in: foundation) + let encode = try await specification.type.resolve( + .swift( + .getter( + "propertyListValue.getter : PreviewsFoundationHost.PropertyList", as: (() -> NativeSwiftValue).self, + valueABIs: [propertyListType: .opaque(named: propertyListType.name)], receiverABI: .opaque(named: specification.type.name)))) + let propertyList = try unsafe encode.unsafeInvoke(on: specification) + let dictionaryType = try await runtime.resolve(.swift(.type("Swift.Dictionary", genericArguments: [.type(String.self), .type(Any.self)]))) + let serialize = try await propertyListType.resolve( + .swift( + .getter( + "serializableDictionary.getter : [Swift.String : Any]", as: (() -> NativeSwiftValue).self, valueABIs: [dictionaryType: .pointer], + receiverABI: .opaque(named: propertyListType.name)))) + let dictionary = try unsafe serialize.unsafeInvoke(on: propertyList) + return try dictionary.withCopy { value in + guard let dictionary = value as? [String: Any] else { + throw NativeRuntimeError.unsupportedContract("Native preview specification is not a property list dictionary") + } + return try PropertyListSerialization.data(fromPropertyList: dictionary, format: .binary, options: 0) + } + } + + func providerTypeName(path: NativeSwiftValue, moduleName: String) async throws -> String { + let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) + let type = try await ABIRuntime.shared.resolve(.swift(.type("PreviewsModel.Module")), in: model) + let initialize = try await type.resolve( + .swift( + .initializer( + "init(name: Swift.String) -> PreviewsModel.Module", as: ((String) -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) + let module = try unsafe initialize.unsafeInvoke(moduleName) + let mangle = try await path.type.resolve( + .swift( + .method( + "mangledName(in: PreviewsModel.Module) -> Swift.String", as: ((NativeSwiftValue) -> String).self, + valueABIs: [type: .opaque(named: type.name)], receiverABI: .opaque(named: path.type.name)))) + return try unsafe mangle.unsafeInvoke(on: path, module) + } + + static func registryColumn(in source: String, line: Int, utf16Column: Int) throws -> Int { + let lines = source.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) + guard line > 0, lines.indices.contains(line - 1), utf16Column >= 0 else { + throw NativeRuntimeError.invocation("The preview source changed while resolving its location") + } + let text = lines[line - 1] + // The native parser reports UTF-16 offsets; macro metadata reports + // one-based UTF-8 byte columns. Unicode prefixes must retain that mapping. + guard let position = text.utf16.index(text.utf16.startIndex, offsetBy: utf16Column, limitedBy: text.utf16.endIndex), + let index = String.Index(position, within: text) else { + throw NativeRuntimeError.invocation("The preview source changed while resolving its location") + } + return text[.. Selection { + let sourcePath = source.resolvingSymlinksInPath().path + guard targets.contains(where: { $0.sourceFiles.contains { $0.resolvingSymlinksInPath().path == sourcePath } }) else { + throw NativeRuntimeError.invalidRequest("The active scheme did not build \(source.path)") + } + let platformTargets = targets.filter { + NativePreviewPlatform(sdkRoot: $0.sdkRoot, sdkVariant: $0.sdkVariant) == platform + } + let sources = platformTargets.filter { + $0.architecture == "arm64" && $0.sourceFiles.contains { $0.resolvingSymlinksInPath().path == sourcePath } + } + guard !sources.isEmpty else { throw NativePipelineRequired() } + var selections: [Selection] = [] + for target in sources { + if let output = target.outputURL, productBundle(containing: output) != nil { + selections.append(Selection(source: target, host: target)) + continue + } + let objectPaths = Set(target.objectFiles.map { $0.resolvingSymlinksInPath().path }) + let sourceOutput = target.outputURL + let frameworkName = sourceOutput?.pathComponents.last(where: { $0.hasSuffix(".framework") }) + let hosts = try platformTargets.filter { candidate in + guard candidate.architecture == "arm64", + let output = candidate.outputURL, let app = productBundle(containing: output) else { return false } + if candidate.objectFiles.contains(where: { objectPaths.contains($0.resolvingSymlinksInPath().path) }) { + return true + } + guard let sourceOutput else { return false } + if try (["a", "o", "dylib"].contains(sourceOutput.pathExtension) + || (frameworkName != nil && NativePreviewBinary.isStaticArchive(at: sourceOutput))) + && candidate.linksProduct(at: sourceOutput) { return true } + guard frameworkName != nil || sourceOutput.pathExtension == "dylib" else { return false } + let rootLibrary = app.appendingPathComponent(sourceOutput.lastPathComponent) + if frameworkName == nil, FileManager.default.fileExists(atPath: rootLibrary.path), + try NativePreviewBinary.matches(sourceOutput, rootLibrary) { + return true + } + let frameworks = Bundle(url: app)?.privateFrameworksURL ?? app.appendingPathComponent("Frameworks", isDirectory: true) + guard FileManager.default.fileExists(atPath: frameworks.path) else { return false } + return try FileManager.default.subpathsOfDirectory(atPath: frameworks.path).contains { subpath in + let library = frameworks.appendingPathComponent(subpath) + guard library.lastPathComponent == sourceOutput.lastPathComponent, + frameworkName.map({ library.pathComponents.contains($0) }) ?? true else { return false } + return try NativePreviewBinary.matches(sourceOutput, library) + } + } + selections += hosts.map { Selection(source: target, host: $0) } + if hosts.isEmpty, let sourceOutput, + try NativePreviewBinary.isStaticLibrary(at: sourceOutput) + || (frameworkBundle(containing: sourceOutput) != nil && NativePreviewBinary.isDynamicLibrary(at: sourceOutput)) { + selections.append(Selection(source: target, host: target)) + } + } + var candidates = selections + let runnable = candidates.filter { $0.host.isRunnable } + if !runnable.isEmpty { candidates = runnable } + guard candidates.count == 1 else { throw NativePipelineRequired() } + return candidates[0] + } + + static func productBundle(containing output: URL) -> URL? { + var url = output.deletingLastPathComponent() + while url.path != "/" { + if ["app", "appex"].contains(url.pathExtension) { return url } + url.deleteLastPathComponent() + } + return nil + } + + static func frameworkBundle(containing output: URL) -> URL? { + var url = output.deletingLastPathComponent() + while url.path != "/" { + if url.pathExtension == "framework" { return url } + url.deleteLastPathComponent() + } + return nil + } + + static func containingApp(for extensionOutput: URL, targets: [NativePreviewBuild.Target]) throws -> URL? { + guard let product = productBundle(containing: extensionOutput), product.pathExtension == "appex" else { return nil } + let relativeBinary = String(extensionOutput.path.dropFirst(product.path.count + 1)) + let candidates = try targets.compactMap { target -> (app: URL, isRunnable: Bool)? in + guard target.architecture == "arm64", NativePreviewPlatform(sdkRoot: target.sdkRoot, sdkVariant: target.sdkVariant) != nil, + let output = target.outputURL, let app = productBundle(containing: output), + app.pathExtension == "app" else { return nil } + let embedded = (Bundle(url: app)?.builtInPlugInsURL ?? app.appendingPathComponent("PlugIns", isDirectory: true)) + .appendingPathComponent(product.lastPathComponent, isDirectory: true) + .appendingPathComponent(relativeBinary) + guard FileManager.default.fileExists(atPath: embedded.path), + try NativePreviewBinary.matches(extensionOutput, embedded) else { return nil } + return (app, target.isRunnable) + } + guard !candidates.isEmpty else { return nil } + let runnable = candidates.filter(\.isRunnable) + let matches = runnable.isEmpty ? candidates : runnable + guard matches.count == 1 else { throw NativePipelineRequired() } + return matches[0].app + } + + static func widgetExtensionIdentifier(_ product: URL) throws -> String? { + guard product.pathExtension == "appex" else { return nil } + let info = try bundleInfo(at: product) + guard (info["NSExtension"] as? [String: Any])?["NSExtensionPointIdentifier"] as? String == "com.apple.widgetkit-extension" else { + return nil + } + return info["CFBundleIdentifier"] as? String + } + + struct LinkedPreviewImage { + let url: URL + let searchPaths: [(framework: Bool, url: URL)] + let linkInputs: [URL] + } + + struct FrameworkDependencies { + struct Relocation { + let library: String + let name: String + let replacement: String + } + var products: [URL: String] = [:] + var relocations: [Relocation] = [] + var rootLibraries: [String] = [] + } + + static func frameworkDependencies(for roots: [NativePreviewBuild.Target], targets: [NativePreviewBuild.Target], + platform: NativePreviewPlatform, in products: URL, agentApp: URL? = nil, + sourceProduct: URL? = nil, linkedImages: [URL: LinkedPreviewImage] = [:], + environment: [String: String] = [:], nativeApp: URL? = nil) throws -> FrameworkDependencies { + typealias SearchPath = (framework: Bool, url: URL) + typealias Library = (output: URL, product: URL, identifier: String, dependencies: [String], rpaths: [String], target: NativePreviewBuild.Target?) + let rootOutputs = Set(roots.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) + func linkedImage(at output: URL) -> LinkedPreviewImage? { + linkedImages.values.first { $0.url.resolvingSymlinksInPath() == output.resolvingSymlinksInPath() } + } + let nativeImage = roots.compactMap { root in + root.outputURL.flatMap { linkedImages[$0.resolvingSymlinksInPath()]?.url } + }.first + func library(at output: URL, target: NativePreviewBuild.Target? = nil) throws -> Library? { + let output = output.resolvingSymlinksInPath() + var isDirectory: ObjCBool = false + guard unsafe FileManager.default.fileExists(atPath: output.path, isDirectory: &isDirectory), !isDirectory.boolValue, + let image = try NativePreviewBinary.dynamicLibrary(at: output) else { return nil } + let packageImage = nativeApp == nil && agentApp != nil && target?.isDynamicPackageProduct == true + && rootOutputs.contains(output) + let product = packageImage ? output : frameworkBundle(containing: output) ?? output + return (output, product, image.identifier, image.dependencies, image.rpaths, target) + } + func relativePath(from directory: URL, to item: URL) -> String { + let base = directory.standardizedFileURL.pathComponents + let target = item.standardizedFileURL.pathComponents + let shared = zip(base, target).prefix { $0.0 == $0.1 }.count + return (Array(repeating: "..", count: base.count - shared) + target.dropFirst(shared)).joined(separator: "/") + } + func runtimeURL(_ path: String, importer: URL) -> URL? { + if path == "@loader_path" { return importer.deletingLastPathComponent() } + if path.hasPrefix("@loader_path/") { + return importer.deletingLastPathComponent().appendingPathComponent(String(path.dropFirst("@loader_path/".count))) + } + if nativeApp != nil, let output = nativeImage, let host = productBundle(containing: output) { + let executable = platform.executableDirectory(in: host) + if path == "@executable_path" { return executable } + if path.hasPrefix("@executable_path/") { + return executable.appendingPathComponent(String(path.dropFirst("@executable_path/".count))) + } + } + return path.hasPrefix("/") ? URL(filePath: path) : nil + } + func nativePath(_ url: URL) throws -> String? { + guard let nativeApp else { return nil } + var relationship: FileManager.URLRelationship = .other + try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: nativeApp, toItemAt: url) + guard relationship == .contains else { return nil } + return url.resolvingSymlinksInPath().pathComponents + .dropFirst(nativeApp.resolvingSymlinksInPath().pathComponents.count).joined(separator: "/") + } + // Native-preloaded runtimes must keep their original image identity when their clients are relocated. + let preloaded = Set(environment["DYLD_INSERT_LIBRARIES", default: ""].split(separator: ":") + .filter { $0.hasPrefix("/") }.map { URL(filePath: String($0)).resolvingSymlinksInPath() }) + let libraries = try targets.compactMap { target -> Library? in + guard target.architecture == "arm64", + NativePreviewPlatform(sdkRoot: target.sdkRoot, sdkVariant: target.sdkVariant) == platform, + let output = target.outputURL, productBundle(containing: output) == nil else { return nil } + return try library(at: linkedImages[output.resolvingSymlinksInPath()]?.url ?? output, target: target) + } + let rootImages = try roots.compactMap { root -> Library? in + guard let output = root.outputURL?.resolvingSymlinksInPath() else { return nil } + return try library(at: linkedImages[output]?.url ?? output, target: root) + } + var pending = try rootImages.map { root in + let executable = nativeApp == nil ? nil : productBundle(containing: root.output).flatMap { Bundle(url: $0)?.executableURL } + let executablePaths = try executable.flatMap { executable in + try NativePreviewBinary.file(at: executable)?.rpaths.compactMap { runtimeURL($0, importer: executable) } + } ?? [] + return (library: root, inheritedPaths: executablePaths, inheritedLinkPaths: [SearchPath]()) + } + var visited = Set(rootImages.map { $0.output }) + var result = FrameworkDependencies() + func stagedPath(_ library: Library) throws -> String { + if let path = try nativePath(library.output) { return path } + if linkedImage(at: library.output) != nil { + return relativePath(from: products, to: library.output) + } + let product = library.product.resolvingSymlinksInPath() + let relativeProduct: String + if product == sourceProduct?.resolvingSymlinksInPath() { + relativeProduct = product.lastPathComponent + } else if let path = result.products[product] { + relativeProduct = path + } else { + if nativeApp == nil, let agentApp, library.target?.isDynamicPackageProduct == true, + rootOutputs.contains(library.output) { + // Native package JIT images keep their dynamic boundary while their classes belong to the agent bundle. + let image = platform.executableDirectory(in: agentApp) + .appendingPathComponent("XcodeMCPPreviewPackage-\(UUID().uuidString).dylib") + relativeProduct = relativePath(from: products, to: image) + } else { + let prefix = nativeApp.map { app in + let frameworks = platform.frameworksDirectory(in: app) + return frameworks.pathComponents.dropFirst(app.pathComponents.count).joined(separator: "/") + "/PreviewDependencies" + } ?? "Dependencies" + relativeProduct = "\(prefix)/\(result.products.count)/" + product.lastPathComponent + } + result.products[product] = relativeProduct + } + return relativeProduct + library.output.path.dropFirst(product.path.count) + } + result.rootLibraries = try rootImages.map { try stagedPath($0) } + while let current = pending.popLast() { + let runtimePaths = current.library.rpaths.compactMap { runtimeURL($0, importer: current.library.output) } + + current.inheritedPaths + let inputs = try current.library.target?.linkedInputs() + let linkedImage = linkedImage(at: current.library.output) + let searchPaths = (linkedImage?.searchPaths ?? inputs?.searchPaths ?? []) + current.inheritedLinkPaths + let linkedLibraries = try (linkedImage?.linkInputs ?? inputs?.files ?? []).compactMap { candidate in + try libraries.first { $0.output.resolvingSymlinksInPath() == candidate.resolvingSymlinksInPath() } + ?? library(at: candidate) + } + for name in current.library.dependencies { + let matches = libraries.filter { $0.identifier == name || $0.output.path == name } + var dependency: Library? + var resolvedInNativeApp = false + // Existing native products keep their packaging and loader paths. Only newly reachable code is staged. + if nativeApp != nil { + let candidates = name.hasPrefix("@rpath/") + ? runtimePaths.map { $0.appendingPathComponent(String(name.dropFirst("@rpath/".count))) } + : runtimeURL(name, importer: current.library.output).map { [$0] } ?? [] + for candidate in candidates where FileManager.default.fileExists(atPath: candidate.path) { + if try nativePath(candidate) != nil, let resolved = try library(at: candidate) { + dependency = resolved + resolvedInNativeApp = name.hasPrefix("@") + break + } + } + } + if dependency == nil { dependency = matches.first { $0.output.path == name } } + if dependency == nil { + let linked = linkedLibraries.filter { $0.identifier == name || $0.output.path == name } + if linked.count == 1 { dependency = linked[0] } + } + if dependency == nil { + let candidates: [URL] + if name.hasPrefix("@rpath/") { + let relative = String(name.dropFirst("@rpath/".count)) + let paths = searchPaths.filter { $0.framework == relative.contains(".framework/") }.map(\.url) + candidates = (runtimePaths + paths).map { $0.appendingPathComponent(relative) } + } else { + candidates = runtimeURL(name, importer: current.library.output).map { [$0] } ?? [] + } + // Prebuilt inputs have no native target record; their real load commands and linker paths locate them. + for candidate in candidates { + if let built = libraries.first(where: { $0.output.resolvingSymlinksInPath() == candidate.resolvingSymlinksInPath() }) { + dependency = built + break + } + if let resolved = try library(at: candidate) { + dependency = resolved + break + } + } + } + if dependency == nil, matches.count == 1 { dependency = matches[0] } + guard let dependency, !preloaded.contains(dependency.output) else { continue } + let importer = try stagedPath(current.library) + let target = try stagedPath(dependency) + let replacement = "@loader_path/" + relativePath( + from: products.appendingPathComponent(importer).deletingLastPathComponent(), + to: products.appendingPathComponent(target)) + let internalRelative = name.hasPrefix("@loader_path/") + && current.library.product.resolvingSymlinksInPath() == dependency.product.resolvingSymlinksInPath() + if name != replacement && !internalRelative && !resolvedInNativeApp { + result.relocations.append(.init(library: importer, name: name, + replacement: replacement)) + } + if visited.insert(dependency.output.resolvingSymlinksInPath()).inserted { + pending.append((dependency, runtimePaths, searchPaths)) + } + } + } + return result + } + + static func linkStaticProducts(for roots: [NativePreviewBuild.Target], host: NativePreviewBuild.Target? = nil, + in app: URL, products: URL, platform: NativePreviewPlatform, + process: NativePreviewProcess) async throws -> [URL: LinkedPreviewImage] { + let staticRoots = try roots.filter { root in + try root.outputURL.map { try NativePreviewBinary.isStaticLibrary(at: $0) } ?? false + } + let staticOutputs = Set(staticRoots.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) + var images: [URL: LinkedPreviewImage] = [:] + var active: Set = [] + func link(_ root: NativePreviewBuild.Target) async throws { + guard let output = root.outputURL?.resolvingSymlinksInPath(), images[output] == nil else { return } + guard active.insert(output).inserted else { + throw NativeRuntimeError.unsupportedContract("The static preview roots contain a link dependency cycle at \(root.buildableName)") + } + defer { active.remove(output) } + if staticOutputs.count > 1 { + for dependency in root.dependencies { + if let peer = staticRoots.first(where: { $0.outputURL?.resolvingSymlinksInPath() == dependency.outputURL?.resolvingSymlinksInPath() }) { + try await link(peer) + } + } + let targets = [root] + root.dependencies.filter { dependency in + dependency.outputURL.map { !staticOutputs.contains($0.resolvingSymlinksInPath()) } ?? true + } + for target in targets { + guard let targetOutput = target.outputURL?.resolvingSymlinksInPath(), + try NativePreviewBinary.isStaticLibrary(at: targetOutput) else { continue } + for input in try target.linkedInputs().files where input.resolvingSymlinksInPath() != targetOutput { + if let peer = staticRoots.first(where: { $0.outputURL?.resolvingSymlinksInPath() == input.resolvingSymlinksInPath() }) { + try await link(peer) + } + } + } + } + let packageRoot = host == nil && root.isDynamicPackageProduct + let directory = packageRoot ? platform.executableDirectory(in: app) : products + let name = packageRoot ? "XcodeMCPPreviewPackage-\(UUID().uuidString).dylib" + : staticRoots.count == 1 ? "XcodeMCPPreviewSource.dylib" : "XcodeMCPPreviewSource-\(UUID().uuidString).dylib" + images[output] = try await linkStaticProduct(root, host: host, in: app, products: products, + to: directory.appendingPathComponent(name), linkedImages: images, platform: platform, process: process) + } + for root in staticRoots { try await link(root) } + return images + } + + static func linkStaticProduct(_ source: NativePreviewBuild.Target, host: NativePreviewBuild.Target? = nil, + in app: URL, products: URL, to image: URL? = nil, + linkedImages: [URL: LinkedPreviewImage] = [:], platform: NativePreviewPlatform, + process: NativePreviewProcess) async throws -> LinkedPreviewImage { + guard let output = source.outputURL else { + throw NativeRuntimeError.unsupportedContract("The static preview target has no linked product") + } + let image = image ?? products.appendingPathComponent("XcodeMCPPreviewSource.dylib") + if let host, host.outputURL?.resolvingSymlinksInPath() != output.resolvingSymlinksInPath() { + return try await linkStaticProduct(source, host: host, to: image, in: app.deletingLastPathComponent(), + installName: "@rpath/" + image.lastPathComponent, process: process) + } + // A separate image keeps the static source's entry symbol away from the renderer's entry point. + // Its placement preserves the bundle owner selected for this native root. + let archive = try NativePreviewBinary.isStaticArchive(at: output) + let input = app.deletingLastPathComponent().appendingPathComponent(image.deletingPathExtension().lastPathComponent) + .appendingPathExtension(archive ? "a" : "o") + try copyReplacingItem(output, to: input) + let sdk = try await process.xcrun(["--sdk", platform.sdk, "--show-sdk-path"]) + .trimmingCharacters(in: .whitespacesAndNewlines) + // A Swift input supplies runtime libraries without recompiling the source product. + let linkSource = app.deletingLastPathComponent().appendingPathComponent("PreviewSource.swift") + try Data().write(to: linkSource) + var arguments = ["--sdk", platform.sdk, "swiftc", "-emit-library", "-parse-as-library", "-target", platform.triple, "-sdk", sdk, + linkSource.path, "-lc++"] + arguments += archive ? ["-Xlinker", "-force_load", "-Xlinker", input.path] : [input.path] + arguments += [ + "-Xlinker", "-headerpad_max_install_names", "-Xlinker", "-install_name", "-Xlinker", + "@rpath/" + image.lastPathComponent, "-o", image.path] + let targets = [source] + source.dependencies.filter { dependency in + dependency.outputURL.flatMap { linkedImages[$0.resolvingSymlinksInPath()] } == nil + } + let sanitizers = [(targets.contains(where: \.enableAddressSanitizer), "address"), + (targets.contains(where: \.enableThreadSanitizer), "thread"), + (targets.contains(where: \.enableUndefinedBehaviorSanitizer), "undefined")].filter(\.0).map(\.1) + if !sanitizers.isEmpty { arguments.append("-sanitize=" + sanitizers.joined(separator: ",")) } + let inputs = try targets.map { try $0.linkedInputs() } + let outputs = Set(targets.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) + var merged: Set = [] + for (target, inputs) in zip(targets, inputs) { + guard let targetOutput = target.outputURL else { continue } + let mergesArchives = try NativePreviewBinary.isStaticArchive(at: targetOutput) + guard try mergesArchives || NativePreviewBinary.file(at: targetOutput)?.header.fileType == .object else { continue } + for input in inputs.files { + let path = input.resolvingSymlinksInPath() + guard path != targetOutput.resolvingSymlinksInPath(), outputs.contains(path) else { continue } + // Relocatable links consume object inputs, but may leave archive members for the final link. + let fullyMerged = try mergesArchives ? NativePreviewBinary.isStaticLibrary(at: input) + : NativePreviewBinary.file(at: input)?.header.fileType == .object + if fullyMerged { merged.insert(path) } + } + } + var linked = merged.union([output.resolvingSymlinksInPath()]) + for dependency in source.dependencies { + guard let output = dependency.outputURL else { + throw NativeRuntimeError.unsupportedContract("The preview dependency \(dependency.buildableName) has no linked product") + } + guard linked.insert(output.resolvingSymlinksInPath()).inserted else { continue } + let input = linkedImages[output.resolvingSymlinksInPath()]?.url ?? output + arguments += try NativePreviewBinary.file(at: input)?.header.fileType == .object + ? [input.path] : ["-Xlinker", input.path] + } + for (target, inputs) in zip(targets, inputs) { + guard let output = target.outputURL, try NativePreviewBinary.isStaticLibrary(at: output) else { continue } + for path in target.searchPaths(in: target.compileCommandLine) + target.searchPaths(in: target.linkCommandLine) { + arguments += [path.argument, path.url.path] + } + for input in inputs.files where !linked.contains(input.resolvingSymlinksInPath()) { + let linkedInput = linkedImages[input.resolvingSymlinksInPath()]?.url ?? input + var directory: ObjCBool = false + if unsafe FileManager.default.fileExists(atPath: linkedInput.path, isDirectory: &directory), !directory.boolValue, + try linkedInput.pathExtension == "tbd" || NativePreviewBinary.isStaticArchive(at: linkedInput) || NativePreviewBinary.isDynamicLibrary(at: linkedInput) { + arguments += ["-Xlinker", linkedInput.path] + linked.insert(input.resolvingSymlinksInPath()) + } + } + for library in inputs.libraries where library.file == nil { + arguments += library.framework ? ["-framework", library.name] : ["-l" + library.name] + } + } + let command = ["/usr/bin/xcrun"] + arguments + _ = try await process.xcrun(arguments) + // Native debug links can defer code signing to Xcode; this generated copy has its own signing owner. + _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", image.path]) + if let framework = frameworkBundle(containing: output) { + let copiedFramework = products.appendingPathComponent(framework.lastPathComponent) + if FileManager.default.fileExists(atPath: copiedFramework.path) { + _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", copiedFramework.path]) + } + } + let linkedInputs = try source.linkedInputs(in: command) + return LinkedPreviewImage(url: image, searchPaths: linkedInputs.searchPaths, linkInputs: linkedInputs.files) + } + + private static func linkStaticProduct(_ source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, + to image: URL, in directory: URL, installName: String? = nil, + process: NativePreviewProcess) async throws -> LinkedPreviewImage { + guard let output = source.outputURL else { + throw NativeRuntimeError.unsupportedContract("The static preview target has no linked product") + } + let input = directory.appendingPathComponent(try NativePreviewBinary.isStaticArchive(at: output) + ? "PreviewSource.a" : output.lastPathComponent) + try copyReplacingItem(output, to: input) + let command = try hostedStaticProductCommand(source: source, host: host, product: input, image: image, + installName: installName) + _ = try await process.run(command[0], Array(command.dropFirst()), + directory: host.linkerWorkingDirectory.map { URL(filePath: $0, directoryHint: .isDirectory) }) + _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", image.path]) + let inputs = try host.linkedInputs(in: command) + return LinkedPreviewImage(url: image, searchPaths: inputs.searchPaths, linkInputs: inputs.files) + } + + static func prepareNativeExtension(source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, + containingApp: URL, in directory: URL, targets: [NativePreviewBuild.Target], + platform: NativePreviewPlatform, process: NativePreviewProcess) async throws -> URL { + guard let output = host.outputURL, let product = productBundle(containing: output) else { + throw NativeRuntimeError.unsupportedContract("The static preview host has no linked product") + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let app = directory.appendingPathComponent(containingApp.lastPathComponent, isDirectory: true) + try copyReplacingItem(containingApp, to: app) + let originalEmbedded = (Bundle(url: containingApp)?.builtInPlugInsURL ?? containingApp.appendingPathComponent("PlugIns", isDirectory: true)) + .appendingPathComponent(product.lastPathComponent, isDirectory: true) + let embedded = app.appendingPathComponent(originalEmbedded.pathComponents.dropFirst(containingApp.pathComponents.count) + .joined(separator: "/"), isDirectory: true) + let image = embedded.appendingPathComponent(output.pathComponents.dropFirst(product.pathComponents.count).joined(separator: "/")) + let linked = try await linkStaticProduct(source, host: host, to: image, in: directory, process: process) + let dependencies = try frameworkDependencies(for: [source], targets: targets, platform: platform, + in: app, linkedImages: source.outputURL.map { [$0.resolvingSymlinksInPath(): linked] } ?? [:], + environment: host.rendererEnvironment, nativeApp: app) + try copyFrameworkDependencies(dependencies, into: app) + try await relocateFrameworkDependencies(dependencies, in: app, process: process) + // Re-sign only the changed owners, preserving each bundle's own entitlements and executable stub. + for (original, copy) in [(originalEmbedded, embedded), (containingApp, app)] { + var signing = ["--force", "--sign", "-"] + if let entitlements = try NativePreviewEntitlements.read(from: original).signed { + let plist = directory.appendingPathComponent(copy.lastPathComponent + "-entitlements.plist") + try entitlements.write(to: plist) + signing += ["--entitlements", plist.path] + } + _ = try await process.run("/usr/bin/codesign", signing + [copy.path]) + } + return app + } + + private static func hostedStaticProductCommand(source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, + product: URL, image: URL, installName: String?) throws -> [String] { + guard let executable = host.linkCommandLine.first else { + throw NativeRuntimeError.unsupportedContract("The static preview host has no link command") + } + let directory = product.deletingLastPathComponent().appendingPathComponent("PreviewLink", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let inputs = try host.linkedInputs() + let mergesArchives = try NativePreviewBinary.isStaticArchive(at: product) + var owned = Set((source.objectFiles + [source.outputURL].compactMap { $0 }).map { $0.resolvingSymlinksInPath() }) + // A relocatable link can leave archive members for the host's final link. + for input in try source.linkedInputs().files { + var isDirectory: ObjCBool = false + if unsafe FileManager.default.fileExists(atPath: input.path, isDirectory: &isDirectory), !isDirectory.boolValue, + try (mergesArchives && NativePreviewBinary.isStaticArchive(at: input)) + || NativePreviewBinary.file(at: input)?.header.fileType == .object { + owned.insert(input.resolvingSymlinksInPath()) + } + } + func owns(_ path: String) -> Bool { + host.url(for: path).map { owned.contains($0.resolvingSymlinksInPath()) } ?? false + } + func ownsLibrary(framework: Bool, name: String) -> Bool { + inputs.libraries.contains { $0.framework == framework && $0.name == name + && $0.file.map { owned.contains($0.resolvingSymlinksInPath()) } == true } + } + func encode(_ argument: (value: String, forwarded: Bool), replacing value: String? = nil) -> [String] { + let value = value ?? argument.value + return argument.forwarded ? ["-Xlinker", value] : [value] + } + let arguments = host.linkArguments(in: Array(host.linkCommandLine.dropFirst())) + var result = [executable] + var index = 0 + while index < arguments.count { + let argument = arguments[index] + let next = arguments.indices.contains(index + 1) ? arguments[index + 1] : nil + if ["-o", "-install_name", "-dependency_info", "-object_path_lto", "-map"].contains(argument.value), let next { + let value = argument.value == "-o" ? image.path : argument.value == "-install_name" ? installName ?? next.value + : directory.appendingPathComponent(URL(filePath: next.value).lastPathComponent).path + result += encode(argument) + encode(next, replacing: value) + index += 2 + } else if argument.value == "-filelist", let next, let path = host.url(for: next.value) { + let entries = try String(contentsOf: path, encoding: .utf8).split(whereSeparator: \.isNewline).map(String.init) + let copy = directory.appendingPathComponent("PreviewLinkFileList-\(index).txt") + try (entries.filter { !owns($0) }.joined(separator: "\n") + "\n").write(to: copy, atomically: true, encoding: .utf8) + result += encode(argument) + encode(next, replacing: copy.path) + index += 2 + } else if argument.value == "-force_load", let next, owns(next.value) { + index += 2 + } else if argument.value == "-framework", let next, ownsLibrary(framework: true, name: next.value) { + index += 2 + } else if argument.value == "-l", let next, ownsLibrary(framework: false, name: next.value) { + index += 2 + } else if argument.value.hasPrefix("-l"), ownsLibrary(framework: false, name: String(argument.value.dropFirst(2))) { + index += 1 + } else { + if !owns(argument.value) { result += encode(argument) } + index += 1 + } + } + for path in source.searchPaths(in: source.compileCommandLine) + source.searchPaths(in: source.linkCommandLine) { + result += [path.argument == "-L" ? "-L" : "-F", path.url.path] + } + let sourceArguments = mergesArchives + ? ["-Xlinker", "-force_load", "-Xlinker", product.path] : [product.path] + return result + sourceArguments + ["-Xlinker", "-headerpad_max_install_names"] + } + + static func copyFrameworkDependencies(_ dependencies: FrameworkDependencies, into products: URL) throws { + for (source, path) in dependencies.products { + let destination = products.appendingPathComponent(path) + try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: source, to: destination) + } + } + + static func relocateFrameworkDependencies(_ dependencies: FrameworkDependencies, in products: URL, + process: NativePreviewProcess) async throws { + var changedFrameworks: Set = [] + for path in Set(dependencies.relocations.map(\.library)).sorted() { + let library = products.appendingPathComponent(path).standardizedFileURL + let arguments = dependencies.relocations.filter { $0.library == path }.flatMap { ["-change", $0.name, $0.replacement] } + _ = try await process.xcrun(["install_name_tool"] + arguments + [library.path]) + _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", library.path]) + if let framework = frameworkBundle(containing: library) { changedFrameworks.insert(framework) } + } + // Nested dylibs can be sealed framework resources; refresh their owning bundle after re-signing the changed code. + for framework in changedFrameworks.sorted(by: { $0.path.count > $1.path.count }) { + _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", framework.path]) + } + } + + @discardableResult + static func prepareApp(product: URL, sourceProduct: URL? = nil, helper: URL, app: URL, containingApp: URL? = nil, + platform: NativePreviewPlatform = .iOS, clientIdentifier: String? = nil, + staticProduct: Bool = false, resourceURLs: [URL] = []) throws -> URL { + let frameworks = platform.frameworksDirectory(in: app) + let products: URL + if let sourceProduct, staticProduct { + products = app.deletingLastPathComponent().appendingPathComponent("Products", isDirectory: true) + .appendingPathComponent(sourceProduct.deletingLastPathComponent().lastPathComponent, isDirectory: true) + } else { products = frameworks } + try FileManager.default.copyItem(at: product, to: app) + let original = try bundleInfo(at: app) + try FileManager.default.createDirectory(at: products, withIntermediateDirectories: true) + if let sourceProduct, sourceProduct.pathExtension == "framework" { + try FileManager.default.copyItem(at: sourceProduct, to: products.appendingPathComponent(sourceProduct.lastPathComponent)) + } + for resource in resourceURLs { + try FileManager.default.copyItem(at: resource, to: products.appendingPathComponent(resource.lastPathComponent)) + } + let executable = helper.appendingPathComponent("XcodeMCPPreviewRenderer") + try copyReplacingItem(executable, to: platform.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer")) + var info = Self.rendererInfo(original, platform: platform) + // The client coexists with the original extension registration. + if let clientIdentifier { info["CFBundleIdentifier"] = clientIdentifier } + try PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0) + .write(to: platform.infoURL(in: app)) + try FileManager.default.createDirectory(at: platform.resourcesDirectory(in: app), withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: frameworks, withIntermediateDirectories: true) + if let shared = containingApp.map({ platform.frameworksDirectory(in: $0) }), + FileManager.default.fileExists(atPath: shared.path) { + // Extensions search their own Frameworks before their containing app's. + for item in try FileManager.default.contentsOfDirectory(at: shared, includingPropertiesForKeys: nil) { + let destination = frameworks.appendingPathComponent(item.lastPathComponent) + if !FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.copyItem(at: item, to: destination) + } + } + } + try copyContents(helper.appendingPathComponent("Frameworks"), to: frameworks) + return products + } + + static func appName(product: URL, containingApp: URL?, localization: String?) throws -> String { + let owner = containingApp ?? product + guard let bundle = Bundle(url: owner) else { throw NativePipelineRequired() } + if let localization { + let info = bundle.infoDictionary ?? [:] + let key = info["CFBundleDisplayName"] is String ? "CFBundleDisplayName" : "CFBundleName" + guard let name = info[key] as? String else { return "" } + return bundle.localizedString(forKey: key, value: name, table: "InfoPlist", + localizations: [Locale.Language(identifier: localization)]) + } + return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String + ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "" + } + + static func rendererInfo(_ original: [String: Any], platform: NativePreviewPlatform = .iOS) -> [String: Any] { + let startupKeys = ["CFBundleExecutable", "CFBundlePackageType", "NSPrincipalClass", "UIMainStoryboardFile", + "UIApplicationSceneManifest", "NSExtension", "NSMainNibFile", "NSMainStoryboardFile", + "UISupportedInterfaceOrientations"] + // Bundle lookup gives platform/device-qualified keys precedence over base keys. + var info = original.filter { key, _ in + !startupKeys.contains { key == $0 || key.hasPrefix($0 + "-") || key.hasPrefix($0 + "~") } + } + info["CFBundleExecutable"] = "XcodeMCPPreviewRenderer" + info["CFBundlePackageType"] = "APPL" + let minimumKey = platform.isSimulator ? "MinimumOSVersion" : "LSMinimumSystemVersion" + if (info[minimumKey] as? String ?? "").compare(platform.minimumVersion, options: .numeric) == .orderedAscending { + info[minimumKey] = platform.minimumVersion + } + if platform != .macOS && platform != .watchOS { + info["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown", + "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"] + info["UIApplicationSceneManifest"] = ["UIApplicationSupportsMultipleScenes": false, + "UISceneConfigurations": ["UIWindowSceneSessionRoleApplication": [["UISceneConfigurationName": "Preview", "UISceneDelegateClassName": "XcodeMCPPreviewRenderer.PreviewRendererScene"]]]] + } + if platform == .macOS { info["NSPrincipalClass"] = "NSApplication" } + if platform == .watchOS { + info["WKApplication"] = true + info["WKWatchOnly"] = true + info["WKRunsIndependentlyOfCompanionApp"] = nil + info["WKCompanionAppBundleIdentifier"] = nil + } + return info + } + + private static func copyContents(_ source: URL, to destination: URL) throws { + for item in try FileManager.default.contentsOfDirectory(at: source, includingPropertiesForKeys: nil) { + try copyReplacingItem(item, to: destination.appendingPathComponent(item.lastPathComponent)) + } + } + + private static func copyReplacingItem(_ source: URL, to destination: URL) throws { + if FileManager.default.fileExists(atPath: destination.path) { try FileManager.default.removeItem(at: destination) } + try FileManager.default.copyItem(at: source, to: destination) + } + + static func previewLibraries(in app: URL, platform: NativePreviewPlatform) throws -> [URL] { + let libraries = try FileManager.default.contentsOfDirectory(at: platform.executableDirectory(in: app), includingPropertiesForKeys: nil) + .filter { $0.lastPathComponent.hasSuffix(".debug.dylib") } + guard !libraries.isEmpty else { throw NativePipelineRequired() } + return libraries + } + + static func programLibraries(previewLibraries: [URL], output: URL) throws -> [URL] { + try previewLibraries.filter { try NativePreviewBinary.matches(output, $0) } + } + + static func registryLibraries(in app: URL, previewLibraries: [URL], products: URL? = nil) throws -> [URL] { + var libraries = previewLibraries + libraries += try FileManager.default.contentsOfDirectory(at: Bundle(url: app)?.executableURL?.deletingLastPathComponent() ?? app, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "dylib" } + let frameworks = Bundle(url: app)?.privateFrameworksURL ?? app.appendingPathComponent("Frameworks", isDirectory: true) + for directory in Set([frameworks] + (products.map { [$0] } ?? [])) { + for subpath in try FileManager.default.subpathsOfDirectory(atPath: directory.path) { + let item = directory.appendingPathComponent(subpath) + if item.pathExtension == "framework" { + if let executable = Bundle(url: item)?.executableURL { libraries.append(executable) } + } else if item.pathExtension == "dylib" { + libraries.append(item) + } + } + } + return Array(Set(libraries.map { $0.resolvingSymlinksInPath() })).sorted { $0.path < $1.path } + } + + static func libraryPaths(in app: URL, previewLibraries: [URL], registryLibraries: [URL], sourceOutput: URL?, + products: URL? = nil) throws -> [String] { + var libraries = previewLibraries + if let sourceOutput, Self.productBundle(containing: sourceOutput) == nil { + let frameworkName = sourceOutput.pathComponents.last(where: { $0.hasSuffix(".framework") }) + if frameworkName != nil || sourceOutput.pathExtension == "dylib", + try !NativePreviewBinary.isStaticArchive(at: sourceOutput) { + guard let sourceLibrary = try registryLibraries.first(where: { library in + guard library.lastPathComponent == sourceOutput.lastPathComponent, + frameworkName.map({ library.pathComponents.contains($0) }) ?? true else { return false } + return try NativePreviewBinary.matches(sourceOutput, library) + }) else { throw NativePipelineRequired() } + libraries.append(sourceLibrary) + } + } + let root = app.resolvingSymlinksInPath() + let products = products?.resolvingSymlinksInPath() + var paths: [String] = [] + for library in libraries { + let library = library.resolvingSymlinksInPath() + var relationship: FileManager.URLRelationship = .other + try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: root, toItemAt: library) + let relative: String + if relationship == .contains { + relative = String(library.path.dropFirst(root.path.count + 1)) + } else if let products { + try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: products, toItemAt: library) + guard relationship == .contains else { throw NativePipelineRequired() } + let operation = root.deletingLastPathComponent() + try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: operation, toItemAt: library) + guard relationship == .contains else { throw NativePipelineRequired() } + relative = "../" + library.path.dropFirst(operation.path.count + 1) + } else { throw NativePipelineRequired() } + if !paths.contains(relative) { paths.append(relative) } + } + return paths + } + + static func registryNames(in symbols: String) -> [String] { + Set(symbols.split(whereSeparator: \.isNewline).compactMap { line -> String? in + let symbol = String(line) + // Names may use mangling substitutions. The renderer checks PreviewRegistry conformance. + guard symbol.hasPrefix("_$s"), symbol.hasSuffix("VMn"), symbol.contains("fMu_") else { return nil } + return String(symbol.dropFirst(3).dropLast(2)) + }).sorted() + } + + static func programRootNames(in symbols: String) -> [String] { + let suffix = "5$mainyyFZ" + return Set(symbols.split(whereSeparator: \.isNewline).compactMap { line -> String? in + let symbol = String(line) + // The renderer checks Widget/WidgetBundle conformance before initializing the program root. + guard symbol.hasPrefix("_$s"), symbol.hasSuffix(suffix) else { return nil } + return String(symbol.dropFirst(3).dropLast(suffix.count)) + }).sorted() + } + + static func bundleInfo(at bundle: URL) throws -> [String: Any] { + let rootInfo = bundle.appendingPathComponent("Info.plist") + let infoURL = FileManager.default.fileExists(atPath: rootInfo.path) ? rootInfo : bundle.appendingPathComponent("Contents/Info.plist") + let data = try Data(contentsOf: infoURL) + guard let info = try unsafe PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { + throw NativeRuntimeError.unsupportedContract("The built preview product has an unsupported Info.plist") + } + return info + } +} diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift index 9bc37f69..ecd3a49f 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift @@ -9,6 +9,7 @@ final class NativePreviewTool { private static let defaultTimeout: Int64 = 300 private let installation: NativeXcodeInstallation private let builder: NativePreviewBuild + private let definitions: NativePreviewDefinitions private var operations: [UUID: (request: URL?, task: Task)] = [:] private var sessions: [String: WorkspaceSession] = [:] private let renderQueue = NativePreviewRenderQueue() @@ -73,7 +74,7 @@ final class NativePreviewTool { let requestKey: [String: JSONValue] let sourcePath: String let source: URL - let location: Definition + let location: NativePreviewDefinitions.Definition let index: Int let localization: String? let context: NativePreviewBuild.PlanningContext @@ -111,6 +112,7 @@ final class NativePreviewTool { init(installation: NativeXcodeInstallation) { self.installation = installation builder = NativePreviewBuild(installation: installation) + definitions = NativePreviewDefinitions(installation: installation) } static func handles(_ action: NativeActionClass) -> Bool { @@ -339,7 +341,7 @@ final class NativePreviewTool { private struct Prepared { let workspace: AnyObject let source: URL - let location: Definition + let location: NativePreviewDefinitions.Definition let destination: NativePreviewBuild.DestinationSelection let context: NativePreviewBuild.PlanningContext let retainedBuild: (build: NativePreviewBuild.Result, signature: NativePreviewProductSignature)? @@ -389,8 +391,8 @@ final class NativePreviewTool { try await NativeWorkspaceRegistry.waitForSourcePackages(in: workspace) } session.plan?.certificate = nil - let source = try await sourceURL(input.sourcePath, workspace: workspace) - let location = try await previewDefinition(source: source, index: input.index) + let source = try await definitions.sourceURL(input.sourcePath, workspace: workspace) + let location = try await definitions.definition(in: source, at: input.index) let context = try builder.planningContext(workspace: workspace) let resolution = try await builder.resolveDestination(workspace: workspace, input: input.nativeValue) if let plan = session.plan, plan.source == source, plan.index == input.index, @@ -614,19 +616,13 @@ final class NativePreviewTool { return try result.get() } - static func removeStagedApp(_ app: URL) throws { - try FileManager.default.removeItem(at: app) - let products = app.deletingLastPathComponent().appendingPathComponent("Products", isDirectory: true) - if FileManager.default.fileExists(atPath: products.path) { try FileManager.default.removeItem(at: products) } - } - private struct RendererPreparation { var request: PreviewRendererRequest let app: URL let product: URL let containingApp: URL? let environment: [String: String] - let selection: Selection + let selection: NativePreviewStaging.Selection let staticProduct: Bool let additionalProducts: [URL] let productSignature: NativePreviewProductSignature @@ -660,7 +656,7 @@ final class NativePreviewTool { request.columnNumber = prepared.location.column request.definitionIndex = input.index if let path = prepared.location.providerPath, let module = request.moduleName { - request.providerTypeName = try await providerTypeName(path: path, moduleName: module) + request.providerTypeName = try await definitions.providerTypeName(path: path, moduleName: module) } else { request.providerTypeName = nil } if metadataOnly == true, let source = request.nativeSource, let provider = request.providerTypeName { request.nativeSource = .providerMetadata(extensionIdentifier: source.extensionIdentifier, providerName: provider) @@ -674,7 +670,7 @@ final class NativePreviewTool { request.activityViewStyle = input.activityViewStyle request.activityViewContext = input.activityViewContext request.activityToggleState = input.activityToggleState - request.appName = try Self.appName(product: stage.preparation.product, + request.appName = try NativePreviewStaging.appName(product: stage.preparation.product, containingApp: stage.preparation.containingApp, localization: input.localization) request.metadataOnly = metadataOnly request.isLegacyComplication = isLegacyComplication @@ -690,7 +686,7 @@ final class NativePreviewTool { nativeWidget: Bool = false, additionalProducts: [URL] = []) async throws -> RendererPreparation { let source = prepared.source let location = prepared.location - let selection = try Self.selectTarget(build.targets, source: source, platform: platform) + let selection = try NativePreviewStaging.selectTarget(build.targets, source: source, platform: platform) let target = selection.host guard let version = build.systemVersion, version.compare(platform.minimumVersion, options: .numeric) != .orderedAscending else { throw NativePipelineRequired() @@ -698,7 +694,7 @@ final class NativePreviewTool { guard let output = target.outputURL else { throw NativeRuntimeError.unsupportedContract("The preview target has no linked product") } - let appProduct = Self.productBundle(containing: output) + let appProduct = NativePreviewStaging.productBundle(containing: output) let product: URL let sourceProduct: URL? if let appProduct { @@ -707,44 +703,44 @@ final class NativePreviewTool { sourceProduct = nil } else { product = try await builder.frameworkAgent(for: destination) - sourceProduct = Self.frameworkBundle(containing: output) ?? output + sourceProduct = NativePreviewStaging.frameworkBundle(containing: output) ?? output } let app = directory.appendingPathComponent(sourceProduct == nil ? "Preview.app" : product.lastPathComponent, isDirectory: true) let staticProduct = try selection.source.outputURL.map { try NativePreviewBinary.isStaticLibrary(at: $0) } ?? false let entitlements = try NativePreviewEntitlements.read(from: product) let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/PreviewRenderer/\(platform.helperDirectory)") - let containingApp = try Self.containingApp(for: output, targets: build.targets) + let containingApp = try NativePreviewStaging.containingApp(for: output, targets: build.targets) let originalProducts = additionalProducts + [product] + (sourceProduct.map { [$0] } ?? []) + (containingApp.map { [$0] } ?? []) let originalSignature = try await NativePreviewProductSignature.make(build: build, source: source, helper: helper, digestCache: digestCache, additionalProducts: originalProducts) let nativeExtensionIdentifier = ((metadataOnly == true && location.providerPath != nil) || nativeWidget) && (platform == .iOS || platform == .watchOS) && containingApp != nil - ? try Self.widgetExtensionIdentifier(product) : nil + ? try NativePreviewStaging.widgetExtensionIdentifier(product) : nil let clientIdentifier = (platform == .iOS || platform == .watchOS) && containingApp != nil ? "dev.xcodemcp.PreviewClient." + UUID().uuidString : nil let roots = sourceProduct == nil ? [selection.source] : build.previewRoots let copiedSourceProduct = sourceProduct.flatMap { product in - roots.contains { $0.isDynamicPackageProduct && $0.outputURL.flatMap(Self.frameworkBundle(containing:)) == product } + roots.contains { $0.isDynamicPackageProduct && $0.outputURL.flatMap(NativePreviewStaging.frameworkBundle(containing:)) == product } ? nil : product } - let products = try Self.prepareApp(product: product, sourceProduct: copiedSourceProduct, helper: helper, app: app, + let products = try NativePreviewStaging.prepareApp(product: product, sourceProduct: copiedSourceProduct, helper: helper, app: app, containingApp: containingApp, platform: platform, clientIdentifier: clientIdentifier, staticProduct: staticProduct, resourceURLs: selection.source.resourceURLs) let linkedImages = try await nativeExtensionIdentifier == nil - ? Self.linkStaticProducts(for: roots, host: sourceProduct == nil ? selection.host : nil, in: app, + ? NativePreviewStaging.linkStaticProducts(for: roots, host: sourceProduct == nil ? selection.host : nil, in: app, products: products, platform: platform, process: process) : [:] let primaryImage = selection.source.outputURL.flatMap { linkedImages[$0.resolvingSymlinksInPath()]?.url } - let dependencies = sourceProduct == nil && linkedImages.isEmpty ? FrameworkDependencies() - : try Self.frameworkDependencies(for: roots, targets: build.targets, platform: platform, + let dependencies = sourceProduct == nil && linkedImages.isEmpty ? NativePreviewStaging.FrameworkDependencies() + : try NativePreviewStaging.frameworkDependencies(for: roots, targets: build.targets, platform: platform, in: products, agentApp: sourceProduct == nil ? nil : app, sourceProduct: copiedSourceProduct, linkedImages: linkedImages, environment: target.rendererEnvironment) let copiedProducts = Array(Set(originalProducts + Array(dependencies.products.keys))) let productSignature = try await NativePreviewProductSignature.make(build: build, source: source, helper: helper, digestCache: digestCache, additionalProducts: copiedProducts) - try Self.copyFrameworkDependencies(dependencies, into: products) + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: products) if let simulatorEntitlements = entitlements.simulator { let section = app.deletingLastPathComponent().appendingPathComponent("simulator-entitlements.plist") try simulatorEntitlements.write(to: section) @@ -763,18 +759,18 @@ final class NativePreviewTool { } else if sourceProduct != nil { libraries = dependencies.rootLibraries.map { products.appendingPathComponent($0) } } else { - libraries = try primaryImage.map { [$0] } ?? previewLibraries(in: app, platform: platform) + libraries = try primaryImage.map { [$0] } ?? NativePreviewStaging.previewLibraries(in: app, platform: platform) } let registryLibraries = try nativeExtensionIdentifier == nil - ? Self.registryLibraries(in: app, previewLibraries: libraries, products: products) : [] - let libraryPaths = try nativeExtensionIdentifier == nil ? Self.libraryPaths(in: app, previewLibraries: libraries, + ? NativePreviewStaging.registryLibraries(in: app, previewLibraries: libraries, products: products) : [] + let libraryPaths = try nativeExtensionIdentifier == nil ? NativePreviewStaging.libraryPaths(in: app, previewLibraries: libraries, registryLibraries: registryLibraries, sourceOutput: sourceProduct == nil ? primaryImage ?? selection.source.outputURL : nil, products: products) : [] let names = try NativePreviewBinary.previewSymbols(in: registryLibraries).registryNames let providerName: String? if let path = location.providerPath { guard let moduleName = selection.source.moduleName else { throw NativePipelineRequired() } - providerName = try await providerTypeName(path: path, moduleName: moduleName) + providerName = try await definitions.providerTypeName(path: path, moduleName: moduleName) } else { providerName = nil } let programRootNames: [String] do { @@ -785,7 +781,7 @@ final class NativePreviewTool { } } else { programOutputs = [primaryImage ?? output] } let programLibraries = try programOutputs.flatMap { - try Self.programLibraries(previewLibraries: registryLibraries, output: $0) + try NativePreviewStaging.programLibraries(previewLibraries: registryLibraries, output: $0) } if programLibraries.isEmpty { programRootNames = [] @@ -802,7 +798,7 @@ final class NativePreviewTool { displayVariantOverrides: input.displayVariants, activityViewStyle: input.activityViewStyle, activityViewContext: input.activityViewContext, activityToggleState: input.activityToggleState, - appName: try Self.appName(product: product, containingApp: containingApp, localization: input.localization), + appName: try NativePreviewStaging.appName(product: product, containingApp: containingApp, localization: input.localization), nativeEnvironment: target.rendererEnvironment.isEmpty ? nil : target.rendererEnvironment, metadataOnly: metadataOnly, isLegacyComplication: isLegacyComplication) if !selection.source.resourceURLs.isEmpty { @@ -815,7 +811,7 @@ final class NativePreviewTool { request.nativeSource = .providerMetadata(extensionIdentifier: nativeExtensionIdentifier, providerName: providerName) } // UUID-less source identity relies on unchanged bytes; relocate copies only after resolving their library paths. - try await Self.relocateFrameworkDependencies(dependencies, in: products, process: process) + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: products, process: process) var signing = ["--force", "--sign", "-"] if let signedEntitlements = entitlements.signed { let plist = app.deletingLastPathComponent().appendingPathComponent("signed-entitlements.plist") @@ -835,7 +831,7 @@ final class NativePreviewTool { private func nativeContainingApp(for renderer: RendererPreparation, build: NativePreviewBuild.Result, platform: NativePreviewPlatform, process: NativePreviewProcess) async throws -> URL? { guard let containingApp = renderer.containingApp, renderer.staticProduct else { return renderer.containingApp } - return try await Self.prepareNativeExtension(source: renderer.selection.source, host: renderer.selection.host, + return try await NativePreviewStaging.prepareNativeExtension(source: renderer.selection.source, host: renderer.selection.host, containingApp: containingApp, in: renderer.app.deletingLastPathComponent().appendingPathComponent("NativeHost", isDirectory: true), targets: build.targets, platform: platform, process: process) } @@ -966,17 +962,18 @@ final class NativePreviewTool { let nativeContainingApp: URL? if nativeWidget, let containingApp = renderer.containingApp, - let extensionIdentifier = try Self.widgetExtensionIdentifier(renderer.product) { + let extensionIdentifier = try NativePreviewStaging.widgetExtensionIdentifier(renderer.product) { let specification: Data if let registry = location.registry, let moduleName = renderer.request.moduleName { - specification = try await registrySpecification(registry: registry, moduleName: moduleName) + specification = try await definitions.registrySpecification(registry: registry, moduleName: moduleName) } else if let providerName = renderer.request.providerTypeName, let description = metadataResponse.nativeProviderPreviewDescription { - specification = try await providerSpecification(name: providerName, description: description) + specification = try await definitions.providerSpecification(name: providerName, + description: builder.decodePreviewValue(description, named: "PreviewDescription")) } else { throw NativePipelineRequired() } if !stage.nativeWidgetPrepared { let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/PreviewRenderer/\(platform.helperDirectory)") - try Self.removeStagedApp(renderer.app) - try Self.prepareApp(product: renderer.product, helper: helper, app: renderer.app, containingApp: containingApp, platform: platform, + try NativePreviewStaging.removeStagedApp(renderer.app) + try NativePreviewStaging.prepareApp(product: renderer.product, helper: helper, app: renderer.app, containingApp: containingApp, platform: platform, clientIdentifier: "dev.xcodemcp.PreviewClient." + UUID().uuidString) } renderer.request.libraryNames = [] @@ -1186,7 +1183,7 @@ final class NativePreviewTool { process: NativePreviewProcess, localization: String?, containingApp: URL? = nil) async throws -> (response: PreviewRendererResult, snapshot: Data?, destination: [String: JSONValue], deviceType: URL, exclusion: Data?) { let app = stage.preparation.app - let info = try Self.bundleInfo(at: app) + let info = try NativePreviewStaging.bundleInfo(at: app) guard let bundle = info["CFBundleIdentifier"] as? String else { throw NativeRuntimeError.unsupportedContract("The preview product has no bundle identifier") } @@ -1197,13 +1194,13 @@ final class NativePreviewTool { if !stage.installed { if stage.processIdentifier != nil { try await stop(stage, session: session, process: process) } for other in session.stages.values where other !== stage && other.installed { - if try Self.bundleInfo(at: other.preparation.app)["CFBundleIdentifier"] as? String == bundle { + if try NativePreviewStaging.bundleInfo(at: other.preparation.app)["CFBundleIdentifier"] as? String == bundle { try await stop(other, session: session, process: process) other.installed = false } } if let containingApp { - guard let containingIdentifier = try Self.bundleInfo(at: containingApp)["CFBundleIdentifier"] as? String else { + guard let containingIdentifier = try NativePreviewStaging.bundleInfo(at: containingApp)["CFBundleIdentifier"] as? String else { throw NativeRuntimeError.unsupportedContract("The preview containing app has no bundle identifier") } _ = try await process.xcrun(simctl + ["install", simulator.identifier, containingApp.path]) @@ -1321,1062 +1318,12 @@ final class NativePreviewTool { return workspace } - private func sourceURL(_ path: String, workspace: AnyObject) async throws -> URL { - do { - let action = try await ABIRuntime.shared.resolve( - .swift(.type("PreviewsXcode.AgenticAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) - let resolve = try await action.resolve(.swift(.staticMethod( - "projectRelativeSourceFileURL(at: Swift.String, in: __C.IDEWorkspace) async throws -> Foundation.URL", - as: (@concurrent (String, AnyObject) async throws -> PreviewURL).self))) - return try unsafe await resolve.unsafeInvoke(path, workspace).value - } catch is ABIResolutionError { - return try await legacySourceURL(path, workspace: workspace) - } - } - - private func legacySourceURL(_ path: String, workspace: AnyObject) async throws -> URL { - let type = try await ABIRuntime.shared.resolve( - .swift(.type("PreviewsXcode.RenderPreviewAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) - let resolve = try await type.resolve( - .swift( - .staticMethod( - "(resolveSourceFileURL in _FEA7E13ECD12FBA8521281D73C9764CE)(at: Swift.String, in: __C.IDEWorkspace) async throws -> Foundation.URL", - as: (@concurrent (String, AnyObject) async throws -> PreviewURL).self))) - return try unsafe await resolve.unsafeInvoke(path, workspace).value - } - - struct Selection { - let source: NativePreviewBuild.Target - let host: NativePreviewBuild.Target - } - static func rendererArguments(localization: String?) throws -> [String] { guard let localization else { return [] } let languages = try PropertyListSerialization.data(fromPropertyList: [localization], format: .xml, options: 0) return ["-AppleLanguages", String(decoding: languages, as: UTF8.self), "-AppleLocale", localization] } - static func selectTarget(_ targets: [NativePreviewBuild.Target], source: URL, platform: NativePreviewPlatform) throws -> Selection { - let sourcePath = source.resolvingSymlinksInPath().path - guard targets.contains(where: { $0.sourceFiles.contains { $0.resolvingSymlinksInPath().path == sourcePath } }) else { - throw NativeRuntimeError.invalidRequest("The active scheme did not build \(source.path)") - } - let platformTargets = targets.filter { - NativePreviewPlatform(sdkRoot: $0.sdkRoot, sdkVariant: $0.sdkVariant) == platform - } - let sources = platformTargets.filter { - $0.architecture == "arm64" && $0.sourceFiles.contains { $0.resolvingSymlinksInPath().path == sourcePath } - } - guard !sources.isEmpty else { throw NativePipelineRequired() } - var selections: [Selection] = [] - for target in sources { - if let output = target.outputURL, productBundle(containing: output) != nil { - selections.append(Selection(source: target, host: target)) - continue - } - let objectPaths = Set(target.objectFiles.map { $0.resolvingSymlinksInPath().path }) - let sourceOutput = target.outputURL - let frameworkName = sourceOutput?.pathComponents.last(where: { $0.hasSuffix(".framework") }) - let hosts = try platformTargets.filter { candidate in - guard candidate.architecture == "arm64", - let output = candidate.outputURL, let app = productBundle(containing: output) else { return false } - if candidate.objectFiles.contains(where: { objectPaths.contains($0.resolvingSymlinksInPath().path) }) { - return true - } - guard let sourceOutput else { return false } - if try (["a", "o", "dylib"].contains(sourceOutput.pathExtension) - || (frameworkName != nil && NativePreviewBinary.isStaticArchive(at: sourceOutput))) - && candidate.linksProduct(at: sourceOutput) { return true } - guard frameworkName != nil || sourceOutput.pathExtension == "dylib" else { return false } - let rootLibrary = app.appendingPathComponent(sourceOutput.lastPathComponent) - if frameworkName == nil, FileManager.default.fileExists(atPath: rootLibrary.path), - try NativePreviewBinary.matches(sourceOutput, rootLibrary) { - return true - } - let frameworks = Bundle(url: app)?.privateFrameworksURL ?? app.appendingPathComponent("Frameworks", isDirectory: true) - guard FileManager.default.fileExists(atPath: frameworks.path) else { return false } - return try FileManager.default.subpathsOfDirectory(atPath: frameworks.path).contains { subpath in - let library = frameworks.appendingPathComponent(subpath) - guard library.lastPathComponent == sourceOutput.lastPathComponent, - frameworkName.map({ library.pathComponents.contains($0) }) ?? true else { return false } - return try NativePreviewBinary.matches(sourceOutput, library) - } - } - selections += hosts.map { Selection(source: target, host: $0) } - if hosts.isEmpty, let sourceOutput, - try NativePreviewBinary.isStaticLibrary(at: sourceOutput) - || (frameworkBundle(containing: sourceOutput) != nil && NativePreviewBinary.isDynamicLibrary(at: sourceOutput)) { - selections.append(Selection(source: target, host: target)) - } - } - var candidates = selections - let runnable = candidates.filter { $0.host.isRunnable } - if !runnable.isEmpty { candidates = runnable } - guard candidates.count == 1 else { throw NativePipelineRequired() } - return candidates[0] - } - - private struct Definition { - let line: Int - let column: Int - let displayName: String - let providerPath: NativeSwiftValue? - let registry: NativeSwiftValue? - let source: NativePreviewBuild.Source - } - - private func previewDefinition(source: URL, index: Int) async throws -> Definition { - let runtime = ABIRuntime.shared - let action = try await runtime.resolve( - .swift(.type("PreviewsXcode.RenderPreviewAction")), in: .path(installation.framework("PreviewsXcode", in: "PlugIns"))) - let unit = try await runtime.resolve( - .swift(.type("PreviewsPipeline.PreviewTranslationUnit")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let parsed: NativeSwiftValue - do { - let parse = try await action.resolve(.swift(.staticMethod( - "parseTranslationUnit(sourceFileURL: Foundation.URL) async throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.RenderPreviewType])", - as: (@concurrent (PreviewURL) async throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) - parsed = try unsafe await parse.unsafeInvoke(PreviewURL(value: source)) - } catch is ABIResolutionError { - do { - let parse = try await action.resolve(.swift(.staticMethod( - "parseTranslationUnit(sourceFileURL: Foundation.URL) throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.RenderPreviewType])", - as: ((PreviewURL) throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) - parsed = try unsafe parse.unsafeInvoke(PreviewURL(value: source)) - } catch is ABIResolutionError { - let parse = try await action.resolve(.swift(.staticMethod( - "(parseTranslationUnit in _FEA7E13ECD12FBA8521281D73C9764CE)(sourceFileURL: Foundation.URL) throws -> (translationUnit: PreviewsPipeline.PreviewTranslationUnit, previews: [PreviewsXcode.RenderPreviewAction.(RenderPreviewType in _FEA7E13ECD12FBA8521281D73C9764CE)])", - as: ((PreviewURL) throws -> NativeSwiftValue).self, valueABIs: [unit: .opaque(named: unit.name)]))) - parsed = try unsafe parse.unsafeInvoke(PreviewURL(value: source)) - } - } - let translationUnit = try parsed.copyTupleElement(at: 0) - let array = try parsed.copyTupleElement(at: 1) - let previews = try array.withCopy { value -> [Any] in - guard let values = value as? [Any] else { - throw NativeRuntimeError.unsupportedContract("Native preview definitions are not an array") - } - return values - } - guard previews.indices.contains(index) else { - throw NativeRuntimeError.invalidRequest("Preview index \(index) is outside the \(previews.count) definitions in \(source.lastPathComponent)") - } - func own(_ value: T) async throws -> NativeSwiftValue { - let identity = try await runtime.resolve( - .swift(.function("XcodeMCPNativeRuntime.nativePreviewValue(A) -> A", as: ((T) -> NativeSwiftValue).self, genericArguments: [.type(T.self)]))) - return try unsafe identity.unsafeInvoke(value) - } - let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) - let locationType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceLocation")), in: model) - let boundType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceLocation.Bound")), in: model) - let pathType = try await runtime.resolve(.swift(.type("PreviewsModel.MangleableTypePath")), in: model) - let syntaxType = try await runtime.resolve(.swift(.type("PreviewsModel.SyntaxLocation")), in: model) - let contents = try String(contentsOf: source, encoding: .utf8) - var definitions: [Definition] = [] - for value in previews { - let definition = try await _openExistential(value, do: own) - let record: NativeSwiftValue - let location: NativeSwiftValue - let displayName: String - let providerPath: NativeSwiftValue? - let registryRecord: NativeSwiftValue? - if let provider = try await definition.copyEnumPayload(forCase: "previewProvider") { - record = provider - registryRecord = nil - let getPath = try await provider.type.resolve( - .swift( - .getter( - "path", as: (() -> NativeSwiftValue).self, valueABIs: [pathType: .opaque(named: pathType.name)], - receiverABI: .opaque(named: provider.type.name)))) - providerPath = try unsafe getPath.unsafeInvoke(on: provider) - let getSyntax = try await provider.type.resolve( - .swift( - .getter( - "location", as: (() -> NativeSwiftValue).self, valueABIs: [syntaxType: .opaque(named: syntaxType.name)], - receiverABI: .opaque(named: provider.type.name)))) - let syntax = try unsafe getSyntax.unsafeInvoke(on: provider) - let getLocation = try await syntax.type.resolve( - .swift( - .getter( - "locationExcludingTrivia", as: (() -> NativeSwiftValue).self, valueABIs: [locationType: .opaque(named: locationType.name)], - receiverABI: .opaque(named: syntax.type.name)))) - location = try unsafe getLocation.unsafeInvoke(on: syntax) - let getName = try await provider.type.resolve( - .swift(.getter("displayName", as: (() -> String).self, receiverABI: .opaque(named: provider.type.name)))) - displayName = try unsafe getName.unsafeInvoke(on: provider) - } else if let registry = try await definition.copyEnumPayload(forCase: "registryPreview") { - record = registry - registryRecord = registry - providerPath = nil - let getName = try await registry.type.resolve( - .swift( - .getter( - "(extension in PreviewsPipeline):PreviewsModel.RegistryDefinition.defaultDisplayName.getter : Swift.String", - as: (() -> String).self, receiverABI: .opaque(named: registry.type.name)))) - displayName = try unsafe getName.unsafeInvoke(on: registry) - let getLocation = try await registry.type.resolve( - .swift( - .getter( - "fullSourceLocation", as: (() -> NativeSwiftValue).self, valueABIs: [locationType: .opaque(named: locationType.name)], - receiverABI: .opaque(named: registry.type.name)))) - location = try unsafe getLocation.unsafeInvoke(on: registry) - } else { throw NativePipelineRequired() } - let getLine = try await record.type.resolve(.swift(.getter("lineNumber", as: (() -> Int).self, receiverABI: .opaque(named: record.type.name)))) - let line = try unsafe getLine.unsafeInvoke(on: record) - let getBound = try await location.type.resolve( - .swift( - .getter( - "lowerBound", as: (() -> NativeSwiftValue).self, valueABIs: [boundType: .opaque(named: boundType.name)], - receiverABI: .opaque(named: location.type.name)))) - let bound = try unsafe getBound.unsafeInvoke(on: location) - let getColumn = try await bound.type.resolve(.swift(.getter("column", as: (() -> Int).self, receiverABI: .opaque(named: bound.type.name)))) - let column = try unsafe getColumn.unsafeInvoke(on: bound) - definitions.append(Definition(line: line, column: try Self.registryColumn(in: contents, line: line, utf16Column: column), - displayName: displayName, providerPath: providerPath, registry: registryRecord, - source: .init(translationUnit: translationUnit, definition: definition))) - } - // The parser returns providers and registries in separate batches. The - // native tool selects definitions in source order, including mixed files. - return definitions.sorted { ($0.line, $0.column) < ($1.line, $1.column) }[index] - } - - private func registrySpecification(registry: NativeSwiftValue, moduleName: String) async throws -> Data { - let runtime = ABIRuntime.shared - let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) - let messaging = ImageSelector.path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks")) - let optionalUUID = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(UUID.self)]))) - let getSidecar = try await registry.type.resolve( - .swift( - .getter( - "sidecarIdentifier.getter : Swift.Optional", as: (() -> NativeSwiftValue).self, - valueABIs: [optionalUUID: .opaque(named: optionalUUID.name)], receiverABI: .opaque(named: registry.type.name)))) - let sidecar = try unsafe getSidecar.unsafeInvoke(on: registry) - guard try await sidecar.copyEnumPayload(forCase: "some") == nil else { throw NativePipelineRequired() } - let idType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.RegistryID")), in: messaging) - let getID = try await registry.type.resolve( - .swift( - .getter( - "id.getter : PreviewsMessagingHost.RegistryID", as: (() -> NativeSwiftValue).self, valueABIs: [idType: .opaque(named: idType.name)], - receiverABI: .opaque(named: registry.type.name)))) - let id = try unsafe getID.unsafeInvoke(on: registry) - let moduleType = try await runtime.resolve(.swift(.type("PreviewsModel.Module")), in: model) - let initializeModule = try await moduleType.resolve( - .swift( - .initializer( - "init(name: Swift.String) -> PreviewsModel.Module", as: ((String) -> NativeSwiftValue).self, - valueABIs: [moduleType: .opaque(named: moduleType.name)]))) - let module = try unsafe initializeModule.unsafeInvoke(moduleName) - let locationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.RuntimeRegistryLocation")), in: messaging) - let locate = try await registry.type.resolve( - .swift( - .method( - "runtimeLocation(in: PreviewsModel.Module) -> PreviewsMessagingHost.RuntimeRegistryLocation", - as: ((NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [moduleType: .opaque(named: moduleType.name), locationType: .opaque(named: locationType.name)], - receiverABI: .opaque(named: registry.type.name)))) - let location = try unsafe locate.unsafeInvoke(on: registry, module) - let specificationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewSpecification")), in: messaging) - let makeSpecification = try await specificationType.resolve( - .swift( - .staticMethod( - "registryPreview(stableID: PreviewsMessagingHost.RegistryID, location: PreviewsMessagingHost.RuntimeRegistryLocation) -> PreviewsMessagingHost.PreviewSpecification", - as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [ - idType: .opaque(named: idType.name), locationType: .opaque(named: locationType.name), - specificationType: .opaque(named: specificationType.name), - ]))) - let specification = try unsafe makeSpecification.unsafeInvoke(id, location) - return try await previewSpecificationData(specification) - } - - private func providerSpecification(name: String, description: Data) async throws -> Data { - let runtime = ABIRuntime.shared - let messaging = ImageSelector.path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks")) - let providerType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.ProviderPayload")), in: messaging) - let makeProvider = try await providerType.resolve( - .swift( - .initializer( - "init(providerName: Swift.String) -> PreviewsMessagingHost.ProviderPayload", as: ((String) -> NativeSwiftValue).self, - valueABIs: [providerType: .opaque(named: providerType.name)]))) - let provider = try unsafe makeProvider.unsafeInvoke(name) - let description = try await builder.decodePreviewValue(description, named: "PreviewDescription") - let getIndex = try await description.type.resolve( - .swift(.getter("index.getter : Swift.Int", as: (() -> Int).self, receiverABI: .opaque(named: description.type.name)))) - let index = try unsafe getIndex.unsafeInvoke(on: description) - let specificationType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewSpecification")), in: messaging) - let makeSpecification = try await specificationType.resolve( - .swift( - .staticMethod( - "providerPreview(provider: PreviewsMessagingHost.ProviderPayload, indexInProvider: Swift.Int) -> PreviewsMessagingHost.PreviewSpecification", - as: ((NativeSwiftValue, Int) -> NativeSwiftValue).self, - valueABIs: [providerType: .opaque(named: providerType.name), specificationType: .opaque(named: specificationType.name)]))) - let specification = try unsafe makeSpecification.unsafeInvoke(provider, index) - return try await previewSpecificationData(specification) - } - - private func previewSpecificationData(_ specification: NativeSwiftValue) async throws -> Data { - let runtime = ABIRuntime.shared - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let propertyListType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.PropertyList")), in: foundation) - let encode = try await specification.type.resolve( - .swift( - .getter( - "propertyListValue.getter : PreviewsFoundationHost.PropertyList", as: (() -> NativeSwiftValue).self, - valueABIs: [propertyListType: .opaque(named: propertyListType.name)], receiverABI: .opaque(named: specification.type.name)))) - let propertyList = try unsafe encode.unsafeInvoke(on: specification) - let dictionaryType = try await runtime.resolve(.swift(.type("Swift.Dictionary", genericArguments: [.type(String.self), .type(Any.self)]))) - let serialize = try await propertyListType.resolve( - .swift( - .getter( - "serializableDictionary.getter : [Swift.String : Any]", as: (() -> NativeSwiftValue).self, valueABIs: [dictionaryType: .pointer], - receiverABI: .opaque(named: propertyListType.name)))) - let dictionary = try unsafe serialize.unsafeInvoke(on: propertyList) - return try dictionary.withCopy { value in - guard let dictionary = value as? [String: Any] else { - throw NativeRuntimeError.unsupportedContract("Native preview specification is not a property list dictionary") - } - return try PropertyListSerialization.data(fromPropertyList: dictionary, format: .binary, options: 0) - } - } - - private func providerTypeName(path: NativeSwiftValue, moduleName: String) async throws -> String { - let model = ImageSelector.path(installation.framework("PreviewsModel", in: "SharedFrameworks")) - let type = try await ABIRuntime.shared.resolve(.swift(.type("PreviewsModel.Module")), in: model) - let initialize = try await type.resolve( - .swift( - .initializer( - "init(name: Swift.String) -> PreviewsModel.Module", as: ((String) -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) - let module = try unsafe initialize.unsafeInvoke(moduleName) - let mangle = try await path.type.resolve( - .swift( - .method( - "mangledName(in: PreviewsModel.Module) -> Swift.String", as: ((NativeSwiftValue) -> String).self, - valueABIs: [type: .opaque(named: type.name)], receiverABI: .opaque(named: path.type.name)))) - return try unsafe mangle.unsafeInvoke(on: path, module) - } - - static func registryColumn(in source: String, line: Int, utf16Column: Int) throws -> Int { - let lines = source.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) - guard line > 0, lines.indices.contains(line - 1), utf16Column >= 0 else { - throw NativeRuntimeError.invocation("The preview source changed while resolving its location") - } - let text = lines[line - 1] - // The native parser reports UTF-16 offsets; macro metadata reports - // one-based UTF-8 byte columns. Unicode prefixes must retain that mapping. - guard let position = text.utf16.index(text.utf16.startIndex, offsetBy: utf16Column, limitedBy: text.utf16.endIndex), - let index = String.Index(position, within: text) else { - throw NativeRuntimeError.invocation("The preview source changed while resolving its location") - } - return text[.. URL? { - var url = output.deletingLastPathComponent() - while url.path != "/" { - if ["app", "appex"].contains(url.pathExtension) { return url } - url.deleteLastPathComponent() - } - return nil - } - - static func frameworkBundle(containing output: URL) -> URL? { - var url = output.deletingLastPathComponent() - while url.path != "/" { - if url.pathExtension == "framework" { return url } - url.deleteLastPathComponent() - } - return nil - } - - static func containingApp(for extensionOutput: URL, targets: [NativePreviewBuild.Target]) throws -> URL? { - guard let product = productBundle(containing: extensionOutput), product.pathExtension == "appex" else { return nil } - let relativeBinary = String(extensionOutput.path.dropFirst(product.path.count + 1)) - let candidates = try targets.compactMap { target -> (app: URL, isRunnable: Bool)? in - guard target.architecture == "arm64", NativePreviewPlatform(sdkRoot: target.sdkRoot, sdkVariant: target.sdkVariant) != nil, - let output = target.outputURL, let app = productBundle(containing: output), - app.pathExtension == "app" else { return nil } - let embedded = (Bundle(url: app)?.builtInPlugInsURL ?? app.appendingPathComponent("PlugIns", isDirectory: true)) - .appendingPathComponent(product.lastPathComponent, isDirectory: true) - .appendingPathComponent(relativeBinary) - guard FileManager.default.fileExists(atPath: embedded.path), - try NativePreviewBinary.matches(extensionOutput, embedded) else { return nil } - return (app, target.isRunnable) - } - guard !candidates.isEmpty else { return nil } - let runnable = candidates.filter(\.isRunnable) - let matches = runnable.isEmpty ? candidates : runnable - guard matches.count == 1 else { throw NativePipelineRequired() } - return matches[0].app - } - - private static func widgetExtensionIdentifier(_ product: URL) throws -> String? { - guard product.pathExtension == "appex" else { return nil } - let info = try bundleInfo(at: product) - guard (info["NSExtension"] as? [String: Any])?["NSExtensionPointIdentifier"] as? String == "com.apple.widgetkit-extension" else { - return nil - } - return info["CFBundleIdentifier"] as? String - } - - struct LinkedPreviewImage { - let url: URL - let searchPaths: [(framework: Bool, url: URL)] - let linkInputs: [URL] - } - - struct FrameworkDependencies { - struct Relocation { - let library: String - let name: String - let replacement: String - } - var products: [URL: String] = [:] - var relocations: [Relocation] = [] - var rootLibraries: [String] = [] - } - - static func frameworkDependencies(for roots: [NativePreviewBuild.Target], targets: [NativePreviewBuild.Target], - platform: NativePreviewPlatform, in products: URL, agentApp: URL? = nil, - sourceProduct: URL? = nil, linkedImages: [URL: LinkedPreviewImage] = [:], - environment: [String: String] = [:], nativeApp: URL? = nil) throws -> FrameworkDependencies { - typealias SearchPath = (framework: Bool, url: URL) - typealias Library = (output: URL, product: URL, identifier: String, dependencies: [String], rpaths: [String], target: NativePreviewBuild.Target?) - let rootOutputs = Set(roots.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) - func linkedImage(at output: URL) -> LinkedPreviewImage? { - linkedImages.values.first { $0.url.resolvingSymlinksInPath() == output.resolvingSymlinksInPath() } - } - let nativeImage = roots.compactMap { root in - root.outputURL.flatMap { linkedImages[$0.resolvingSymlinksInPath()]?.url } - }.first - func library(at output: URL, target: NativePreviewBuild.Target? = nil) throws -> Library? { - let output = output.resolvingSymlinksInPath() - var isDirectory: ObjCBool = false - guard unsafe FileManager.default.fileExists(atPath: output.path, isDirectory: &isDirectory), !isDirectory.boolValue, - let image = try NativePreviewBinary.dynamicLibrary(at: output) else { return nil } - let packageImage = nativeApp == nil && agentApp != nil && target?.isDynamicPackageProduct == true - && rootOutputs.contains(output) - let product = packageImage ? output : frameworkBundle(containing: output) ?? output - return (output, product, image.identifier, image.dependencies, image.rpaths, target) - } - func relativePath(from directory: URL, to item: URL) -> String { - let base = directory.standardizedFileURL.pathComponents - let target = item.standardizedFileURL.pathComponents - let shared = zip(base, target).prefix { $0.0 == $0.1 }.count - return (Array(repeating: "..", count: base.count - shared) + target.dropFirst(shared)).joined(separator: "/") - } - func runtimeURL(_ path: String, importer: URL) -> URL? { - if path == "@loader_path" { return importer.deletingLastPathComponent() } - if path.hasPrefix("@loader_path/") { - return importer.deletingLastPathComponent().appendingPathComponent(String(path.dropFirst("@loader_path/".count))) - } - if nativeApp != nil, let output = nativeImage, let host = productBundle(containing: output) { - let executable = platform.executableDirectory(in: host) - if path == "@executable_path" { return executable } - if path.hasPrefix("@executable_path/") { - return executable.appendingPathComponent(String(path.dropFirst("@executable_path/".count))) - } - } - return path.hasPrefix("/") ? URL(filePath: path) : nil - } - func nativePath(_ url: URL) throws -> String? { - guard let nativeApp else { return nil } - var relationship: FileManager.URLRelationship = .other - try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: nativeApp, toItemAt: url) - guard relationship == .contains else { return nil } - return url.resolvingSymlinksInPath().pathComponents - .dropFirst(nativeApp.resolvingSymlinksInPath().pathComponents.count).joined(separator: "/") - } - // Native-preloaded runtimes must keep their original image identity when their clients are relocated. - let preloaded = Set(environment["DYLD_INSERT_LIBRARIES", default: ""].split(separator: ":") - .filter { $0.hasPrefix("/") }.map { URL(filePath: String($0)).resolvingSymlinksInPath() }) - let libraries = try targets.compactMap { target -> Library? in - guard target.architecture == "arm64", - NativePreviewPlatform(sdkRoot: target.sdkRoot, sdkVariant: target.sdkVariant) == platform, - let output = target.outputURL, productBundle(containing: output) == nil else { return nil } - return try library(at: linkedImages[output.resolvingSymlinksInPath()]?.url ?? output, target: target) - } - let rootImages = try roots.compactMap { root -> Library? in - guard let output = root.outputURL?.resolvingSymlinksInPath() else { return nil } - return try library(at: linkedImages[output]?.url ?? output, target: root) - } - var pending = try rootImages.map { root in - let executable = nativeApp == nil ? nil : productBundle(containing: root.output).flatMap { Bundle(url: $0)?.executableURL } - let executablePaths = try executable.flatMap { executable in - try NativePreviewBinary.file(at: executable)?.rpaths.compactMap { runtimeURL($0, importer: executable) } - } ?? [] - return (library: root, inheritedPaths: executablePaths, inheritedLinkPaths: [SearchPath]()) - } - var visited = Set(rootImages.map { $0.output }) - var result = FrameworkDependencies() - func stagedPath(_ library: Library) throws -> String { - if let path = try nativePath(library.output) { return path } - if linkedImage(at: library.output) != nil { - return relativePath(from: products, to: library.output) - } - let product = library.product.resolvingSymlinksInPath() - let relativeProduct: String - if product == sourceProduct?.resolvingSymlinksInPath() { - relativeProduct = product.lastPathComponent - } else if let path = result.products[product] { - relativeProduct = path - } else { - if nativeApp == nil, let agentApp, library.target?.isDynamicPackageProduct == true, - rootOutputs.contains(library.output) { - // Native package JIT images keep their dynamic boundary while their classes belong to the agent bundle. - let image = platform.executableDirectory(in: agentApp) - .appendingPathComponent("XcodeMCPPreviewPackage-\(UUID().uuidString).dylib") - relativeProduct = relativePath(from: products, to: image) - } else { - let prefix = nativeApp.map { app in - let frameworks = platform.frameworksDirectory(in: app) - return frameworks.pathComponents.dropFirst(app.pathComponents.count).joined(separator: "/") + "/PreviewDependencies" - } ?? "Dependencies" - relativeProduct = "\(prefix)/\(result.products.count)/" + product.lastPathComponent - } - result.products[product] = relativeProduct - } - return relativeProduct + library.output.path.dropFirst(product.path.count) - } - result.rootLibraries = try rootImages.map { try stagedPath($0) } - while let current = pending.popLast() { - let runtimePaths = current.library.rpaths.compactMap { runtimeURL($0, importer: current.library.output) } - + current.inheritedPaths - let inputs = try current.library.target?.linkedInputs() - let linkedImage = linkedImage(at: current.library.output) - let searchPaths = (linkedImage?.searchPaths ?? inputs?.searchPaths ?? []) + current.inheritedLinkPaths - let linkedLibraries = try (linkedImage?.linkInputs ?? inputs?.files ?? []).compactMap { candidate in - try libraries.first { $0.output.resolvingSymlinksInPath() == candidate.resolvingSymlinksInPath() } - ?? library(at: candidate) - } - for name in current.library.dependencies { - let matches = libraries.filter { $0.identifier == name || $0.output.path == name } - var dependency: Library? - var resolvedInNativeApp = false - // Existing native products keep their packaging and loader paths. Only newly reachable code is staged. - if nativeApp != nil { - let candidates = name.hasPrefix("@rpath/") - ? runtimePaths.map { $0.appendingPathComponent(String(name.dropFirst("@rpath/".count))) } - : runtimeURL(name, importer: current.library.output).map { [$0] } ?? [] - for candidate in candidates where FileManager.default.fileExists(atPath: candidate.path) { - if try nativePath(candidate) != nil, let resolved = try library(at: candidate) { - dependency = resolved - resolvedInNativeApp = name.hasPrefix("@") - break - } - } - } - if dependency == nil { dependency = matches.first { $0.output.path == name } } - if dependency == nil { - let linked = linkedLibraries.filter { $0.identifier == name || $0.output.path == name } - if linked.count == 1 { dependency = linked[0] } - } - if dependency == nil { - let candidates: [URL] - if name.hasPrefix("@rpath/") { - let relative = String(name.dropFirst("@rpath/".count)) - let paths = searchPaths.filter { $0.framework == relative.contains(".framework/") }.map(\.url) - candidates = (runtimePaths + paths).map { $0.appendingPathComponent(relative) } - } else { - candidates = runtimeURL(name, importer: current.library.output).map { [$0] } ?? [] - } - // Prebuilt inputs have no native target record; their real load commands and linker paths locate them. - for candidate in candidates { - if let built = libraries.first(where: { $0.output.resolvingSymlinksInPath() == candidate.resolvingSymlinksInPath() }) { - dependency = built - break - } - if let resolved = try library(at: candidate) { - dependency = resolved - break - } - } - } - if dependency == nil, matches.count == 1 { dependency = matches[0] } - guard let dependency, !preloaded.contains(dependency.output) else { continue } - let importer = try stagedPath(current.library) - let target = try stagedPath(dependency) - let replacement = "@loader_path/" + relativePath( - from: products.appendingPathComponent(importer).deletingLastPathComponent(), - to: products.appendingPathComponent(target)) - let internalRelative = name.hasPrefix("@loader_path/") - && current.library.product.resolvingSymlinksInPath() == dependency.product.resolvingSymlinksInPath() - if name != replacement && !internalRelative && !resolvedInNativeApp { - result.relocations.append(.init(library: importer, name: name, - replacement: replacement)) - } - if visited.insert(dependency.output.resolvingSymlinksInPath()).inserted { - pending.append((dependency, runtimePaths, searchPaths)) - } - } - } - return result - } - - static func linkStaticProducts(for roots: [NativePreviewBuild.Target], host: NativePreviewBuild.Target? = nil, - in app: URL, products: URL, platform: NativePreviewPlatform, - process: NativePreviewProcess) async throws -> [URL: LinkedPreviewImage] { - let staticRoots = try roots.filter { root in - try root.outputURL.map { try NativePreviewBinary.isStaticLibrary(at: $0) } ?? false - } - let staticOutputs = Set(staticRoots.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) - var images: [URL: LinkedPreviewImage] = [:] - var active: Set = [] - func link(_ root: NativePreviewBuild.Target) async throws { - guard let output = root.outputURL?.resolvingSymlinksInPath(), images[output] == nil else { return } - guard active.insert(output).inserted else { - throw NativeRuntimeError.unsupportedContract("The static preview roots contain a link dependency cycle at \(root.buildableName)") - } - defer { active.remove(output) } - if staticOutputs.count > 1 { - for dependency in root.dependencies { - if let peer = staticRoots.first(where: { $0.outputURL?.resolvingSymlinksInPath() == dependency.outputURL?.resolvingSymlinksInPath() }) { - try await link(peer) - } - } - let targets = [root] + root.dependencies.filter { dependency in - dependency.outputURL.map { !staticOutputs.contains($0.resolvingSymlinksInPath()) } ?? true - } - for target in targets { - guard let targetOutput = target.outputURL?.resolvingSymlinksInPath(), - try NativePreviewBinary.isStaticLibrary(at: targetOutput) else { continue } - for input in try target.linkedInputs().files where input.resolvingSymlinksInPath() != targetOutput { - if let peer = staticRoots.first(where: { $0.outputURL?.resolvingSymlinksInPath() == input.resolvingSymlinksInPath() }) { - try await link(peer) - } - } - } - } - let packageRoot = host == nil && root.isDynamicPackageProduct - let directory = packageRoot ? platform.executableDirectory(in: app) : products - let name = packageRoot ? "XcodeMCPPreviewPackage-\(UUID().uuidString).dylib" - : staticRoots.count == 1 ? "XcodeMCPPreviewSource.dylib" : "XcodeMCPPreviewSource-\(UUID().uuidString).dylib" - images[output] = try await linkStaticProduct(root, host: host, in: app, products: products, - to: directory.appendingPathComponent(name), linkedImages: images, platform: platform, process: process) - } - for root in staticRoots { try await link(root) } - return images - } - - static func linkStaticProduct(_ source: NativePreviewBuild.Target, host: NativePreviewBuild.Target? = nil, - in app: URL, products: URL, to image: URL? = nil, - linkedImages: [URL: LinkedPreviewImage] = [:], platform: NativePreviewPlatform, - process: NativePreviewProcess) async throws -> LinkedPreviewImage { - guard let output = source.outputURL else { - throw NativeRuntimeError.unsupportedContract("The static preview target has no linked product") - } - let image = image ?? products.appendingPathComponent("XcodeMCPPreviewSource.dylib") - if let host, host.outputURL?.resolvingSymlinksInPath() != output.resolvingSymlinksInPath() { - return try await linkStaticProduct(source, host: host, to: image, in: app.deletingLastPathComponent(), - installName: "@rpath/" + image.lastPathComponent, process: process) - } - // A separate image keeps the static source's entry symbol away from the renderer's entry point. - // Its placement preserves the bundle owner selected for this native root. - let archive = try NativePreviewBinary.isStaticArchive(at: output) - let input = app.deletingLastPathComponent().appendingPathComponent(image.deletingPathExtension().lastPathComponent) - .appendingPathExtension(archive ? "a" : "o") - try copyReplacingItem(output, to: input) - let sdk = try await process.xcrun(["--sdk", platform.sdk, "--show-sdk-path"]) - .trimmingCharacters(in: .whitespacesAndNewlines) - // A Swift input supplies runtime libraries without recompiling the source product. - let linkSource = app.deletingLastPathComponent().appendingPathComponent("PreviewSource.swift") - try Data().write(to: linkSource) - var arguments = ["--sdk", platform.sdk, "swiftc", "-emit-library", "-parse-as-library", "-target", platform.triple, "-sdk", sdk, - linkSource.path, "-lc++"] - arguments += archive ? ["-Xlinker", "-force_load", "-Xlinker", input.path] : [input.path] - arguments += [ - "-Xlinker", "-headerpad_max_install_names", "-Xlinker", "-install_name", "-Xlinker", - "@rpath/" + image.lastPathComponent, "-o", image.path] - let targets = [source] + source.dependencies.filter { dependency in - dependency.outputURL.flatMap { linkedImages[$0.resolvingSymlinksInPath()] } == nil - } - let sanitizers = [(targets.contains(where: \.enableAddressSanitizer), "address"), - (targets.contains(where: \.enableThreadSanitizer), "thread"), - (targets.contains(where: \.enableUndefinedBehaviorSanitizer), "undefined")].filter(\.0).map(\.1) - if !sanitizers.isEmpty { arguments.append("-sanitize=" + sanitizers.joined(separator: ",")) } - let inputs = try targets.map { try $0.linkedInputs() } - let outputs = Set(targets.compactMap { $0.outputURL?.resolvingSymlinksInPath() }) - var merged: Set = [] - for (target, inputs) in zip(targets, inputs) { - guard let targetOutput = target.outputURL else { continue } - let mergesArchives = try NativePreviewBinary.isStaticArchive(at: targetOutput) - guard try mergesArchives || NativePreviewBinary.file(at: targetOutput)?.header.fileType == .object else { continue } - for input in inputs.files { - let path = input.resolvingSymlinksInPath() - guard path != targetOutput.resolvingSymlinksInPath(), outputs.contains(path) else { continue } - // Relocatable links consume object inputs, but may leave archive members for the final link. - let fullyMerged = try mergesArchives ? NativePreviewBinary.isStaticLibrary(at: input) - : NativePreviewBinary.file(at: input)?.header.fileType == .object - if fullyMerged { merged.insert(path) } - } - } - var linked = merged.union([output.resolvingSymlinksInPath()]) - for dependency in source.dependencies { - guard let output = dependency.outputURL else { - throw NativeRuntimeError.unsupportedContract("The preview dependency \(dependency.buildableName) has no linked product") - } - guard linked.insert(output.resolvingSymlinksInPath()).inserted else { continue } - let input = linkedImages[output.resolvingSymlinksInPath()]?.url ?? output - arguments += try NativePreviewBinary.file(at: input)?.header.fileType == .object - ? [input.path] : ["-Xlinker", input.path] - } - for (target, inputs) in zip(targets, inputs) { - guard let output = target.outputURL, try NativePreviewBinary.isStaticLibrary(at: output) else { continue } - for path in target.searchPaths(in: target.compileCommandLine) + target.searchPaths(in: target.linkCommandLine) { - arguments += [path.argument, path.url.path] - } - for input in inputs.files where !linked.contains(input.resolvingSymlinksInPath()) { - let linkedInput = linkedImages[input.resolvingSymlinksInPath()]?.url ?? input - var directory: ObjCBool = false - if unsafe FileManager.default.fileExists(atPath: linkedInput.path, isDirectory: &directory), !directory.boolValue, - try linkedInput.pathExtension == "tbd" || NativePreviewBinary.isStaticArchive(at: linkedInput) || NativePreviewBinary.isDynamicLibrary(at: linkedInput) { - arguments += ["-Xlinker", linkedInput.path] - linked.insert(input.resolvingSymlinksInPath()) - } - } - for library in inputs.libraries where library.file == nil { - arguments += library.framework ? ["-framework", library.name] : ["-l" + library.name] - } - } - let command = ["/usr/bin/xcrun"] + arguments - _ = try await process.xcrun(arguments) - // Native debug links can defer code signing to Xcode; this generated copy has its own signing owner. - _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", image.path]) - if let framework = frameworkBundle(containing: output) { - let copiedFramework = products.appendingPathComponent(framework.lastPathComponent) - if FileManager.default.fileExists(atPath: copiedFramework.path) { - _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", copiedFramework.path]) - } - } - let linkedInputs = try source.linkedInputs(in: command) - return LinkedPreviewImage(url: image, searchPaths: linkedInputs.searchPaths, linkInputs: linkedInputs.files) - } - - private static func linkStaticProduct(_ source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, - to image: URL, in directory: URL, installName: String? = nil, - process: NativePreviewProcess) async throws -> LinkedPreviewImage { - guard let output = source.outputURL else { - throw NativeRuntimeError.unsupportedContract("The static preview target has no linked product") - } - let input = directory.appendingPathComponent(try NativePreviewBinary.isStaticArchive(at: output) - ? "PreviewSource.a" : output.lastPathComponent) - try copyReplacingItem(output, to: input) - let command = try hostedStaticProductCommand(source: source, host: host, product: input, image: image, - installName: installName) - _ = try await process.run(command[0], Array(command.dropFirst()), - directory: host.linkerWorkingDirectory.map { URL(filePath: $0, directoryHint: .isDirectory) }) - _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", image.path]) - let inputs = try host.linkedInputs(in: command) - return LinkedPreviewImage(url: image, searchPaths: inputs.searchPaths, linkInputs: inputs.files) - } - - static func prepareNativeExtension(source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, - containingApp: URL, in directory: URL, targets: [NativePreviewBuild.Target], - platform: NativePreviewPlatform, process: NativePreviewProcess) async throws -> URL { - guard let output = host.outputURL, let product = productBundle(containing: output) else { - throw NativeRuntimeError.unsupportedContract("The static preview host has no linked product") - } - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let app = directory.appendingPathComponent(containingApp.lastPathComponent, isDirectory: true) - try copyReplacingItem(containingApp, to: app) - let originalEmbedded = (Bundle(url: containingApp)?.builtInPlugInsURL ?? containingApp.appendingPathComponent("PlugIns", isDirectory: true)) - .appendingPathComponent(product.lastPathComponent, isDirectory: true) - let embedded = app.appendingPathComponent(originalEmbedded.pathComponents.dropFirst(containingApp.pathComponents.count) - .joined(separator: "/"), isDirectory: true) - let image = embedded.appendingPathComponent(output.pathComponents.dropFirst(product.pathComponents.count).joined(separator: "/")) - let linked = try await linkStaticProduct(source, host: host, to: image, in: directory, process: process) - let dependencies = try frameworkDependencies(for: [source], targets: targets, platform: platform, - in: app, linkedImages: source.outputURL.map { [$0.resolvingSymlinksInPath(): linked] } ?? [:], - environment: host.rendererEnvironment, nativeApp: app) - try copyFrameworkDependencies(dependencies, into: app) - try await relocateFrameworkDependencies(dependencies, in: app, process: process) - // Re-sign only the changed owners, preserving each bundle's own entitlements and executable stub. - for (original, copy) in [(originalEmbedded, embedded), (containingApp, app)] { - var signing = ["--force", "--sign", "-"] - if let entitlements = try NativePreviewEntitlements.read(from: original).signed { - let plist = directory.appendingPathComponent(copy.lastPathComponent + "-entitlements.plist") - try entitlements.write(to: plist) - signing += ["--entitlements", plist.path] - } - _ = try await process.run("/usr/bin/codesign", signing + [copy.path]) - } - return app - } - - private static func hostedStaticProductCommand(source: NativePreviewBuild.Target, host: NativePreviewBuild.Target, - product: URL, image: URL, installName: String?) throws -> [String] { - guard let executable = host.linkCommandLine.first else { - throw NativeRuntimeError.unsupportedContract("The static preview host has no link command") - } - let directory = product.deletingLastPathComponent().appendingPathComponent("PreviewLink", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let inputs = try host.linkedInputs() - let mergesArchives = try NativePreviewBinary.isStaticArchive(at: product) - var owned = Set((source.objectFiles + [source.outputURL].compactMap { $0 }).map { $0.resolvingSymlinksInPath() }) - // A relocatable link can leave archive members for the host's final link. - for input in try source.linkedInputs().files { - var isDirectory: ObjCBool = false - if unsafe FileManager.default.fileExists(atPath: input.path, isDirectory: &isDirectory), !isDirectory.boolValue, - try (mergesArchives && NativePreviewBinary.isStaticArchive(at: input)) - || NativePreviewBinary.file(at: input)?.header.fileType == .object { - owned.insert(input.resolvingSymlinksInPath()) - } - } - func owns(_ path: String) -> Bool { - host.url(for: path).map { owned.contains($0.resolvingSymlinksInPath()) } ?? false - } - func ownsLibrary(framework: Bool, name: String) -> Bool { - inputs.libraries.contains { $0.framework == framework && $0.name == name - && $0.file.map { owned.contains($0.resolvingSymlinksInPath()) } == true } - } - func encode(_ argument: (value: String, forwarded: Bool), replacing value: String? = nil) -> [String] { - let value = value ?? argument.value - return argument.forwarded ? ["-Xlinker", value] : [value] - } - let arguments = host.linkArguments(in: Array(host.linkCommandLine.dropFirst())) - var result = [executable] - var index = 0 - while index < arguments.count { - let argument = arguments[index] - let next = arguments.indices.contains(index + 1) ? arguments[index + 1] : nil - if ["-o", "-install_name", "-dependency_info", "-object_path_lto", "-map"].contains(argument.value), let next { - let value = argument.value == "-o" ? image.path : argument.value == "-install_name" ? installName ?? next.value - : directory.appendingPathComponent(URL(filePath: next.value).lastPathComponent).path - result += encode(argument) + encode(next, replacing: value) - index += 2 - } else if argument.value == "-filelist", let next, let path = host.url(for: next.value) { - let entries = try String(contentsOf: path, encoding: .utf8).split(whereSeparator: \.isNewline).map(String.init) - let copy = directory.appendingPathComponent("PreviewLinkFileList-\(index).txt") - try (entries.filter { !owns($0) }.joined(separator: "\n") + "\n").write(to: copy, atomically: true, encoding: .utf8) - result += encode(argument) + encode(next, replacing: copy.path) - index += 2 - } else if argument.value == "-force_load", let next, owns(next.value) { - index += 2 - } else if argument.value == "-framework", let next, ownsLibrary(framework: true, name: next.value) { - index += 2 - } else if argument.value == "-l", let next, ownsLibrary(framework: false, name: next.value) { - index += 2 - } else if argument.value.hasPrefix("-l"), ownsLibrary(framework: false, name: String(argument.value.dropFirst(2))) { - index += 1 - } else { - if !owns(argument.value) { result += encode(argument) } - index += 1 - } - } - for path in source.searchPaths(in: source.compileCommandLine) + source.searchPaths(in: source.linkCommandLine) { - result += [path.argument == "-L" ? "-L" : "-F", path.url.path] - } - let sourceArguments = mergesArchives - ? ["-Xlinker", "-force_load", "-Xlinker", product.path] : [product.path] - return result + sourceArguments + ["-Xlinker", "-headerpad_max_install_names"] - } - - static func copyFrameworkDependencies(_ dependencies: FrameworkDependencies, into products: URL) throws { - for (source, path) in dependencies.products { - let destination = products.appendingPathComponent(path) - try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.copyItem(at: source, to: destination) - } - } - - static func relocateFrameworkDependencies(_ dependencies: FrameworkDependencies, in products: URL, - process: NativePreviewProcess) async throws { - var changedFrameworks: Set = [] - for path in Set(dependencies.relocations.map(\.library)).sorted() { - let library = products.appendingPathComponent(path).standardizedFileURL - let arguments = dependencies.relocations.filter { $0.library == path }.flatMap { ["-change", $0.name, $0.replacement] } - _ = try await process.xcrun(["install_name_tool"] + arguments + [library.path]) - _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", library.path]) - if let framework = frameworkBundle(containing: library) { changedFrameworks.insert(framework) } - } - // Nested dylibs can be sealed framework resources; refresh their owning bundle after re-signing the changed code. - for framework in changedFrameworks.sorted(by: { $0.path.count > $1.path.count }) { - _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", framework.path]) - } - } - - @discardableResult - static func prepareApp(product: URL, sourceProduct: URL? = nil, helper: URL, app: URL, containingApp: URL? = nil, - platform: NativePreviewPlatform = .iOS, clientIdentifier: String? = nil, - staticProduct: Bool = false, resourceURLs: [URL] = []) throws -> URL { - let frameworks = platform.frameworksDirectory(in: app) - let products: URL - if let sourceProduct, staticProduct { - products = app.deletingLastPathComponent().appendingPathComponent("Products", isDirectory: true) - .appendingPathComponent(sourceProduct.deletingLastPathComponent().lastPathComponent, isDirectory: true) - } else { products = frameworks } - try FileManager.default.copyItem(at: product, to: app) - let original = try bundleInfo(at: app) - try FileManager.default.createDirectory(at: products, withIntermediateDirectories: true) - if let sourceProduct, sourceProduct.pathExtension == "framework" { - try FileManager.default.copyItem(at: sourceProduct, to: products.appendingPathComponent(sourceProduct.lastPathComponent)) - } - for resource in resourceURLs { - try FileManager.default.copyItem(at: resource, to: products.appendingPathComponent(resource.lastPathComponent)) - } - let executable = helper.appendingPathComponent("XcodeMCPPreviewRenderer") - try copyReplacingItem(executable, to: platform.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer")) - var info = Self.rendererInfo(original, platform: platform) - // The client coexists with the original extension registration. - if let clientIdentifier { info["CFBundleIdentifier"] = clientIdentifier } - try PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0) - .write(to: platform.infoURL(in: app)) - try FileManager.default.createDirectory(at: platform.resourcesDirectory(in: app), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: frameworks, withIntermediateDirectories: true) - if let shared = containingApp.map({ platform.frameworksDirectory(in: $0) }), - FileManager.default.fileExists(atPath: shared.path) { - // Extensions search their own Frameworks before their containing app's. - for item in try FileManager.default.contentsOfDirectory(at: shared, includingPropertiesForKeys: nil) { - let destination = frameworks.appendingPathComponent(item.lastPathComponent) - if !FileManager.default.fileExists(atPath: destination.path) { - try FileManager.default.copyItem(at: item, to: destination) - } - } - } - try copyContents(helper.appendingPathComponent("Frameworks"), to: frameworks) - return products - } - - static func appName(product: URL, containingApp: URL?, localization: String?) throws -> String { - let owner = containingApp ?? product - guard let bundle = Bundle(url: owner) else { throw NativePipelineRequired() } - if let localization { - let info = bundle.infoDictionary ?? [:] - let key = info["CFBundleDisplayName"] is String ? "CFBundleDisplayName" : "CFBundleName" - guard let name = info[key] as? String else { return "" } - return bundle.localizedString(forKey: key, value: name, table: "InfoPlist", - localizations: [Locale.Language(identifier: localization)]) - } - return bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String - ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "" - } - - static func rendererInfo(_ original: [String: Any], platform: NativePreviewPlatform = .iOS) -> [String: Any] { - let startupKeys = ["CFBundleExecutable", "CFBundlePackageType", "NSPrincipalClass", "UIMainStoryboardFile", - "UIApplicationSceneManifest", "NSExtension", "NSMainNibFile", "NSMainStoryboardFile", - "UISupportedInterfaceOrientations"] - // Bundle lookup gives platform/device-qualified keys precedence over base keys. - var info = original.filter { key, _ in - !startupKeys.contains { key == $0 || key.hasPrefix($0 + "-") || key.hasPrefix($0 + "~") } - } - info["CFBundleExecutable"] = "XcodeMCPPreviewRenderer" - info["CFBundlePackageType"] = "APPL" - let minimumKey = platform.isSimulator ? "MinimumOSVersion" : "LSMinimumSystemVersion" - if (info[minimumKey] as? String ?? "").compare(platform.minimumVersion, options: .numeric) == .orderedAscending { - info[minimumKey] = platform.minimumVersion - } - if platform != .macOS && platform != .watchOS { - info["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown", - "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight"] - info["UIApplicationSceneManifest"] = ["UIApplicationSupportsMultipleScenes": false, - "UISceneConfigurations": ["UIWindowSceneSessionRoleApplication": [["UISceneConfigurationName": "Preview", "UISceneDelegateClassName": "XcodeMCPPreviewRenderer.PreviewRendererScene"]]]] - } - if platform == .macOS { info["NSPrincipalClass"] = "NSApplication" } - if platform == .watchOS { - info["WKApplication"] = true - info["WKWatchOnly"] = true - info["WKRunsIndependentlyOfCompanionApp"] = nil - info["WKCompanionAppBundleIdentifier"] = nil - } - return info - } - - private static func copyContents(_ source: URL, to destination: URL) throws { - for item in try FileManager.default.contentsOfDirectory(at: source, includingPropertiesForKeys: nil) { - try copyReplacingItem(item, to: destination.appendingPathComponent(item.lastPathComponent)) - } - } - - private static func copyReplacingItem(_ source: URL, to destination: URL) throws { - if FileManager.default.fileExists(atPath: destination.path) { try FileManager.default.removeItem(at: destination) } - try FileManager.default.copyItem(at: source, to: destination) - } - - private func previewLibraries(in app: URL, platform: NativePreviewPlatform) throws -> [URL] { - let libraries = try FileManager.default.contentsOfDirectory(at: platform.executableDirectory(in: app), includingPropertiesForKeys: nil) - .filter { $0.lastPathComponent.hasSuffix(".debug.dylib") } - guard !libraries.isEmpty else { throw NativePipelineRequired() } - return libraries - } - - static func programLibraries(previewLibraries: [URL], output: URL) throws -> [URL] { - try previewLibraries.filter { try NativePreviewBinary.matches(output, $0) } - } - - static func registryLibraries(in app: URL, previewLibraries: [URL], products: URL? = nil) throws -> [URL] { - var libraries = previewLibraries - libraries += try FileManager.default.contentsOfDirectory(at: Bundle(url: app)?.executableURL?.deletingLastPathComponent() ?? app, includingPropertiesForKeys: nil) - .filter { $0.pathExtension == "dylib" } - let frameworks = Bundle(url: app)?.privateFrameworksURL ?? app.appendingPathComponent("Frameworks", isDirectory: true) - for directory in Set([frameworks] + (products.map { [$0] } ?? [])) { - for subpath in try FileManager.default.subpathsOfDirectory(atPath: directory.path) { - let item = directory.appendingPathComponent(subpath) - if item.pathExtension == "framework" { - if let executable = Bundle(url: item)?.executableURL { libraries.append(executable) } - } else if item.pathExtension == "dylib" { - libraries.append(item) - } - } - } - return Array(Set(libraries.map { $0.resolvingSymlinksInPath() })).sorted { $0.path < $1.path } - } - - static func libraryPaths(in app: URL, previewLibraries: [URL], registryLibraries: [URL], sourceOutput: URL?, - products: URL? = nil) throws -> [String] { - var libraries = previewLibraries - if let sourceOutput, Self.productBundle(containing: sourceOutput) == nil { - let frameworkName = sourceOutput.pathComponents.last(where: { $0.hasSuffix(".framework") }) - if frameworkName != nil || sourceOutput.pathExtension == "dylib", - try !NativePreviewBinary.isStaticArchive(at: sourceOutput) { - guard let sourceLibrary = try registryLibraries.first(where: { library in - guard library.lastPathComponent == sourceOutput.lastPathComponent, - frameworkName.map({ library.pathComponents.contains($0) }) ?? true else { return false } - return try NativePreviewBinary.matches(sourceOutput, library) - }) else { throw NativePipelineRequired() } - libraries.append(sourceLibrary) - } - } - let root = app.resolvingSymlinksInPath() - let products = products?.resolvingSymlinksInPath() - var paths: [String] = [] - for library in libraries { - let library = library.resolvingSymlinksInPath() - var relationship: FileManager.URLRelationship = .other - try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: root, toItemAt: library) - let relative: String - if relationship == .contains { - relative = String(library.path.dropFirst(root.path.count + 1)) - } else if let products { - try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: products, toItemAt: library) - guard relationship == .contains else { throw NativePipelineRequired() } - let operation = root.deletingLastPathComponent() - try unsafe FileManager.default.getRelationship(&relationship, ofDirectoryAt: operation, toItemAt: library) - guard relationship == .contains else { throw NativePipelineRequired() } - relative = "../" + library.path.dropFirst(operation.path.count + 1) - } else { throw NativePipelineRequired() } - if !paths.contains(relative) { paths.append(relative) } - } - return paths - } - - static func registryNames(in symbols: String) -> [String] { - Set(symbols.split(whereSeparator: \.isNewline).compactMap { line -> String? in - let symbol = String(line) - // Names may use mangling substitutions. The renderer checks PreviewRegistry conformance. - guard symbol.hasPrefix("_$s"), symbol.hasSuffix("VMn"), symbol.contains("fMu_") else { return nil } - return String(symbol.dropFirst(3).dropLast(2)) - }).sorted() - } - - static func programRootNames(in symbols: String) -> [String] { - let suffix = "5$mainyyFZ" - return Set(symbols.split(whereSeparator: \.isNewline).compactMap { line -> String? in - let symbol = String(line) - // The renderer checks Widget/WidgetBundle conformance before initializing the program root. - guard symbol.hasPrefix("_$s"), symbol.hasSuffix(suffix) else { return nil } - return String(symbol.dropFirst(3).dropLast(suffix.count)) - }).sorted() - } - private struct Simulator { let identifier: String let destination: [String: JSONValue] @@ -2438,16 +1385,6 @@ final class NativePreviewTool { "systemVersion": .string(destination.systemVersion ?? runtimeID)], deviceType: deviceType) } - private static func bundleInfo(at bundle: URL) throws -> [String: Any] { - let rootInfo = bundle.appendingPathComponent("Info.plist") - let infoURL = FileManager.default.fileExists(atPath: rootInfo.path) ? rootInfo : bundle.appendingPathComponent("Contents/Info.plist") - let data = try Data(contentsOf: infoURL) - guard let info = try unsafe PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { - throw NativeRuntimeError.unsupportedContract("The built preview product has an unsupported Info.plist") - } - return info - } - @MainActor private struct Input { let nativeValue: NativeSwiftValue @@ -2554,8 +1491,3 @@ struct NativePipelineRequired: Error {} // Generic calls supply the native enum's indirect ABI and retained ownership. @inline(never) package func nativePreviewValue(_ value: T) -> T { value } - -private struct PreviewURL: ABIBridgeSwiftValue { - let value: URL - static let swiftABIType: NativeType = try! .opaque(named: "Foundation.URL") -} diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift index bdeb74dc..6a08d783 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift @@ -8,7 +8,7 @@ struct NativePreviewDiscoveryTests { @Test func recognizesRegistryNamesWithMangledWordSubstitutions() { let symbol = "_$s15EmbeddedPreview04$s15a89Preview0024FrameworkViewswift_ynAHffMX12_0_33_11075570A56CB59BAD1AB26CEC639C6ELl0B0fMf_15B12RegistryfMu_VMn" let name = "15EmbeddedPreview04$s15a89Preview0024FrameworkViewswift_ynAHffMX12_0_33_11075570A56CB59BAD1AB26CEC639C6ELl0B0fMf_15B12RegistryfMu_V" - #expect(NativePreviewTool.registryNames(in: symbol) == [name]) + #expect(NativePreviewStaging.registryNames(in: symbol) == [name]) } @Test func discoversProgramRootsFromCompilerMainSymbols() { @@ -22,8 +22,8 @@ struct NativePreviewDiscoveryTests { "_$s\(widgetRoot)VMn", "_main", ].joined(separator: "\n") - #expect(NativePreviewTool.programRootNames(in: symbols) == [appRoot, widgetRoot]) - #expect(NativePreviewTool.programRootNames(in: "_$s\(widgetRoot)VMn") == []) + #expect(NativePreviewStaging.programRootNames(in: symbols) == [appRoot, widgetRoot]) + #expect(NativePreviewStaging.programRootNames(in: "_$s\(widgetRoot)VMn") == []) } @Test func programLibrariesMatchTheBuiltHostImage() async throws { @@ -41,8 +41,8 @@ struct NativePreviewDiscoveryTests { try FileManager.default.copyItem(at: output, to: stagedHost) try FileManager.default.copyItem(at: otherOutput, to: otherLibrary) - #expect(try NativePreviewTool.programLibraries(previewLibraries: [otherLibrary, stagedHost], output: output) == [stagedHost]) - #expect(try NativePreviewTool.programLibraries(previewLibraries: [otherLibrary], output: output) == []) + #expect(try NativePreviewStaging.programLibraries(previewLibraries: [otherLibrary, stagedHost], output: output) == [stagedHost]) + #expect(try NativePreviewStaging.programLibraries(previewLibraries: [otherLibrary], output: output) == []) } @Test func includesEmbeddedFrameworkExecutablesAndDebugLibraries() async throws { @@ -74,16 +74,16 @@ struct NativePreviewDiscoveryTests { try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) .write(to: wrongFramework.appendingPathComponent("Info.plist")) - let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: [preview]) + let libraries = try NativePreviewStaging.registryLibraries(in: app, previewLibraries: [preview]) let expected = [preview, rootDylib, executable, frameworkPreview, dylib, nestedDylib, wrongExecutable] .map { $0.resolvingSymlinksInPath().path } #expect(Set(libraries.map(\.path)) == Set(expected)) - let frameworkPaths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [preview], + let frameworkPaths = try NativePreviewStaging.libraryPaths(in: app, previewLibraries: [preview], registryLibraries: libraries, sourceOutput: sourceOutput) #expect(frameworkPaths == ["FixtureApp.debug.dylib", "Frameworks/FixtureKit.framework/FixtureImplementation"]) - let staticPaths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [preview], + let staticPaths = try NativePreviewStaging.libraryPaths(in: app, previewLibraries: [preview], registryLibraries: libraries, sourceOutput: app.deletingLastPathComponent().appendingPathComponent("FixturePackage.o")) #expect(staticPaths == ["FixtureApp.debug.dylib"]) } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift index a9b9fd81..9ad8f7b5 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift @@ -6,12 +6,12 @@ import Testing struct NativePreviewLocationTests { @Test func unicodePrefixUsesMacroByteCoordinates() throws { let source = "import SwiftUI\n/* 🌸 */ #Preview { Text(\"A\") }\n" - #expect(try NativePreviewTool.registryColumn(in: source, line: 2, utf16Column: 9) == 12) + #expect(try NativePreviewDefinitions.registryColumn(in: source, line: 2, utf16Column: 9) == 12) } @Test func changedSourceCannotUseStaleCoordinates() { #expect(throws: NativeRuntimeError.self) { - try NativePreviewTool.registryColumn(in: "#Preview {}", line: 1, utf16Column: 100) + try NativePreviewDefinitions.registryColumn(in: "#Preview {}", line: 1, utf16Column: 100) } } } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift index b5e4aef8..150b5620 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift @@ -78,7 +78,7 @@ struct NativePreviewToolTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: isRunnable) } - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: platform) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: platform) #expect(selected.source.moduleName == platform.rawValue) #expect(selected.host.moduleName == platform.rawValue) } @@ -90,7 +90,7 @@ struct NativePreviewToolTests { sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", root.appendingPathComponent("Watch.app/Watch.debug.dylib").path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: true) #expect(throws: NativePipelineRequired.self) { - try NativePreviewTool.selectTarget([watch], source: source, platform: .iOS) + try NativePreviewStaging.selectTarget([watch], source: source, platform: .iOS) } } @@ -111,7 +111,7 @@ struct NativePreviewToolTests { buildableName: "SharedPreview.o", sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", library.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false)] : []) - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.moduleName == "RunnableApp") #expect(selected.source.moduleName == (sharedLibrary ? "SharedPreview" : "RunnableApp")) } @@ -134,7 +134,7 @@ struct NativePreviewToolTests { try Data("resource".utf8).write(to: product.appendingPathComponent("Contents/Resources/Marker.txt")) try Data("renderer".utf8).write(to: helper.appendingPathComponent("XcodeMCPPreviewRenderer")) try Data("library".utf8).write(to: helper.appendingPathComponent("Frameworks/libPreview.dylib")) - try NativePreviewTool.prepareApp(product: product, helper: helper, app: app, platform: .macOS) + try NativePreviewStaging.prepareApp(product: product, helper: helper, app: app, platform: .macOS) let info = try #require(Bundle(url: app)?.infoDictionary) #expect(info["CFBundleIdentifier"] as? String == "dev.lynnswap.MacFixture") #expect(info["NSMainStoryboardFile"] == nil) @@ -148,7 +148,7 @@ struct NativePreviewToolTests { @Test func watchRendererRunsWithoutACompanionApp() { let original: [String: Any] = ["CFBundleIdentifier": "dev.lynnswap.WatchFixture", "WKCompanionAppBundleIdentifier": "dev.lynnswap.Companion", "WKRunsIndependentlyOfCompanionApp": true] - let info = NativePreviewTool.rendererInfo(original, platform: .watchOS) + let info = NativePreviewStaging.rendererInfo(original, platform: .watchOS) #expect(info["WKApplication"] as? Bool == true) #expect(info["WKWatchOnly"] as? Bool == true) #expect(info["WKCompanionAppBundleIdentifier"] == nil) @@ -167,7 +167,7 @@ struct NativePreviewToolTests { debugDylibEnabled: true, isRunnable: false) } #expect(throws: NativePipelineRequired.self) { - try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) + try NativePreviewStaging.selectTarget(targets, source: source, platform: .iOS) } } @@ -185,11 +185,11 @@ struct NativePreviewToolTests { linkCommandLine: ["-o", root.appendingPathComponent("FixtureHost.app/FixtureHost.debug.dylib").path, product.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true)] } - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: .iOS) #expect(selected.source.architecture == "arm64") #expect(selected.host.architecture == "arm64") #expect(throws: NativePipelineRequired.self) { - try NativePreviewTool.selectTarget(targets.filter { $0.architecture == "x86_64" }, source: source, platform: .iOS) + try NativePreviewStaging.selectTarget(targets.filter { $0.architecture == "x86_64" }, source: source, platform: .iOS) } } @@ -216,7 +216,7 @@ struct NativePreviewToolTests { try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: dylib, to: binary) } - let selected = try NativePreviewTool.selectTarget(hosts + [feature], source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(hosts + [feature], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == feature.outputURL) #expect(selected.source.moduleName == feature.moduleName) @@ -245,7 +245,7 @@ struct NativePreviewToolTests { try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: frameworkBinary, to: binary) } - let selected = try NativePreviewTool.selectTarget(hosts + [framework], source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(hosts + [framework], source: source, platform: .iOS) #expect(selected.host.outputURL == (embedded ? hosts[1].outputURL : framework.outputURL)) #expect(selected.source.outputURL == framework.outputURL) #expect(selected.source.moduleName == framework.moduleName) @@ -269,7 +269,7 @@ struct NativePreviewToolTests { sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", archive.path], linkerWorkingDirectory: nil, objectFiles: [object], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false) - let selected = try NativePreviewTool.selectTarget(hosts + [package], source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(hosts + [package], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == package.outputURL) #expect(selected.source.moduleName == package.moduleName) @@ -294,7 +294,7 @@ struct NativePreviewToolTests { sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", product.path], linkerWorkingDirectory: nil, objectFiles: [root.appendingPathComponent("PackageContent.o")], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false) - let selected = try NativePreviewTool.selectTarget(hosts + [package], source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(hosts + [package], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == package.outputURL) #expect(selected.source.moduleName == package.moduleName) @@ -354,7 +354,7 @@ struct NativePreviewToolTests { sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", platform.executableDirectory(in: app).appendingPathComponent("Host.debug.dylib").path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true)) } - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: platform) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: platform) #expect(selected.source.moduleName == "FixtureKit") #expect(selected.host.moduleName == (embedded ? "Host" : "FixtureKit")) } @@ -372,7 +372,7 @@ struct NativePreviewToolTests { let app = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: [binary.path, "-o", appImage.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let selected = try NativePreviewTool.selectTarget([framework, app], source: source, platform: .macOS) + let selected = try NativePreviewStaging.selectTarget([framework, app], source: source, platform: .macOS) #expect(selected.source.moduleName == "FixtureKit") #expect(selected.host.moduleName == "FixtureKit") } @@ -434,7 +434,7 @@ struct NativePreviewToolTests { sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: archiveCommand, linkerWorkingDirectory: nil, objectFiles: [core, object, previewObject], sourceFiles: [source, coreSource, previewCode], debugDylibEnabled: false, isRunnable: false, compileCommandLine: compileCommand) - let standalone = try NativePreviewTool.selectTarget([target], source: source, platform: .macOS) + let standalone = try NativePreviewStaging.selectTarget([target], source: source, platform: .macOS) #expect(standalone.host.moduleName == "FixtureKit") let appURL = root.appendingPathComponent("Host.app") let appImage = appURL.appendingPathComponent("Contents/MacOS/Host.debug.dylib") @@ -505,13 +505,13 @@ struct NativePreviewToolTests { try await previewBinaryOutput("/usr/bin/codesign", ["--force", "--sign", "-", appImage.path]) let appSymbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", appImage.path]) #expect(appSymbols.contains("_static_preview_value") == forceLoad) - #expect(!NativePreviewTool.registryNames(in: appSymbols).isEmpty == forceLoad) + #expect(!NativePreviewStaging.registryNames(in: appSymbols).isEmpty == forceLoad) let protectedFiles = [binary, support, appImage, fileList, dependencyInfo, mergedArchive] let originals = try protectedFiles.map { try Data(contentsOf: $0) } let app = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: appCommand, linkerWorkingDirectory: root.path, objectFiles: [appObject, packageObject], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let hosted = try NativePreviewTool.selectTarget([target, app], source: source, platform: .macOS) + let hosted = try NativePreviewStaging.selectTarget([target, app], source: source, platform: .macOS) #expect(hosted.host.moduleName == "Host") #expect(hosted.source.moduleName == "FixtureKit") let helper = root.appendingPathComponent("Helper") @@ -555,19 +555,19 @@ struct NativePreviewToolTests { environment: ["DYLD_LIBRARY_PATH": support.deletingLastPathComponent().path]) #expect(baseline == "dev.lynnswap.StaticHost\nhost resource\n\(appURL.resolvingSymlinksInPath().path)\n") let staged = root.appendingPathComponent("Preview.app") - let products = try NativePreviewTool.prepareApp(product: appURL, helper: helper, app: staged, platform: .macOS, + let products = try NativePreviewStaging.prepareApp(product: appURL, helper: helper, app: staged, platform: .macOS, staticProduct: true) - let linked = try await NativePreviewTool.linkStaticProduct(hosted.source, host: hosted.host, in: staged, products: products, platform: .macOS, process: process) - let dependencies = try NativePreviewTool.frameworkDependencies(for: [hosted.source], targets: [target, app], + let linked = try await NativePreviewStaging.linkStaticProduct(hosted.source, host: hosted.host, in: staged, products: products, platform: .macOS, process: process) + let dependencies = try NativePreviewStaging.frameworkDependencies(for: [hosted.source], targets: [target, app], platform: .macOS, in: products, linkedImages: [try #require(hosted.source.outputURL).resolvingSymlinksInPath(): linked]) - try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) - try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) - let libraries = try NativePreviewTool.registryLibraries(in: staged, previewLibraries: [linked.url]) - let paths = try NativePreviewTool.libraryPaths(in: staged, previewLibraries: [linked.url], registryLibraries: libraries, + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: products) + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: products, process: process) + let libraries = try NativePreviewStaging.registryLibraries(in: staged, previewLibraries: [linked.url]) + let paths = try NativePreviewStaging.libraryPaths(in: staged, previewLibraries: [linked.url], registryLibraries: libraries, sourceOutput: linked.url) #expect(paths == ["Contents/Frameworks/XcodeMCPPreviewSource.dylib"]) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", linked.url.path]) - #expect(!NativePreviewTool.registryNames(in: symbols).isEmpty) + #expect(!NativePreviewStaging.registryNames(in: symbols).isEmpty) _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", staged.path]) _ = try await process.run("/usr/bin/codesign", ["--verify", "--strict", "--deep", staged.path]) let executable = staged.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer") @@ -719,13 +719,13 @@ struct NativePreviewToolTests { } let originalSymbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", image.path]) #expect(!originalSymbols.contains("_static_preview_value")) - #expect(NativePreviewTool.registryNames(in: originalSymbols).isEmpty) + #expect(NativePreviewStaging.registryNames(in: originalSymbols).isEmpty) let baseline = try await process.run(executable.path, []) let files = try #require(FileManager.default.enumerator(at: parent, includingPropertiesForKeys: [.isRegularFileKey])) let protectedFiles = try files.compactMap { $0 as? URL }.filter { try $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true } + [archive, dependency, leaf] let originalBytes = try protectedFiles.map { try Data(contentsOf: $0) } - let staged = try await NativePreviewTool.prepareNativeExtension(source: sourceTarget, host: host, containingApp: parent, + let staged = try await NativePreviewStaging.prepareNativeExtension(source: sourceTarget, host: host, containingApp: parent, in: root.appendingPathComponent("NativePreview"), targets: [sourceTarget, host], platform: .macOS, process: process) let stagedProduct = staged.appendingPathComponent("Contents/PlugIns/Widget.appex") let stagedImage = stagedProduct.appendingPathComponent("Contents/MacOS/Widget.debug.dylib") @@ -758,7 +758,7 @@ struct NativePreviewToolTests { } let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", stagedImage.path]) #expect(symbols.contains("_static_preview_value")) - #expect(!NativePreviewTool.registryNames(in: symbols).isEmpty) + #expect(!NativePreviewStaging.registryNames(in: symbols).isEmpty) #expect(try NativePreviewBinary.dynamicLibrary(at: stagedImage)?.identifier == "@rpath/Widget.debug.dylib") #expect(try NativePreviewBinary.matches(executable, stagedProduct.appendingPathComponent("Contents/MacOS/Widget"))) for bundle in [stagedProduct, staged] { @@ -905,11 +905,11 @@ struct NativePreviewToolTests { let app = root.appendingPathComponent("Staged/Preview.app") let agent = try previewAgent(in: root, helper: helper) try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: false) - let products = try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS, + let products = try NativePreviewStaging.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS, staticProduct: true) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let linked = try await NativePreviewTool.linkStaticProduct(target, in: app, products: products, platform: .macOS, process: process) + let linked = try await NativePreviewStaging.linkStaticProduct(target, in: app, products: products, platform: .macOS, process: process) let image = linked.url let runtime = try await previewBinaryOutput("/usr/bin/xcrun", ["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.asan_osx_dynamic.dylib"]).trimmingCharacters(in: .whitespacesAndNewlines) @@ -917,18 +917,18 @@ struct NativePreviewToolTests { "ASAN_OPTIONS": "color=never:external_symbolizer_path='':abort_on_error=1", "DYLD_INSERT_LIBRARIES": runtime, ] - let dependencies = try NativePreviewTool.frameworkDependencies(for: [target], targets: [target], platform: .macOS, + let dependencies = try NativePreviewStaging.frameworkDependencies(for: [target], targets: [target], platform: .macOS, in: products, linkedImages: [try #require(target.outputURL).resolvingSymlinksInPath(): linked], environment: nativeEnvironment) - try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) - let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: [image], products: products) - let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [image], registryLibraries: libraries, + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: products) + let libraries = try NativePreviewStaging.registryLibraries(in: app, previewLibraries: [image], products: products) + let paths = try NativePreviewStaging.libraryPaths(in: app, previewLibraries: [image], registryLibraries: libraries, sourceOutput: image, products: products) #expect(paths == ["../Products/" + products.lastPathComponent + "/XcodeMCPPreviewSource.dylib"]) - #expect(try NativePreviewTool.programLibraries(previewLibraries: libraries, output: image) == [image.resolvingSymlinksInPath()]) + #expect(try NativePreviewStaging.programLibraries(previewLibraries: libraries, output: image) == [image.resolvingSymlinksInPath()]) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", image.path]).split(whereSeparator: \.isNewline) #expect(symbols.contains("_static_preview_value")) #expect(symbols.contains("_main")) - try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: products, process: process) let stagedExecutable = NativePreviewPlatform.macOS.executableDirectory(in: app).appendingPathComponent(executable.lastPathComponent) let helperIdentifier = try #require(Bundle(url: agent)?.bundleIdentifier) let text = try await process.run(stagedExecutable.path, [app.appendingPathComponent(paths[0]).path], environment: nativeEnvironment) @@ -961,7 +961,7 @@ struct NativePreviewToolTests { try FileManager.default.copyItem(at: app, to: installedApp) try FileManager.default.copyItem(at: products.deletingLastPathComponent(), to: installedApp.deletingLastPathComponent().appendingPathComponent("Products")) - try NativePreviewTool.removeStagedApp(app) + try NativePreviewStaging.removeStagedApp(app) let installedExecutable = NativePreviewPlatform.macOS.executableDirectory(in: installedApp).appendingPathComponent(executable.lastPathComponent) let installedText = try await process.run(installedExecutable.path, [installedApp.appendingPathComponent(paths[0]).path], environment: nativeEnvironment) @@ -976,7 +976,7 @@ struct NativePreviewToolTests { let rebuiltFramework = root.appendingPathComponent("OtherDestination/FixtureKit.framework") try FileManager.default.createDirectory(at: rebuiltFramework.deletingLastPathComponent(), withIntermediateDirectories: false) try FileManager.default.copyItem(at: framework, to: rebuiltFramework) - let refreshedProducts = try NativePreviewTool.prepareApp(product: agent, sourceProduct: rebuiltFramework, helper: helper, app: app, platform: .macOS, + let refreshedProducts = try NativePreviewStaging.prepareApp(product: agent, sourceProduct: rebuiltFramework, helper: helper, app: app, platform: .macOS, staticProduct: true) #expect(!FileManager.default.fileExists(atPath: image.path)) #expect(try Data(contentsOf: refreshedProducts.appendingPathComponent("FixtureKit.framework/FixtureKit")) == original) @@ -1048,7 +1048,7 @@ struct NativePreviewToolTests { let host = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: command, linkerWorkingDirectory: root.path, objectFiles: [sourceObject], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let selection = try NativePreviewTool.selectTarget([dependency, host], source: dependencyObject.appendingPathExtension("c"), platform: .macOS) + let selection = try NativePreviewStaging.selectTarget([dependency, host], source: dependencyObject.appendingPathExtension("c"), platform: .macOS) #expect(selection.source.outputURL == dependencyOutput) #expect(selection.host.outputURL == hostOutput) selectedSource = selection.source @@ -1057,7 +1057,7 @@ struct NativePreviewToolTests { selectedSource = source selectedHost = nil } - let image = try await NativePreviewTool.linkStaticProduct(selectedSource, host: selectedHost, + let image = try await NativePreviewStaging.linkStaticProduct(selectedSource, host: selectedHost, in: root.appendingPathComponent("Staged/Preview.app"), products: products, platform: .macOS, process: process) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-jU", image.url.path]).split(whereSeparator: \.isNewline) @@ -1175,7 +1175,7 @@ struct NativePreviewToolTests { } roots[0].containsPreviewSource = true let source = root.appendingPathComponent("Source.swift") - let selection = try NativePreviewTool.selectTarget(targets, source: source, platform: .macOS) + let selection = try NativePreviewStaging.selectTarget(targets, source: source, platform: .macOS) #expect(selection.source.outputURL == selection.host.outputURL) let originalFiles = try targets.map { try #require($0.outputURL) } + (frameworkSupport ? [privateSupport] : []) let original = try originalFiles.map { try Data(contentsOf: $0) } @@ -1221,17 +1221,17 @@ struct NativePreviewToolTests { let agent = try previewAgent(in: root, helper: helper) let app = root.appendingPathComponent("Staged").appendingPathComponent(agent.lastPathComponent) try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: false) - let products = try NativePreviewTool.prepareApp(product: agent, sourceProduct: selection.source.outputURL, + let products = try NativePreviewStaging.prepareApp(product: agent, sourceProduct: selection.source.outputURL, helper: helper, app: app, platform: .macOS, staticProduct: true, resourceURLs: selection.source.resourceURLs) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let images = try await NativePreviewTool.linkStaticProducts(for: roots, in: app, products: products, + let images = try await NativePreviewStaging.linkStaticProducts(for: roots, in: app, products: products, platform: .macOS, process: process) - let dependencies = try NativePreviewTool.frameworkDependencies(for: roots, targets: targets, platform: .macOS, + let dependencies = try NativePreviewStaging.frameworkDependencies(for: roots, targets: targets, platform: .macOS, in: products, agentApp: app, linkedImages: images) - try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: products) let libraries = dependencies.rootLibraries.map { products.appendingPathComponent($0) } - try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: products, process: process) try await previewBinaryOutput("/usr/bin/codesign", ["--force", "--sign", "-", app.path]) try await previewBinaryOutput("/usr/bin/codesign", ["--verify", "--deep", "--strict", app.path]) let executable = NativePreviewPlatform.macOS.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer") @@ -1319,7 +1319,7 @@ struct NativePreviewToolTests { try FileManager.default.copyItem(at: framework, to: products.appendingPathComponent(framework.lastPathComponent)) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let image = try await NativePreviewTool.linkStaticProduct(target, in: root.appendingPathComponent("Staged/Preview.app"), + let image = try await NativePreviewStaging.linkStaticProduct(target, in: root.appendingPathComponent("Staged/Preview.app"), products: products, platform: platform, process: process).url let linked = try #require(try NativePreviewBinary.dynamicLibrary(at: image)) #expect(linked.dependencies.contains { $0.contains("/iOSSupport/") && $0.contains("/SwiftUI.framework/") }) @@ -1359,7 +1359,7 @@ struct NativePreviewToolTests { try Data("renderer".utf8).write(to: helper.appendingPathComponent("XcodeMCPPreviewRenderer")) let agent = try previewAgent(in: root, helper: helper, platform: platform) - try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: platform) + try NativePreviewStaging.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: platform) let staged = platform.frameworksDirectory(in: app).appendingPathComponent("FixtureKit.framework") let bundle = try #require(Bundle(url: staged)) @@ -1370,10 +1370,10 @@ struct NativePreviewToolTests { let expectedFamilies: [Int]? = platform == .iOS ? [1, 2] : nil #expect(Bundle(url: app)?.infoDictionary?["UIDeviceFamily"] as? [Int] == expectedFamilies) #expect(Bundle(url: app)?.url(forResource: "Marker", withExtension: "txt") == nil) - #expect(try NativePreviewTool.appName(product: framework, containingApp: nil, localization: "ja-JP") == "Framework JA") + #expect(try NativePreviewStaging.appName(product: framework, containingApp: nil, localization: "ja-JP") == "Framework JA") #expect(try Data(contentsOf: platform.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer")) == Data("renderer".utf8)) - let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: []) - let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [], registryLibraries: libraries, sourceOutput: binary) + let libraries = try NativePreviewStaging.registryLibraries(in: app, previewLibraries: []) + let paths = try NativePreviewStaging.libraryPaths(in: app, previewLibraries: [], registryLibraries: libraries, sourceOutput: binary) #expect(paths == [String(staged.appendingPathComponent(relativeBinary).path.dropFirst(app.path.count + 1))]) #expect(try String(contentsOf: resources.appendingPathComponent("Marker.txt"), encoding: .utf8) == "framework resource") } @@ -1466,7 +1466,7 @@ struct NativePreviewToolTests { if kind == .absoluteBuilt { targets.append(target(library)) } let helper = root.appendingPathComponent("Helper") let app = root.appendingPathComponent("Preview.app") - let dependencies = try NativePreviewTool.frameworkDependencies(for: [sourceTarget], targets: targets, platform: .macOS, + let dependencies = try NativePreviewStaging.frameworkDependencies(for: [sourceTarget], targets: targets, platform: .macOS, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), sourceProduct: source.deletingLastPathComponent()) try FileManager.default.createDirectory(at: helper.appendingPathComponent("Frameworks"), withIntermediateDirectories: true) let loaderSource = root.appendingPathComponent("Loader.c") @@ -1478,26 +1478,26 @@ struct NativePreviewToolTests { try await previewBinaryOutput(helper.appendingPathComponent("XcodeMCPPreviewRenderer").path, [source.path]) } let agent = try previewAgent(in: root, helper: helper) - try NativePreviewTool.prepareApp(product: agent, sourceProduct: source.deletingLastPathComponent(), helper: helper, app: app, + try NativePreviewStaging.prepareApp(product: agent, sourceProduct: source.deletingLastPathComponent(), helper: helper, app: app, platform: .macOS) - try NativePreviewTool.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) let developerDirectory = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]) .trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developerDirectory)), artifacts: root) let frameworks = app.appendingPathComponent("Contents/Frameworks") - let stagedLibraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: []) + let stagedLibraries = try NativePreviewStaging.registryLibraries(in: app, previewLibraries: []) for binary in originalBinaries { #expect(try stagedLibraries.contains { try NativePreviewBinary.matches(binary, $0) }) } #expect(try !stagedLibraries.contains { try NativePreviewBinary.matches(unrelated, $0) }) - let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [], + let paths = try NativePreviewStaging.libraryPaths(in: app, previewLibraries: [], registryLibraries: stagedLibraries, sourceOutput: source) #expect(paths == ["Contents/Frameworks/Feature.framework/Feature"]) let dependencyPath = try #require(dependencies.products[dependencyAlias.deletingLastPathComponent().resolvingSymlinksInPath()]) let stagedDependency = try #require(Bundle(url: frameworks.appendingPathComponent(dependencyPath))) let stagedMarker = try #require(stagedDependency.url(forResource: "Marker", withExtension: "txt")) #expect(try String(contentsOf: stagedMarker, encoding: .utf8) == "dependency resource") - try await NativePreviewTool.relocateFrameworkDependencies(dependencies, + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), process: process) try await previewBinaryOutput(app.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer").path, [frameworks.appendingPathComponent("Feature.framework/Feature").path]) @@ -1530,7 +1530,7 @@ struct NativePreviewToolTests { linkerWorkingDirectory: root.path, objectFiles: [], sourceFiles: [], debugDylibEnabled: false, isRunnable: false) let helper = root.appendingPathComponent("Helper") let app = root.appendingPathComponent("Preview.app") - let dependencies = try NativePreviewTool.frameworkDependencies(for: [target], targets: [target], platform: .macOS, + let dependencies = try NativePreviewStaging.frameworkDependencies(for: [target], targets: [target], platform: .macOS, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), sourceProduct: framework) try FileManager.default.createDirectory(at: helper.appendingPathComponent("Frameworks"), withIntermediateDirectories: true) let loaderSource = root.appendingPathComponent("Loader.c") @@ -1543,13 +1543,13 @@ struct NativePreviewToolTests { try await previewBinaryOutput(helper.appendingPathComponent("XcodeMCPPreviewRenderer").path, [source.path]) let agent = try previewAgent(in: root, helper: helper) - try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS) - try NativePreviewTool.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) + try NativePreviewStaging.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS) + try NativePreviewStaging.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) let developerDirectory = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]) .trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developerDirectory)), artifacts: root) - try await NativePreviewTool.relocateFrameworkDependencies(dependencies, + try await NativePreviewStaging.relocateFrameworkDependencies(dependencies, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), process: process) try await previewBinaryOutput(app.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer").path, @@ -1577,7 +1577,7 @@ struct NativePreviewToolTests { linkCommandLine: ["-o", library.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false)] : []) - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.outputURL == target.outputURL) #expect(selected.source.moduleName == (linkedLibrary ? "ExtensionPreview" : "Extension")) } @@ -1592,7 +1592,7 @@ struct NativePreviewToolTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: product == "Host.app") } - let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewStaging.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.outputURL == targets[1].outputURL) #expect(selected.source.outputURL == targets[1].outputURL) } @@ -1617,9 +1617,9 @@ struct NativePreviewToolTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: name != "Unselected") } - #expect(try NativePreviewTool.containingApp(for: output, targets: hosts)?.path + #expect(try NativePreviewStaging.containingApp(for: output, targets: hosts)?.path == root.appendingPathComponent("Matching.app").path) - #expect(try NativePreviewTool.containingApp(for: output, targets: [hosts[0]]) == nil) + #expect(try NativePreviewStaging.containingApp(for: output, targets: [hosts[0]]) == nil) } @Test(arguments: [false, true]) @@ -1649,7 +1649,7 @@ struct NativePreviewToolTests { try originalInfo.write(to: product.appendingPathComponent("Info.plist")) let clientIdentifier = nativeClient ? "dev.lynnswap.PreviewClient" : nil - try NativePreviewTool.prepareApp(product: product, helper: helper, app: app, containingApp: containing, + try NativePreviewStaging.prepareApp(product: product, helper: helper, app: app, containingApp: containing, clientIdentifier: clientIdentifier) #expect(try Data(contentsOf: app.appendingPathComponent("Assets.car")) == resource) @@ -1690,7 +1690,7 @@ struct NativePreviewToolTests { .write(to: localization.appendingPathComponent("InfoPlist.strings")) } - let name = try NativePreviewTool.appName(product: product, containingApp: hasContainingApp ? parent : nil, + let name = try NativePreviewStaging.appName(product: product, containingApp: hasContainingApp ? parent : nil, localization: "ja-JP") #expect(name == (hasContainingApp ? "Parent JA" : "Extension JA")) } @@ -1718,7 +1718,7 @@ struct NativePreviewToolTests { try PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0) .write(to: product.appendingPathComponent("Info.plist")) - try NativePreviewTool.prepareApp(product: product, helper: helper, app: app) + try NativePreviewStaging.prepareApp(product: product, helper: helper, app: app) #expect(try Data(contentsOf: app.appendingPathComponent("XcodeMCPPreviewRenderer")) == rendererExecutable) #expect(try Data(contentsOf: app.appendingPathComponent("Frameworks/libPreviewRuntime.dylib")) == rendererFramework) @@ -1753,7 +1753,7 @@ struct NativePreviewToolTests { "UIAppFonts": ["FixtureFont.otf"], "FixtureCustom": ["environment": "staging"], ] - let output = NativePreviewTool.rendererInfo(input) + let output = NativePreviewStaging.rendererInfo(input) #expect(output["CFBundleExecutable"] as? String == "XcodeMCPPreviewRenderer") #expect(output["CFBundlePackageType"] as? String == "APPL")