From d4acd833436d705579a66e0e0a321381609a8f8d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 8 Oct 2026 00:26:54 -0300 Subject: [PATCH 1/4] feat(ios): embed dynamic SwiftPM products with `embed` A Swift package product declared `.library(type: .dynamic)` was linked into the target's Frameworks phase but never copied into the app bundle. Debug simulator builds still ran because Xcode adds an absolute LC_RPATH to the build directory's PackageFrameworks folder; device and archive builds crashed in dyld at launch with "Library not loaded: @rpath/.framework/". Xcode records a dynamic package product added through "Frameworks, Libraries, and Embedded Content" twice: once in the Frameworks phase and once in the "Embed Frameworks" copy phase with CodeSignOnCopy. The CLI only ever wrote the first entry. `IosSPMPackageBase` gains `embed?: string[]`, the subset of `libs` to copy into the bundle. For each, the pbxproj service writes a second PBXBuildFile for the same productRef into the target's own "Embed Frameworks" copy phase (dstSubfolderSpec 10), creating the phase when the target has none. Entries are keyed on productRef so re-applying on every prepare stays idempotent. An embed entry that is not in `libs` is warned about and skipped. The option is opt-in: the CLI cannot tell a static product from a dynamic one without parsing Package.swift, and embedding a static product's placeholder breaks the build. The existing post-build architecture strip already walks the bundle's Frameworks folder, so embedded package frameworks get the same treatment as plugin frameworks. --- lib/definitions/ios.d.ts | 7 + lib/definitions/project.d.ts | 10 ++ lib/services/ios/spm-pbxproj-service.ts | 83 ++++++++++ test/services/ios/spm-pbxproj-service.ts | 198 ++++++++++++++++++++--- 4 files changed, 275 insertions(+), 23 deletions(-) diff --git a/lib/definitions/ios.d.ts b/lib/definitions/ios.d.ts index 08c67db5c7..09c0777636 100644 --- a/lib/definitions/ios.d.ts +++ b/lib/definitions/ios.d.ts @@ -50,6 +50,13 @@ declare global { * extensions...) list their names here to link the package with them too. */ targets?: string[]; + /** + * Products built as dynamic libraries (`.library(type: .dynamic)`) must + * also be copied into the app bundle. Lists the subset of `libs` to + * embed; a dynamic product that is linked but not embedded fails in dyld + * at launch on devices. + */ + embed?: string[]; } /** A package resolved from a git remote at a version, range, branch or revision. */ diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index 032b27e3e5..e02070a173 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -111,6 +111,16 @@ interface IOSSPMPackageBase { * you can list their names here to include the Swift Package with them */ targets?: string[]; + /** + * Optional: products built as dynamic libraries (`.library(type: .dynamic)`) + * must also be copied into the app bundle. List the subset of `libs` to + * embed; a dynamic product that is linked but not embedded builds fine but + * fails in dyld at launch on a device. + * + * A `.library(...)` without a type is static and is compiled into the app + * executable, so it needs no embedding. + */ + embed?: string[]; } export interface IOSRemoteSPMPackage extends IOSSPMPackageBase { diff --git a/lib/services/ios/spm-pbxproj-service.ts b/lib/services/ios/spm-pbxproj-service.ts index 0ab41f868c..8ccc836042 100644 --- a/lib/services/ios/spm-pbxproj-service.ts +++ b/lib/services/ios/spm-pbxproj-service.ts @@ -17,6 +17,11 @@ import { IFileSystem } from "../../common/declarations"; * 4. an entry in the target's Frameworks build phase, plus the target's * `packageProductDependencies`. * + * A product listed in `embed` additionally gets a second `PBXBuildFile` in the + * target's "Embed Frameworks" copy phase, which is how Xcode itself records a + * dynamic package product added through "Frameworks, Libraries, and Embedded + * Content" — linking alone leaves the framework out of the app bundle. + * * Every entry is keyed by its pbxproj comment (e.g. `XCRemoteSwiftPackageReference * "Auth0"`), and an existing entry is updated in place rather than duplicated — * so applying the same set of packages repeatedly (which the CLI does on every @@ -200,6 +205,26 @@ export class SPMPbxprojService implements ISPMPbxprojService { comment: packageReferenceComment, }); + const embedLibs = new Set(); + for (const lib of pkg.embed ?? []) { + if (pkg.libs?.includes(lib)) { + embedLibs.add(lib); + } else { + this.$logger.warn( + `SPM: package "${pkg.name}" lists "${lib}" in embed but not in libs — only linked products can be embedded; skipping.`, + ); + } + } + let embedBuildPhaseFiles: any[] | null = null; + if (embedLibs.size) { + const embedBuildPhaseObj = this.findOrCreateEmbedFrameworksBuildPhase( + project, + target, + targetId, + ); + embedBuildPhaseFiles = embedBuildPhaseObj["files"] ??= []; + } + for (const lib of pkg.libs ?? []) { // The comment is just the product name, which two different packages // can share (e.g. both exposing a "Core" lib) — so entries here are @@ -245,6 +270,29 @@ export class SPMPbxprojService implements ISPMPbxprojService { value: spmBuildFileUuid, comment: libComment, }); + + if (!embedLibs.has(lib)) { + continue; + } + + const embedComment = `${lib} in Embed Frameworks`; + const { uuid: spmEmbedBuildFileUuid } = this.addOrUpdateEntry( + project, + "PBXBuildFile", + embedComment, + { + isa: "PBXBuildFile", + productRef: spmProductDependencyUUID, + productRef_comment: lib, + settings: { ATTRIBUTES: ["CodeSignOnCopy"] }, + }, + (existing) => existing.productRef === spmProductDependencyUUID, + ); + + this.addOrUpdateArrayEntry(embedBuildPhaseFiles, spmEmbedBuildFileUuid, { + value: spmEmbedBuildFileUuid, + comment: embedComment, + }); } return true; @@ -263,6 +311,41 @@ export class SPMPbxprojService implements ISPMPbxprojService { return null; } + /** + * Finds the "Embed Frameworks" copy phase listed in this target's own + * buildPhases, creating one when the target has none. Matched on the + * destination (`dstSubfolderSpec` 10 is the bundle's Frameworks folder) + * rather than the name alone, so a copy phase that merely shares the name + * but copies elsewhere is not mistaken for it. + */ + private findOrCreateEmbedFrameworksBuildPhase( + project: any, + target: any, + targetId: string, + ): any { + const section = + project.hash.project.objects["PBXCopyFilesBuildPhase"] ?? {}; + for (const phase of target.buildPhases ?? []) { + const phaseObj = section[phase.value]; + if ( + phaseObj && + String(phaseObj.dstSubfolderSpec) === "10" && + (phaseObj.name === "Embed Frameworks" || + phaseObj.name === '"Embed Frameworks"') + ) { + return phaseObj; + } + } + + return project.addBuildPhase( + [], + "PBXCopyFilesBuildPhase", + "Embed Frameworks", + targetId, + "frameworks", + ).buildPhase; + } + /** Replaces a matching array entry in place, or appends it. */ private addOrUpdateArrayEntry( array: any[], diff --git a/test/services/ios/spm-pbxproj-service.ts b/test/services/ios/spm-pbxproj-service.ts index 44a1f6a7eb..5f86a70666 100644 --- a/test/services/ios/spm-pbxproj-service.ts +++ b/test/services/ios/spm-pbxproj-service.ts @@ -21,6 +21,8 @@ const TARGET_NAME = "TNSBlank"; // its PBXFrameworksBuildPhase uuid in that fixture (a group is also named // "Frameworks", so tests that strip the phase must key on the uuid) const FRAMEWORKS_PHASE_ID = "858B83F418CA22B800AB12DE"; +// its "Embed Frameworks" PBXCopyFilesBuildPhase uuid in that fixture +const EMBED_PHASE_ID = "85F5BDFC1A9363BE006B9701"; const remotePackage: IosSPMPackage = { name: "swift-numerics", @@ -35,6 +37,13 @@ const localPackage: IosSPMPackage = { path: "vendor/LocalPkg", }; +const dynamicPackage: IosSPMPackage = { + name: "DynamicPkg", + libs: ["DynamicProduct", "StaticProduct"], + embed: ["DynamicProduct"], + path: "vendor/DynamicPkg", +}; + let warnings: string[] = []; function createTestInjector(): IInjector { @@ -74,6 +83,55 @@ function countOccurrences(contents: string, needle: string): number { return contents.split(needle).length - 1; } +/** Removes a build phase from the fixture target: its section entry and its slot in buildPhases. */ +function stripBuildPhase(projectRoot: string, phaseId: string, name: string) { + const pbxPath = path.join( + projectRoot, + `${TARGET_NAME}.xcodeproj`, + "project.pbxproj", + ); + const stripped = readFileSync(pbxPath, "utf8") + .replace(new RegExp(`^\\s*${phaseId} /\\* ${name} \\*/,\\n`, "m"), "") + .replace( + new RegExp( + `^\\s*${phaseId} /\\* ${name} \\*/ = \\{[\\s\\S]*?\\};\\n`, + "m", + ), + "", + ); + writeFileSync(pbxPath, stripped); +} + +function parsePbxproj(projectRoot: string): any { + const xcode = require("nativescript-dev-xcode"); + const project = new xcode.project( + path.join(projectRoot, `${TARGET_NAME}.xcodeproj`, "project.pbxproj"), + ); + project.parseSync(); + return project; +} + +/** The uuids of the build files in the fixture target's "Embed Frameworks" phase. */ +function embedPhaseFileUuids(project: any): string[] { + const targets = project.pbxNativeTargetSection(); + const target = + targets[ + Object.keys(targets).find( + (key) => !key.endsWith("_comment") && targets[key].name === TARGET_NAME, + ) + ]; + const copyPhases = project.hash.project.objects["PBXCopyFilesBuildPhase"]; + const embedPhases = (target.buildPhases as any[]) + .map((phase) => copyPhases[phase.value]) + .filter((phase) => phase && String(phase.dstSubfolderSpec) === "10"); + assert.lengthOf( + embedPhases, + 1, + "the target should have exactly one Embed Frameworks phase", + ); + return (embedPhases[0].files ?? []).map((file: any) => file.value); +} + describe("SPMPbxprojService", () => { let service: ISPMPbxprojService; let projectRoot: string; @@ -246,29 +304,7 @@ describe("SPMPbxprojService", () => { }); it("skips a target without a Frameworks build phase, warns, and writes nothing", () => { - // strip the Frameworks build phase from the fixture target — both the - // section entry and its slot in the target's buildPhases - const pbxPath = path.join( - projectRoot, - `${TARGET_NAME}.xcodeproj`, - "project.pbxproj", - ); - const stripped = readFileSync(pbxPath, "utf8") - .replace( - new RegExp( - `^\\s*${FRAMEWORKS_PHASE_ID} /\\* Frameworks \\*/,\\n`, - "m", - ), - "", - ) - .replace( - new RegExp( - `^\\s*${FRAMEWORKS_PHASE_ID} /\\* Frameworks \\*/ = \\{[\\s\\S]*?\\};\\n`, - "m", - ), - "", - ); - writeFileSync(pbxPath, stripped); + stripBuildPhase(projectRoot, FRAMEWORKS_PHASE_ID, "Frameworks"); const result = service.addPackages(projectRoot, [ { targetName: TARGET_NAME, package: remotePackage }, @@ -331,6 +367,122 @@ describe("SPMPbxprojService", () => { ); }); + describe("embed", () => { + it("copies an embedded product into the Embed Frameworks phase with CodeSignOnCopy, and still links it", () => { + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + ]), + ); + + const contents = readPbxproj(projectRoot); + assert.include(contents, "DynamicProduct in Frameworks"); + assert.include(contents, "DynamicProduct in Embed Frameworks"); + assert.match( + contents, + /DynamicProduct in Embed Frameworks \*\/ = \{[^}]*settings = \{ATTRIBUTES = \(CodeSignOnCopy, \); \};/, + "the embed build file should carry the CodeSignOnCopy attribute", + ); + assert.include(contents, "StaticProduct in Frameworks"); + assert.notInclude( + contents, + "StaticProduct in Embed Frameworks", + "a product not listed in embed must only be linked", + ); + + const project = parsePbxproj(projectRoot); + const buildFiles = project.hash.project.objects["PBXBuildFile"]; + const embeddedUuids = embedPhaseFileUuids(project); + assert.lengthOf(embeddedUuids, 1); + assert.equal( + buildFiles[`${embeddedUuids[0]}_comment`], + "DynamicProduct in Embed Frameworks", + ); + assert.deepEqual(buildFiles[embeddedUuids[0]].settings, { + ATTRIBUTES: ["CodeSignOnCopy"], + }); + + // link and embed entries are distinct build files for the same product + const productRefs = Object.keys(buildFiles) + .filter((key) => !key.endsWith("_comment")) + .map((key) => buildFiles[key]) + .filter((file) => file.productRef_comment === "DynamicProduct") + .map((file) => file.productRef); + assert.lengthOf(productRefs, 2); + assert.equal(new Set(productRefs).size, 1); + }); + + it("is idempotent — reapplying an embedded package does not duplicate the embed entry", () => { + const assignments: IosSPMPackageAssignment[] = [ + { targetName: TARGET_NAME, package: dynamicPackage }, + ]; + + assert.isTrue(service.addPackages(projectRoot, assignments)); + const afterFirst = readPbxproj(projectRoot); + assert.isTrue(service.addPackages(projectRoot, assignments)); + const afterSecond = readPbxproj(projectRoot); + + assert.equal(afterSecond, afterFirst); + assert.equal( + countOccurrences( + afterSecond, + "DynamicProduct in Embed Frameworks */ = {", + ), + 1, + ); + assert.lengthOf(embedPhaseFileUuids(parsePbxproj(projectRoot)), 1); + }); + + it("creates the Embed Frameworks phase when the target has none", () => { + stripBuildPhase(projectRoot, EMBED_PHASE_ID, "Embed Frameworks"); + assert.notInclude(readPbxproj(projectRoot), "Embed Frameworks"); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + ]), + ); + + const contents = readPbxproj(projectRoot); + assert.include(contents, 'name = "Embed Frameworks";'); + assert.include(contents, "dstSubfolderSpec = 10;"); + assert.lengthOf(embedPhaseFileUuids(parsePbxproj(projectRoot)), 1); + }); + + it("does not create an Embed Frameworks phase for a package that embeds nothing", () => { + stripBuildPhase(projectRoot, EMBED_PHASE_ID, "Embed Frameworks"); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: remotePackage }, + ]), + ); + + assert.notInclude(readPbxproj(projectRoot), "Embed Frameworks"); + }); + + it("warns about an embed entry that is not a linked lib, and skips it", () => { + assert.isTrue( + service.addPackages(projectRoot, [ + { + targetName: TARGET_NAME, + package: { ...dynamicPackage, embed: ["NotLinked"] }, + }, + ]), + ); + + assert.isTrue( + warnings.some( + (w) => w.includes("NotLinked") && w.includes("not in libs"), + ), + `expected a warning naming the unlinked product, got: ${warnings}`, + ); + const contents = readPbxproj(projectRoot); + assert.notInclude(contents, "in Embed Frameworks"); + assert.include(contents, "DynamicProduct in Frameworks"); + }); + }); + it("quotes requirement values a pbxproj cannot hold bare", () => { assert.isTrue( service.addPackages(projectRoot, [ From f41fcaad2e98e9ab7b45dbeb1c50ba23a54e16f9 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 3 Dec 2026 12:31:39 -0800 Subject: [PATCH 2/4] fix(ios): link embedded SwiftPM products into extensions without embedding A package listed with `targets` is applied to each of those targets with the same config, so `embed` also copied the framework into widget and other app extension bundles. App Store validation rejects frameworks embedded in an extension (ITMS-90206); extensions load them from the host app's Frameworks folder through their `@executable_path/../../Frameworks` runpath. Extension targets now only link products listed in `embed`. --- lib/definitions/ios.d.ts | 3 +- lib/definitions/project.d.ts | 3 +- lib/services/ios/spm-pbxproj-service.ts | 23 +++++++++-- test/services/ios/spm-pbxproj-service.ts | 50 ++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/lib/definitions/ios.d.ts b/lib/definitions/ios.d.ts index 09c0777636..c4d037f688 100644 --- a/lib/definitions/ios.d.ts +++ b/lib/definitions/ios.d.ts @@ -54,7 +54,8 @@ declare global { * Products built as dynamic libraries (`.library(type: .dynamic)`) must * also be copied into the app bundle. Lists the subset of `libs` to * embed; a dynamic product that is linked but not embedded fails in dyld - * at launch on devices. + * at launch on devices. Extension `targets` only link these products and + * load them from the app's bundle. */ embed?: string[]; } diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index e02070a173..a2fbddc980 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -115,7 +115,8 @@ interface IOSSPMPackageBase { * Optional: products built as dynamic libraries (`.library(type: .dynamic)`) * must also be copied into the app bundle. List the subset of `libs` to * embed; a dynamic product that is linked but not embedded builds fine but - * fails in dyld at launch on a device. + * fails in dyld at launch on a device. Extensions listed in `targets` only + * link these products and load them from the app's bundle. * * A `.library(...)` without a type is static and is compiled into the app * executable, so it needs no embedding. diff --git a/lib/services/ios/spm-pbxproj-service.ts b/lib/services/ios/spm-pbxproj-service.ts index 8ccc836042..ccbea3bd11 100644 --- a/lib/services/ios/spm-pbxproj-service.ts +++ b/lib/services/ios/spm-pbxproj-service.ts @@ -3,6 +3,16 @@ import * as semver from "semver"; import { injector } from "../../common/yok"; import { IFileSystem } from "../../common/declarations"; +/** + * Extensions (widgets, watch extensions, ...) load embedded frameworks from the + * host app's Frameworks folder through their `@executable_path/../../Frameworks` + * runpath; App Store validation rejects a framework copied into an extension's + * own bundle (ITMS-90206). + */ +function isExtensionTarget(target: any): boolean { + return /extension/.test(String(target?.productType ?? "")); +} + /** * Writes Swift Package references directly into an Xcode project's pbxproj. * @@ -18,9 +28,10 @@ import { IFileSystem } from "../../common/declarations"; * `packageProductDependencies`. * * A product listed in `embed` additionally gets a second `PBXBuildFile` in the - * target's "Embed Frameworks" copy phase, which is how Xcode itself records a - * dynamic package product added through "Frameworks, Libraries, and Embedded - * Content" — linking alone leaves the framework out of the app bundle. + * "Embed Frameworks" copy phase of each non-extension target, which is how + * Xcode itself records a dynamic package product added through "Frameworks, + * Libraries, and Embedded Content" — linking alone leaves the framework out of + * the app bundle. * * Every entry is keyed by its pbxproj comment (e.g. `XCRemoteSwiftPackageReference * "Auth0"`), and an existing entry is updated in place rather than duplicated — @@ -215,6 +226,12 @@ export class SPMPbxprojService implements ISPMPbxprojService { ); } } + if (embedLibs.size && isExtensionTarget(target)) { + this.$logger.trace( + `SPM: linking ${[...embedLibs].join(", ")} into extension target ${target.name} without embedding; it loads them from the host app's bundle.`, + ); + embedLibs.clear(); + } let embedBuildPhaseFiles: any[] | null = null; if (embedLibs.size) { const embedBuildPhaseObj = this.findOrCreateEmbedFrameworksBuildPhase( diff --git a/test/services/ios/spm-pbxproj-service.ts b/test/services/ios/spm-pbxproj-service.ts index 5f86a70666..64c3794c3a 100644 --- a/test/services/ios/spm-pbxproj-service.ts +++ b/test/services/ios/spm-pbxproj-service.ts @@ -111,6 +111,23 @@ function parsePbxproj(projectRoot: string): any { return project; } +/** Adds an app extension target with its own Frameworks phase to the fixture, returning its uuid. */ +function addExtensionTarget(projectRoot: string, name: string): string { + const project = parsePbxproj(projectRoot); + const target = project.addTarget(name, "app_extension", name); + project.addBuildPhase( + [], + "PBXFrameworksBuildPhase", + "Frameworks", + target.uuid, + ); + writeFileSync( + path.join(projectRoot, `${TARGET_NAME}.xcodeproj`, "project.pbxproj"), + project.writeSync(), + ); + return target.uuid; +} + /** The uuids of the build files in the fixture target's "Embed Frameworks" phase. */ function embedPhaseFileUuids(project: any): string[] { const targets = project.pbxNativeTargetSection(); @@ -461,6 +478,39 @@ describe("SPMPbxprojService", () => { assert.notInclude(readPbxproj(projectRoot), "Embed Frameworks"); }); + it("links an embedded product into an extension target without embedding it there", () => { + const extensionId = addExtensionTarget(projectRoot, "Widget"); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + { targetName: "Widget", package: dynamicPackage }, + ]), + ); + + const project = parsePbxproj(projectRoot); + assert.lengthOf(embedPhaseFileUuids(project), 1); + + const extension = project.pbxNativeTargetSection()[extensionId]; + const phaseIds = (extension.buildPhases as any[]).map( + (phase) => phase.value, + ); + const objects = project.hash.project.objects; + assert.isFalse( + phaseIds.some((id) => objects["PBXCopyFilesBuildPhase"]?.[id]), + "an extension target must not get a copy phase for package products", + ); + const linked = phaseIds + .map((id) => objects["PBXFrameworksBuildPhase"]?.[id]) + .filter(Boolean) + .flatMap((phase: any) => phase.files ?? []) + .map((file: any) => file.comment); + assert.includeMembers(linked, [ + "DynamicProduct in Frameworks", + "StaticProduct in Frameworks", + ]); + }); + it("warns about an embed entry that is not a linked lib, and skips it", () => { assert.isTrue( service.addPackages(projectRoot, [ From 8bbb03ff47202a2443bb894216a75cd86d0110bd Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 3 Dec 2026 13:03:18 -0800 Subject: [PATCH 3/4] fix(ios): embed SwiftPM products only into targets that host frameworks Embedding is limited to apps, App Clips and WatchKit extensions (which hold a watchOS 2 app's code). Framework targets, such as watch folder modules, now only link, like app extensions: a framework nested in another framework fails validation. A package that lists `embed` but reaches only link-only targets in a batch is warned about, since nothing would copy its products into the bundle that hosts them. A product removed from `embed` loses its copy entry on the next prepare, while a build file another target still lists is kept. Products without an explicit type use automatic linkage rather than being guaranteed static; the `embed` docs say so. --- lib/definitions/ios.d.ts | 4 +- lib/definitions/project.d.ts | 9 +- lib/services/ios/spm-pbxproj-service.ts | 98 ++++++++++++++--- test/services/ios/spm-pbxproj-service.ts | 130 ++++++++++++++++++++++- 4 files changed, 219 insertions(+), 22 deletions(-) diff --git a/lib/definitions/ios.d.ts b/lib/definitions/ios.d.ts index c4d037f688..6500fdb354 100644 --- a/lib/definitions/ios.d.ts +++ b/lib/definitions/ios.d.ts @@ -54,8 +54,8 @@ declare global { * Products built as dynamic libraries (`.library(type: .dynamic)`) must * also be copied into the app bundle. Lists the subset of `libs` to * embed; a dynamic product that is linked but not embedded fails in dyld - * at launch on devices. Extension `targets` only link these products and - * load them from the app's bundle. + * at launch on devices. App extensions and frameworks listed in `targets` + * only link these products and load them from the app's bundle. */ embed?: string[]; } diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index a2fbddc980..bdbaab528a 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -115,11 +115,12 @@ interface IOSSPMPackageBase { * Optional: products built as dynamic libraries (`.library(type: .dynamic)`) * must also be copied into the app bundle. List the subset of `libs` to * embed; a dynamic product that is linked but not embedded builds fine but - * fails in dyld at launch on a device. Extensions listed in `targets` only - * link these products and load them from the app's bundle. + * fails in dyld at launch on a device. App extensions and frameworks listed + * in `targets` only link these products and load them from the app's bundle. * - * A `.library(...)` without a type is static and is compiled into the app - * executable, so it needs no embedding. + * A `.library(...)` without a type uses automatic linkage, which Xcode links + * statically into the target, so it needs no embedding; list only products + * declared `type: .dynamic`. */ embed?: string[]; } diff --git a/lib/services/ios/spm-pbxproj-service.ts b/lib/services/ios/spm-pbxproj-service.ts index ccbea3bd11..7c9054d0e9 100644 --- a/lib/services/ios/spm-pbxproj-service.ts +++ b/lib/services/ios/spm-pbxproj-service.ts @@ -4,13 +4,22 @@ import { injector } from "../../common/yok"; import { IFileSystem } from "../../common/declarations"; /** - * Extensions (widgets, watch extensions, ...) load embedded frameworks from the - * host app's Frameworks folder through their `@executable_path/../../Frameworks` - * runpath; App Store validation rejects a framework copied into an extension's - * own bundle (ITMS-90206). + * Target types whose bundle carries its own Frameworks folder. App extensions + * and frameworks only link: they load embedded frameworks from the bundle that + * hosts them, and App Store validation rejects frameworks nested in an app + * extension (ITMS-90206) or another framework. A watchOS 2 app keeps its code, + * and so its frameworks, in its WatchKit extension. */ -function isExtensionTarget(target: any): boolean { - return /extension/.test(String(target?.productType ?? "")); +const EMBEDDING_PRODUCT_TYPES = new Set([ + "com.apple.product-type.application", + "com.apple.product-type.application.on-demand-install-capable", + "com.apple.product-type.watchkit2-extension", +]); + +function canEmbedFrameworks(target: any): boolean { + return EMBEDDING_PRODUCT_TYPES.has( + String(target?.productType ?? "").replace(/^"|"$/g, ""), + ); } /** @@ -28,10 +37,10 @@ function isExtensionTarget(target: any): boolean { * `packageProductDependencies`. * * A product listed in `embed` additionally gets a second `PBXBuildFile` in the - * "Embed Frameworks" copy phase of each non-extension target, which is how - * Xcode itself records a dynamic package product added through "Frameworks, - * Libraries, and Embedded Content" — linking alone leaves the framework out of - * the app bundle. + * "Embed Frameworks" copy phase of each target that can embed + * (`EMBEDDING_PRODUCT_TYPES`), which is how Xcode itself records a dynamic + * package product added through "Frameworks, Libraries, and Embedded Content" + * — linking alone leaves the framework out of the app bundle. * * Every entry is keyed by its pbxproj comment (e.g. `XCRemoteSwiftPackageReference * "Auth0"`), and an existing entry is updated in place rather than duplicated — @@ -72,6 +81,8 @@ export class SPMPbxprojService implements ISPMPbxprojService { project.parseSync(); let added = false; + const embeddedPackages = new Set(); + const linkOnlyTargets = new Map(); for (const { targetName, package: pkg } of assignments) { const targetId = this.findTargetId(project, targetName); if (!targetId) { @@ -83,6 +94,25 @@ export class SPMPbxprojService implements ISPMPbxprojService { if (this.addPackageToTarget(project, targetId, pkg, projectRoot)) { added = true; + if (pkg.embed?.length) { + const target = project.pbxNativeTargetSection()[targetId]; + if (canEmbedFrameworks(target)) { + embeddedPackages.add(pkg.name); + } else { + linkOnlyTargets.set(pkg.name, [ + ...(linkOnlyTargets.get(pkg.name) ?? []), + targetName, + ]); + } + } + } + } + + for (const [packageName, targetNames] of linkOnlyTargets) { + if (!embeddedPackages.has(packageName)) { + this.$logger.warn( + `SPM: package "${packageName}" lists products in embed, but its targets (${targetNames.join(", ")}) load frameworks from the app or WatchKit extension that hosts them. Add the package to that target too, or the products fail to load at launch.`, + ); } } @@ -226,9 +256,9 @@ export class SPMPbxprojService implements ISPMPbxprojService { ); } } - if (embedLibs.size && isExtensionTarget(target)) { + if (embedLibs.size && !canEmbedFrameworks(target)) { this.$logger.trace( - `SPM: linking ${[...embedLibs].join(", ")} into extension target ${target.name} without embedding; it loads them from the host app's bundle.`, + `SPM: linking ${[...embedLibs].join(", ")} into ${target.name} without embedding; it loads them from the bundle that hosts it.`, ); embedLibs.clear(); } @@ -289,6 +319,7 @@ export class SPMPbxprojService implements ISPMPbxprojService { }); if (!embedLibs.has(lib)) { + this.removeEmbedEntries(project, target, spmProductDependencyUUID); continue; } @@ -328,6 +359,49 @@ export class SPMPbxprojService implements ISPMPbxprojService { return null; } + /** + * Drops a product from this target's Embed Frameworks phases, and its + * build file once no other copy phase lists it. + */ + private removeEmbedEntries( + project: any, + target: any, + productRef: string, + ): void { + const buildFiles = project.hash.project.objects["PBXBuildFile"] ?? {}; + const copyPhases = + project.hash.project.objects["PBXCopyFilesBuildPhase"] ?? {}; + const isProductFile = (file: any) => + buildFiles[file.value]?.productRef === productRef; + + const removed = new Set(); + for (const phase of target.buildPhases ?? []) { + const phaseObj = copyPhases[phase.value]; + if (!phaseObj?.files || String(phaseObj.dstSubfolderSpec) !== "10") { + continue; + } + for (const file of phaseObj.files.filter(isProductFile)) { + removed.add(file.value); + } + phaseObj.files = phaseObj.files.filter( + (file: any) => !isProductFile(file), + ); + } + + const stillListed = new Set( + Object.keys(copyPhases) + .filter((key) => !key.endsWith("_comment")) + .flatMap((key) => copyPhases[key].files ?? []) + .map((file: any) => file.value), + ); + for (const uuid of removed) { + if (!stillListed.has(uuid)) { + delete buildFiles[uuid]; + delete buildFiles[`${uuid}_comment`]; + } + } + } + /** * Finds the "Embed Frameworks" copy phase listed in this target's own * buildPhases, creating one when the target has none. Matched on the diff --git a/test/services/ios/spm-pbxproj-service.ts b/test/services/ios/spm-pbxproj-service.ts index 64c3794c3a..53cabc1d19 100644 --- a/test/services/ios/spm-pbxproj-service.ts +++ b/test/services/ios/spm-pbxproj-service.ts @@ -111,10 +111,14 @@ function parsePbxproj(projectRoot: string): any { return project; } -/** Adds an app extension target with its own Frameworks phase to the fixture, returning its uuid. */ -function addExtensionTarget(projectRoot: string, name: string): string { +/** Adds a target with its own Frameworks phase to the fixture, returning its uuid. */ +function addTarget( + projectRoot: string, + name: string, + type: "app_extension" | "framework" | "watch_extension", +): string { const project = parsePbxproj(projectRoot); - const target = project.addTarget(name, "app_extension", name); + const target = project.addTarget(name, type, name); project.addBuildPhase( [], "PBXFrameworksBuildPhase", @@ -128,6 +132,17 @@ function addExtensionTarget(projectRoot: string, name: string): string { return target.uuid; } +/** The comments of the files in a target's Embed Frameworks copy phases. */ +function embeddedIn(project: any, targetId: string): string[] { + const target = project.pbxNativeTargetSection()[targetId]; + const copyPhases = project.hash.project.objects["PBXCopyFilesBuildPhase"]; + return (target.buildPhases as any[]) + .map((phase) => copyPhases?.[phase.value]) + .filter((phase) => phase && String(phase.dstSubfolderSpec) === "10") + .flatMap((phase) => phase.files ?? []) + .map((file: any) => file.comment); +} + /** The uuids of the build files in the fixture target's "Embed Frameworks" phase. */ function embedPhaseFileUuids(project: any): string[] { const targets = project.pbxNativeTargetSection(); @@ -479,7 +494,7 @@ describe("SPMPbxprojService", () => { }); it("links an embedded product into an extension target without embedding it there", () => { - const extensionId = addExtensionTarget(projectRoot, "Widget"); + const extensionId = addTarget(projectRoot, "Widget", "app_extension"); assert.isTrue( service.addPackages(projectRoot, [ @@ -511,6 +526,113 @@ describe("SPMPbxprojService", () => { ]); }); + it("links an embedded product into a framework target without embedding it there", () => { + const frameworkId = addTarget(projectRoot, "Module", "framework"); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + { targetName: "Module", package: dynamicPackage }, + ]), + ); + + const project = parsePbxproj(projectRoot); + assert.deepEqual(embeddedIn(project, frameworkId), []); + assert.lengthOf(embedPhaseFileUuids(project), 1); + assert.isEmpty(warnings); + }); + + it("embeds into a WatchKit extension, which hosts the watch app's code", () => { + const watchExtensionId = addTarget( + projectRoot, + "WatchExtension", + "watch_extension", + ); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: "WatchExtension", package: dynamicPackage }, + ]), + ); + + assert.deepEqual( + embeddedIn(parsePbxproj(projectRoot), watchExtensionId), + ["DynamicProduct in Embed Frameworks"], + ); + assert.isEmpty(warnings); + }); + + it("warns when no target the package is applied to can embed it", () => { + addTarget(projectRoot, "Widget", "app_extension"); + + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: "Widget", package: dynamicPackage }, + ]), + ); + + assert.isTrue( + warnings.some( + (w) => w.includes("DynamicPkg") && w.includes("Widget"), + ), + `expected a warning naming the package and target, got: ${warnings}`, + ); + assert.notInclude(readPbxproj(projectRoot), "in Embed Frameworks"); + }); + + it("removes the embed entry when a product leaves embed, and keeps it linked", () => { + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + ]), + ); + assert.isTrue( + service.addPackages(projectRoot, [ + { + targetName: TARGET_NAME, + package: { ...dynamicPackage, embed: [] }, + }, + ]), + ); + + const contents = readPbxproj(projectRoot); + assert.notInclude(contents, "DynamicProduct in Embed Frameworks"); + assert.include(contents, "DynamicProduct in Frameworks"); + assert.lengthOf(embedPhaseFileUuids(parsePbxproj(projectRoot)), 0); + }); + + it("keeps an embed entry another target still lists", () => { + const watchExtensionId = addTarget( + projectRoot, + "WatchExtension", + "watch_extension", + ); + assert.isTrue( + service.addPackages(projectRoot, [ + { targetName: TARGET_NAME, package: dynamicPackage }, + { targetName: "WatchExtension", package: dynamicPackage }, + ]), + ); + assert.isTrue( + service.addPackages(projectRoot, [ + { + targetName: TARGET_NAME, + package: { ...dynamicPackage, embed: [] }, + }, + ]), + ); + + const project = parsePbxproj(projectRoot); + assert.lengthOf(embedPhaseFileUuids(project), 0); + assert.deepEqual(embeddedIn(project, watchExtensionId), [ + "DynamicProduct in Embed Frameworks", + ]); + assert.include( + readPbxproj(projectRoot), + "DynamicProduct in Embed Frameworks */ = {", + ); + }); + it("warns about an embed entry that is not a linked lib, and skips it", () => { assert.isTrue( service.addPackages(projectRoot, [ From a7b43ebbfb12b0c53e6ab3e2528b4306bf9cee68 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 3 Dec 2026 13:13:28 -0800 Subject: [PATCH 4/4] fix(ios): only remove the embed entries the SPM service wrote --- lib/services/ios/spm-pbxproj-service.ts | 16 ++++++-- test/services/ios/spm-pbxproj-service.ts | 49 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/lib/services/ios/spm-pbxproj-service.ts b/lib/services/ios/spm-pbxproj-service.ts index 7c9054d0e9..f0fc15bb35 100644 --- a/lib/services/ios/spm-pbxproj-service.ts +++ b/lib/services/ios/spm-pbxproj-service.ts @@ -319,7 +319,12 @@ export class SPMPbxprojService implements ISPMPbxprojService { }); if (!embedLibs.has(lib)) { - this.removeEmbedEntries(project, target, spmProductDependencyUUID); + this.removeEmbedEntries( + project, + target, + spmProductDependencyUUID, + `${lib} in Embed Frameworks`, + ); continue; } @@ -360,19 +365,22 @@ export class SPMPbxprojService implements ISPMPbxprojService { } /** - * Drops a product from this target's Embed Frameworks phases, and its - * build file once no other copy phase lists it. + * Drops the embed entry this service wrote for a product from this + * target's Embed Frameworks phases, and its build file once no other copy + * phase lists it. Copy entries written by anyone else are left alone. */ private removeEmbedEntries( project: any, target: any, productRef: string, + embedComment: string, ): void { const buildFiles = project.hash.project.objects["PBXBuildFile"] ?? {}; const copyPhases = project.hash.project.objects["PBXCopyFilesBuildPhase"] ?? {}; const isProductFile = (file: any) => - buildFiles[file.value]?.productRef === productRef; + buildFiles[file.value]?.productRef === productRef && + buildFiles[`${file.value}_comment`] === embedComment; const removed = new Set(); for (const phase of target.buildPhases ?? []) { diff --git a/test/services/ios/spm-pbxproj-service.ts b/test/services/ios/spm-pbxproj-service.ts index 53cabc1d19..e163761ece 100644 --- a/test/services/ios/spm-pbxproj-service.ts +++ b/test/services/ios/spm-pbxproj-service.ts @@ -601,6 +601,55 @@ describe("SPMPbxprojService", () => { assert.lengthOf(embedPhaseFileUuids(parsePbxproj(projectRoot)), 0); }); + it("leaves copy entries it did not write for the same product", () => { + assert.isTrue( + service.addPackages(projectRoot, [ + { + targetName: TARGET_NAME, + package: { ...dynamicPackage, embed: [] }, + }, + ]), + ); + const project = parsePbxproj(projectRoot); + const objects = project.hash.project.objects; + const productRef = Object.keys( + objects["XCSwiftPackageProductDependency"], + ).find( + (key) => + objects["XCSwiftPackageProductDependency"][`${key}_comment`] === + "DynamicProduct", + ); + const userFileUuid = project.generateUuid(); + objects["PBXBuildFile"][userFileUuid] = { + isa: "PBXBuildFile", + productRef, + productRef_comment: "DynamicProduct", + }; + objects["PBXBuildFile"][`${userFileUuid}_comment`] = + "DynamicProduct in Copy Runtime Libraries"; + objects["PBXCopyFilesBuildPhase"][EMBED_PHASE_ID].files.push({ + value: userFileUuid, + comment: "DynamicProduct in Copy Runtime Libraries", + }); + writeFileSync( + path.join(projectRoot, `${TARGET_NAME}.xcodeproj`, "project.pbxproj"), + project.writeSync(), + ); + + assert.isTrue( + service.addPackages(projectRoot, [ + { + targetName: TARGET_NAME, + package: { ...dynamicPackage, embed: [] }, + }, + ]), + ); + + assert.deepEqual(embedPhaseFileUuids(parsePbxproj(projectRoot)), [ + userFileUuid, + ]); + }); + it("keeps an embed entry another target still lists", () => { const watchExtensionId = addTarget( projectRoot,