Skip to content

feat(ios): embed dynamic SwiftPM products with embed - #6169

Draft
edusperoni wants to merge 20 commits into
mainfrom
feat/spm-dynamic-embed
Draft

edusperoni wants to merge 20 commits into
mainfrom
feat/spm-dynamic-embed

Conversation

@edusperoni

Copy link
Copy Markdown
Collaborator

Stacked on #6153 (feat/define-command-migration). Only the last commit belongs to this PR; the rest is the base. Retarget to main once #6153 merges.

PR Checklist

What is the current behavior?

Declare a Swift package product as dynamic and reference it from nativescript.config.ts:

.library(name: "MyProduct", type: .dynamic, targets: ["MyProduct"])
ios: {
  SPMPackages: [{ name: "MyPackage", libs: ["MyProduct"], path: "./packages/MyPackage" }],
}

The app builds, links, and launches on the simulator. On a device or from an archive it crashes in dyld at launch:

dyld: Library not loaded: @rpath/MyProduct.framework/MyProduct
build links @rpath/MyProduct.framework in .app/Frameworks why it runs
ns build ios (Debug, simulator) yes no Xcode adds an absolute LC_RPATH to platforms/ios/build/…/PackageFrameworks
ns build ios --release --for-device yes no it does not: rpaths are @executable_path/Frameworks and @loader_path/Frameworks only

The framework is built (with its dSYM) and simply never copied into the bundle.

Cause. SPMPbxprojService.addPackageToTarget wires a product into the XCSwiftPackageProductDependency, a PBXBuildFile with productRef, and the target's PBXFrameworksBuildPhase. Nothing adds it to the "Embed Frameworks" PBXCopyFilesBuildPhase (dstSubfolderSpec = 10). When a package product is added through Xcode's own "Frameworks, Libraries, and Embedded Content" UI, Xcode emits the same productRef twice: once in the Frameworks phase, and once in the Embed Frameworks copy phase with settings = { ATTRIBUTES = (CodeSignOnCopy, ); }. That second entry is what the CLI was missing. Xcode does not infer it from the link phase alone, as the Release build above shows.

Verified on nativescript@9.1.0-next.2026-08-19 with Xcode 26.3.

What is the new behavior?

IosSPMPackageBase gains an opt-in embed:

ios: {
  SPMPackages: [{
    name: "MyPackage",
    libs: ["MyProduct", "MyStaticProduct"],
    embed: ["MyProduct"],          // the subset of libs built as .dynamic
    path: "./packages/MyPackage",
  }],
}

For each product in embed, addPackageToTarget now:

  • finds the target's own "Embed Frameworks" copy phase (dstSubfolderSpec = 10), creating one when the target has none, the same way the link phase is resolved from the target's own buildPhases rather than any target's;
  • writes a second PBXBuildFile for the same productRef with settings = { ATTRIBUTES = (CodeSignOnCopy, ); } and comment <Product> in Embed Frameworks;
  • appends it to that phase's files, keyed on productRef so re-applying on every prepare stays idempotent.

An embed entry that is not in libs is warned about and skipped, matching how the missing-Frameworks-phase case is reported.

What the service writes for an embedded product:

305AAFFD8CBC4D6CAA90BE54 /* MyProduct in Frameworks */ = {isa = PBXBuildFile; productRef = CF378E9510E242E691E8D60B /* MyProduct */; };
A7D085F2A0404543893668AE /* MyProduct in Embed Frameworks */ = {isa = PBXBuildFile; productRef = CF378E9510E242E691E8D60B /* MyProduct */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };

Why 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.

Nothing else changes. internal/strip-dynamic-framework-architectures.sh already walks $FRAMEWORKS_FOLDER_PATH, so embedded package frameworks get the same architecture strip and re-sign as plugin .xcframeworks.

Docs follow-up (docs.nativescript.org)

The SPM section should say that:

  • .library(type: .dynamic) products need embed, or they fail in dyld at launch on devices;
  • .library(...) without a type is static and ends up inside the app executable. A Release archive strips the executable's symbol table, so C functions reached from JS by name must then be listed for strip -s via STRIPFLAGS in build.xcconfig, or shipped as a dynamic product with embed.

Tests

test/services/ios/spm-pbxproj-service.ts:

  • an embedded product gets both a Frameworks and an Embed Frameworks build file for the same productRef, the latter with CodeSignOnCopy; a linked-only product gets no embed entry;
  • re-applying is byte-identical and does not duplicate the embed entry;
  • the Embed Frameworks phase is created when the target has none, and is not created for a package that embeds nothing;
  • an embed entry missing from libs warns and is skipped.

Options and arguments are declared on the definition and validated
before run. Setup runs ahead of argument enforcement so a definition can
derive its arguments; a redeclared CLI option keeps whatever it leaves
unspecified; unknown options are tolerated instead of skipping
validation; objectOption covers --env.* style values; a missing required
argument keeps the command's preamble in the error.
Platform validation, dynamic delegation, native-add and widget, test,
create/install/post-install-cli/help, enforced-parameter, device,
self-contained, platform, plugin and hooks, open|*, and the rest.
Class-based surfaces the migration left without callers are deprecated
rather than removed, since extensions may import them.
… type

registerCommand takes one shape and registers in one call, off the
global binding and into the loading context's injector; built-in
commands load on first use through a shared helper; getInjector becomes
getRootInjector. Package-manager commands register from their real
path, dev-post-install is reachable again, and a mistyped subcommand
shows help in the terminal.
A command can run another in process without exiting on failure; a
definition's setup state is scoped to one invocation;
DeferredCommandResult is a discriminated union; the command-name types
an extension needs are exported from the contracts.

BREAKING CHANGE: ctx.arguments is now ctx.params on the command context.
ns start's key handling becomes a declarative table over a
caller-supplied context, with state on the context and capabilities on
the injector; the key-command surface leaves the injector facade.
Failures from the spawned run children surface in the parent, and
NS_NO_OPEN keeps the CLI from launching a browser where nobody is
watching.
KeyShortcutRegistry is a contract with disposable registrations; the
engine resolves help and dispatch through it, so an entry registered at
runtime takes effect immediately. The shared entries become builders, a
defineCommand may declare the keys it answers to, and ns run and ns
debug get their own tables behind NS_COMMAND_SHORTCUTS (default off).
Stopping a bundler only sent SIGINT and returned, so a restart could spawn
a replacement while the old watcher was still alive. The stale child's exit
then evicted the replacement's map entry, and a compilation finishing on it
still reached the prepare controller.

Await the child's exit (escalating to SIGKILL), detach its output and IPC
handlers, and key every eviction on process identity. The prepare
controller now keeps its compilation handler per platform, so stopping one
platform no longer leaves the other's listener attached.
r restarts the app of the running session without preparing, building
or syncing; R prepares again first and rebuilds the native app only if
needed; B always rebuilds it. The help hint is repeated once a burst of
syncs settles, and a restart stays on the devices the session was given
instead of every device attached to the platform.
`class X extends Command({ name, options, ... })` is sugar over the object
form: the definition is read through a static getter, `this.options` and
`this.args` are typed, and a command's services are typed from its setup. The
invocation context is provided under COMMAND_CONTEXT, which is what the class
form's field initializers read.
Each invocation builds one context object that every stage shares. The
structured commands move to the class form, whose result type is inferred from
`run` and whose meta is validated eagerly; the simple ones are inlined as
object definitions; cross-command checks go through canExecuteCommand. The
guide describes where a handler gets its services.
CommandsService is the contract a command, a key shortcut or a plugin runs or
consults another command through. It takes a registered name or a definition
run as given, routes a parent name to its subcommand and fires the full hook
name, rejects a dispatch that overlaps a running one while letting them nest,
and replaces the free runCommand and canExecuteCommand helpers. `ctx.injector`
is the invocation's own injector.
`ctx.fail(message, { help })` replaces the commands' direct use of $errors,
and signing and install options are read from the typed `ctx.options` instead
of the global options object.
A definition declares `providers` for its invocation injector; the container
takes `multi: true` providers, which shadow per level as in Angular; and
COMMAND_PRECONDITIONS is a multi token run before setup and before the
arguments policy. `provideProject()` is how a command declares that it runs
inside a project.
- A bare class in `providers` provides itself, as in Angular; the container
  expands it to `{ provide: Cls, useClass: Cls }` and the definition rejects
  anything that is neither a class nor a `provide` object.
- A COMMAND_PRECONDITIONS entry is a function or a list of functions, checked
  with the command's name; the list form is what lets a command keep the
  scope's preconditions next to its own.
- An argument's `validate` runs inside the invocation's injection context.
- `runCommand` and `canExecuteCommand` take `{ injector }` for a definition
  run as given, defaulting to the caller's injection context, then the root;
  a registered name rejects it.
- Option priming happens inside the guarded block, so a throwing
  `validateOptions` leaves no command entry behind.
- `getInjector()` stays as a deprecated alias of `getRootInjector()`, and the
  compat tests carry their original lines again.
- `provideProject` lives under lib/contracts and is exported from
  nativescript/contracts with `CommandReference` and `CommandDispatchOptions`.
- The guide follows the API on every point above.
…iew found

`executeCommandInProcess` and `canExecuteCommandInProcess` were renamed on
this branch before any release, so they go rather than stay deprecated; the
same for the `getInjector()` alias of `getRootInjector()`. The dispatcher's
hierarchical branch in option priming was unreachable once parent names were
routed to their leaf, the adapter shares `define-command`'s `isPlainObject`
instead of carrying a second one, the options service is typed in the
adapter, and `classCommandDefinition` is no longer exported.
The deprecation note on disableCommandHelpSuggestion said only that nothing references it, which the declaration already shows; the file goes back to its merge-base content.
- A legacy command's `skipOptionsValidation` still counts, as the deprecated
  spelling of `allowUnknownOptions`.
- Option priming puts the parser back when validation throws, and an error
  is reported once however many dispatch levels rethrow it.
- `open` passes IDE paths as arguments instead of shell strings, resets the
  visionOS platform override in a `finally`, and logs a failed launch.
- `preview` no longer falls through from the bun case to npm.
- The prepare controller removes its bundler listener even while the watcher
  is paused; a restart re-reads the session's device descriptors so a device
  stopped meanwhile is left alone; `waitForExit` answers at once for a child
  that has already exited.
- The `c` shortcut spawns the CLI through `process.execPath` and reports a
  spawn failure instead of crashing; shortcuts attach over IPC only when an
  IPC channel exists; a visionOS child receives forwarded keys and is
  stopped by `c`.
- The guide no longer names the removed in-process aliases and describes the
  argument specs a definition accepts.
…s `required`

`arguments` cannot be bound as an identifier in strict code, so a definition
could never be destructured or written with property shorthand; the field is
now `params`, the word the context already uses for the same values, and a
stale `arguments` key is rejected with a message naming the fix. `ParamSpec`,
`ParamsPolicy` and `CommandParamValues` replace the argument-named types,
which stay as deprecated aliases; `platformArgument` is `platformParam`.

An option spec takes `required: true`: its absence fails the invocation after
the params policy and before `canExecute`, and the handler's value type
drops `| undefined`, as a `default` already does. The two do not combine.
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/<Product>.framework/<Product>".

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.
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Base automatically changed from feat/define-command-migration to main October 22, 2026 14:38

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant