Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/definitions/ios.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ 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. App extensions and frameworks listed in `targets`
* only link these products and load them from the app's bundle.
*/
embed?: string[];
}

/** A package resolved from a git remote at a version, range, branch or revision. */
Expand Down
12 changes: 12 additions & 0 deletions lib/definitions/project.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,18 @@ 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. App extensions and frameworks listed
* in `targets` only link these products and load them from the app's bundle.
*
* 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[];
}

export interface IOSRemoteSPMPackage extends IOSSPMPackageBase {
Expand Down
182 changes: 182 additions & 0 deletions lib/services/ios/spm-pbxproj-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@ import * as semver from "semver";
import { injector } from "../../common/yok";
import { IFileSystem } from "../../common/declarations";

/**
* 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.
*/
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, ""),
);
}

/**
* Writes Swift Package references directly into an Xcode project's pbxproj.
*
Expand All @@ -17,6 +36,12 @@ 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
* "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 —
* so applying the same set of packages repeatedly (which the CLI does on every
Expand Down Expand Up @@ -56,6 +81,8 @@ export class SPMPbxprojService implements ISPMPbxprojService {
project.parseSync();

let added = false;
const embeddedPackages = new Set<string>();
const linkOnlyTargets = new Map<string, string[]>();
for (const { targetName, package: pkg } of assignments) {
const targetId = this.findTargetId(project, targetName);
if (!targetId) {
Expand All @@ -67,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.`,
);
}
}

Expand Down Expand Up @@ -200,6 +246,32 @@ export class SPMPbxprojService implements ISPMPbxprojService {
comment: packageReferenceComment,
});

const embedLibs = new Set<string>();
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.`,
);
}
}
if (embedLibs.size && !canEmbedFrameworks(target)) {
this.$logger.trace(
`SPM: linking ${[...embedLibs].join(", ")} into ${target.name} without embedding; it loads them from the bundle that hosts it.`,
);
embedLibs.clear();
Comment thread
NathanWalker marked this conversation as resolved.
Resolved
}
let embedBuildPhaseFiles: any[] | null = null;
if (embedLibs.size) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand Down Expand Up @@ -245,6 +317,35 @@ export class SPMPbxprojService implements ISPMPbxprojService {
value: spmBuildFileUuid,
comment: libComment,
});

if (!embedLibs.has(lib)) {
this.removeEmbedEntries(
project,
target,
spmProductDependencyUUID,
`${lib} in Embed Frameworks`,
);
continue;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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;
Expand All @@ -263,6 +364,87 @@ export class SPMPbxprojService implements ISPMPbxprojService {
return null;
}

/**
* 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}_comment`] === embedComment;

const removed = new Set<string>();
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
* 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;
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/** Replaces a matching array entry in place, or appends it. */
private addOrUpdateArrayEntry(
array: any[],
Expand Down
Loading
Loading