mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
docs(swiftpm): correct SwiftPM docs to match current scripts (#58968)
Summary:
Several statements in the SwiftPM docs no longer match the scripts on `main`. This PR corrects them. It changes docs only.
- `scripts/spm/__docs__`: CLI options, the three causes of exit code 2, what `sync` does and when it re-runs, which command writes each file, the header products a hand-written library depends on, and remote mode. Adds a table of environment variables.
- `scripts/ios-prebuild/__docs__`: the SwiftPM statements about where dependency and Hermes headers go.
Where the code has a known gap, the docs describe the current behavior. Examples: `npx react-native spm` does not forward `--configCommand`, and `spm scaffold` also changes the `.xcodeproj`.
A second commit simplifies the same docs: it removes repeated statements and splits long sentences. No facts change. The header resolution details move to `spm-header-paths-contract.md`.
## Changelog:
[INTERNAL] [CHANGED] - Correct SwiftPM docs to match current scripts
Pull Request resolved: https://github.com/react/react-native/pull/58968
Test Plan:
- `npx prettier --check packages/react-native/scripts/{spm,ios-prebuild}/__docs__/*.md`: all files pass.
- Each changed statement was checked against the code on `main`. Relative links and anchors in changed lines resolve.
Reviewed By: christophpurrer
Differential Revision: D125209110
Pulled By: cipolleschi
fbshipit-source-id: faa09373ec67ed6c4f0f560428c0996716cdae5c
(cherry picked from commit 649c946516)
This commit is contained in:
1 parent
50c6e9726d
commit
0f95088438
6 files changed
+729
-611
No files matched your search
@@ -126,11 +126,14 @@ overlay**. The layout contract is defined and validated in code:
|
||||
the `React/` and bare-aliased headers into every slice's
|
||||
`React.framework/Headers`, and `buildReactNativeHeadersXcframework()`
|
||||
assembles the headers-only `ReactNativeHeaders.xcframework` carrying every
|
||||
other namespace (incl. `react/`) plus the third-party dependency namespaces
|
||||
(`folly`, `glog`, `boost`, `fmt`, `double-conversion`, `fast_float`). The
|
||||
Hermes public headers (`<hermes/...>`) are folded in only on the SwiftPM
|
||||
consumer side (`ensureHeadersLayout`); the published prebuild artifact does
|
||||
not yet carry them (TODO in `xcframework.js`).
|
||||
other React Native namespace (incl. `react/`). The third-party dependency
|
||||
namespaces (`folly`, `glog`, `boost`, `fmt`, `double-conversion`,
|
||||
`fast_float`, `SocketRocket`) ship in the separate headers-only
|
||||
`ReactNativeDependenciesHeaders.xcframework` sidecar, built by the
|
||||
dependencies prebuild. The Hermes public headers (`<hermes/...>`) are folded
|
||||
into the published `ReactNativeHeaders` when the hermes-ios headers are
|
||||
staged; without them the compose ships no `hermes/`, unless `--require-hermes`
|
||||
is set, which makes it fail closed.
|
||||
|
||||
### Artifacts
|
||||
|
||||
@@ -139,15 +142,15 @@ The prebuild (`xcframework.js`) always produces:
|
||||
- `React.xcframework` — the compiled React core. Each slice's `React.framework`
|
||||
carries the headers-spec layout (every `<React/...>` header + the framework
|
||||
module map). CocoaPods consumes that layout directly, through
|
||||
`FRAMEWORK_SEARCH_PATHS`. SwiftPM consumes the same headers indirectly: the
|
||||
XCFramework is not a member of the Swift package graph, so the consumer side
|
||||
stages a copy of `React.framework/Headers` into
|
||||
`ReactHeadersTarget/include/React` and rewrites `framework module React` to a
|
||||
plain `module React`, vended as the `ReactHeaders` target (see
|
||||
`spm-header-paths-contract.md` in the SwiftPM docs).
|
||||
- `ReactNativeHeaders.xcframework` — headers-only; carries every other
|
||||
namespace. Consumed by SwiftPM as a `binaryTarget` and by CocoaPods via the
|
||||
`React-Core-prebuilt` pod (headers flattened onto the header search path).
|
||||
`FRAMEWORK_SEARCH_PATHS`. SwiftPM consumes the same headers indirectly,
|
||||
because the XCFramework is not a member of the Swift package graph. The
|
||||
consumer side stages a copy of `React.framework/Headers` into
|
||||
`ReactHeadersTarget/include/React`, rewrites `framework module React` to a
|
||||
plain `module React`, and vends it as the `ReactHeaders` target (see
|
||||
[spm-header-paths-contract.md](../../spm/__docs__/spm-header-paths-contract.md)).
|
||||
- `ReactNativeHeaders.xcframework` — headers-only; carries every other React
|
||||
Native namespace. Consumed by SwiftPM as a `binaryTarget` and by CocoaPods via
|
||||
the `React-Core-prebuilt` pod (headers flattened onto the header search path).
|
||||
|
||||
### CocoaPods consumption
|
||||
|
||||
|
||||
@@ -120,13 +120,14 @@ resolving `<react/...>` through `React.framework` requires case-folding
|
||||
`react.framework` → `React.framework`, which only works on case-insensitive
|
||||
filesystems. The header-search-path route (R2) is exact everywhere.
|
||||
|
||||
**R2 — every other namespace ships in ONE headers-only xcframework,
|
||||
**R2 — every other React Native namespace ships in ONE headers-only xcframework,
|
||||
`ReactNativeHeaders`.** Namespace dirs at its `Headers/` root: `react/`,
|
||||
`yoga/`, `jsi/`, `cxxreact/`, `React_RCTAppDelegate/`, … **including the
|
||||
third-party deps namespaces** (folly/glog/boost/fmt/double-conversion/
|
||||
fast_float, copied out of the ReactNativeDependencies artifact — which thereby
|
||||
becomes binary-only). SPM/Xcode auto-serve a binaryTarget's `Headers/` on the
|
||||
consumer's search path, so everything resolves with zero flags.
|
||||
`yoga/`, `jsi/`, `cxxreact/`, `React_RCTAppDelegate/`, … The third-party deps
|
||||
namespaces (folly, glog, boost, fmt, double-conversion, fast_float,
|
||||
SocketRocket) are **not** here: they ship in the headers-only
|
||||
`ReactNativeDependenciesHeaders` sidecar built by the deps prebuild. SPM/Xcode
|
||||
auto-serve a binaryTarget's `Headers/` on the consumer's search path, so
|
||||
everything resolves with zero flags.
|
||||
|
||||
**R3 — NO include rewriting, anywhere.** Shipped headers are byte-identical to
|
||||
the repo. If a header's includes don't work in the packaged layout, the fix is
|
||||
@@ -249,11 +250,11 @@ declarations stay single-owned.
|
||||
|
||||
### `buildReactNativeHeadersXcframework`
|
||||
|
||||
1. Stage all R2 entries, then copy the six deps namespaces from
|
||||
`third-party/ReactNativeDependencies.xcframework/Headers`. A declared deps
|
||||
namespace that is missing is a **hard error** — previously a warn-and-ship,
|
||||
which once produced a silently deps-less artifact (1.6 MB instead of 11 MB).
|
||||
2. Optionally fold in the `hermes/` public headers (consumer-side compose path).
|
||||
1. Stage all R2 entries. The deps namespaces are not copied here; they ship in
|
||||
the `ReactNativeDependenciesHeaders` sidecar, whose namespace guards live in
|
||||
`buildDepsHeadersXcframework` (`headers-xcframework.js`).
|
||||
2. Fold in the `hermes/` public headers when they are staged (both the prebuild
|
||||
compose and the consumer-side compose path).
|
||||
3. Write the R10 umbrella files, then the R5 module map.
|
||||
4. Compile a stub static archive per slice (headers-only artifacts still need a
|
||||
library for `xcodebuild -create-xcframework`) and compose the xcframework.
|
||||
@@ -274,13 +275,17 @@ mtime + hermes presence).
|
||||
| `#import <React/RCTMountingManager.h>` | same, **textual** via the R9 entry | R9 |
|
||||
| `#import <react/renderer/...>` (C++) | `ReactNativeHeaders/Headers` search path, textual | R2 |
|
||||
| `#import <yoga/Yoga.h>` | same, **modular** via the yoga R5 module | R2, R5 |
|
||||
| `#import <folly/dynamic.h>` | same (deps namespaces relocated here) | R2 |
|
||||
| `#import <folly/dynamic.h>` | SwiftPM: the `ReactNativeDependenciesHeaders` sidecar's `Headers/` (deps namespaces are not in `ReactNativeHeaders`) | R2 |
|
||||
| `<React_RCTAppDelegate/React_RCTAppDelegate-umbrella.h>` | same, modular | R10 |
|
||||
| `#import "RCTFabricComponentsPlugins.h"` (quoted, community Fabric pods) | CocoaPods only: re-vended by the `React-RCTFabric` facade into the pod header map (`rncore_facades.rb`, `FACADE_REEXPOSED_HEADERS`) | — |
|
||||
|
||||
- **SwiftPM**: both xcframeworks are plain `.binaryTarget`s; Xcode auto-serves
|
||||
`React.framework`'s `Headers/`+`Modules/` and `ReactNativeHeaders`' `Headers/`
|
||||
(incl. its `module.modulemap`) to dependents. Zero flags.
|
||||
- **SwiftPM**: `React.xcframework` is not in the package graph. Its headers are
|
||||
copied into `ReactHeadersTarget/include/React` with the module map rewritten
|
||||
to a plain `module React`, vended as the `ReactHeaders` target. The only
|
||||
`.binaryTarget`s are `ReactNativeHeaders` and
|
||||
`ReactNativeDependenciesHeaders`; Xcode auto-serves their `Headers/` (incl.
|
||||
`module.modulemap`) to dependents. Zero flags. See
|
||||
[spm-header-paths-contract.md](../../spm/__docs__/spm-header-paths-contract.md).
|
||||
- **CocoaPods**: `React-Core-prebuilt`'s `prepare_command` flattens
|
||||
`ReactNativeHeaders`' Headers (incl. the module map) into the pod, and the
|
||||
React-core pods are installed as dependency-only **facades**
|
||||
@@ -294,8 +299,8 @@ mtime + hermes presence).
|
||||
| R9 allowlist validation | private header removed/renamed, or bucket drifted | `validatePrivateReactHeaders` |
|
||||
| R10 umbrella check | a probed namespace loses all modular headers | `planFromInventory` |
|
||||
| R5 exemption assert | an invalid-module-identifier namespace gains a modular-candidate header | `planFromInventory` |
|
||||
| Deps namespace guard (missing) | folly/glog/… not staged at compose time | `buildReactNativeHeadersXcframework` |
|
||||
| Deps namespace guard (undeclared) | the deps artifact ships a namespace not in `DEPS_NAMESPACES` (new third-party dep) | `buildReactNativeHeadersXcframework` |
|
||||
| Deps namespace guard (missing) | folly/glog/… not staged at compose time | `buildDepsHeadersXcframework` |
|
||||
| Deps namespace guard (undeclared) | the deps artifact ships a namespace not in `DEPS_NAMESPACES` (new third-party dep) | `buildDepsHeadersXcframework` |
|
||||
| Include-health ratchet | a shipped header gains a `notShipped`/`unresolved`/quoted-unresolvable include not in the committed baseline | `headers-verify.js` |
|
||||
| Structural gate | composed module maps/umbrellas differ from the spec render; R9 headers or deps dirs absent | `headers-verify.js` |
|
||||
| Compile gates | the React module, any R5 namespace module, the R10 umbrella, the R9 textual (Expo-shape) surface, or Swift `RCTBridge.moduleRegistry` fails to compile | `headers-verify.js` (CI: prebuild compose job) |
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
[🏠 Home](../../../../../__docs__/README.md)
|
||||
|
||||
> **Preview.** SwiftPM support is an early preview: the commands, flags,
|
||||
> generated layout, and distribution model may change in future releases, and it
|
||||
> is not yet recommended for production. CocoaPods remains the supported
|
||||
> default.
|
||||
> **Preview.** SwiftPM support is an early preview. The commands, flags,
|
||||
> generated layout, and distribution model may change in future releases. It is
|
||||
> not yet recommended for production. CocoaPods remains the supported default.
|
||||
|
||||
The scripts in `scripts/spm/` let a React Native iOS app consume React Native
|
||||
through **Swift Package Manager** instead of CocoaPods, using prebuilt
|
||||
@@ -13,9 +12,9 @@ XCFrameworks. Support is opt-in and additive: `npx react-native spm` injects
|
||||
package references into the app's existing `.xcodeproj` in place, and `deinit`
|
||||
reverses exactly what it injected.
|
||||
|
||||
The motivation, staged migration plan, and open questions live in
|
||||
[RFC0994](https://github.com/react-native-community/discussions-and-proposals/blob/main/proposals/0994-swift-package-manager-support-for-react-native-ios-projects.md).
|
||||
The documents here describe how the implementation actually works.
|
||||
[RFC0994](https://github.com/react-native-community/discussions-and-proposals/blob/main/proposals/0994-swift-package-manager-support-for-react-native-ios-projects.md)
|
||||
holds the motivation, the staged migration plan, and the open questions. The
|
||||
documents here describe how the implementation works.
|
||||
|
||||
## 🚀 Usage
|
||||
|
||||
@@ -24,21 +23,10 @@ cd ios
|
||||
npx react-native spm # add on first run, update thereafter
|
||||
```
|
||||
|
||||
**If any autolinked dependency ships no `Package.swift`, this stops with
|
||||
`error: Package.swift is missing for library "<name>"` and exit code 2.** That
|
||||
is deliberate — `add` and `update` never scaffold silently, so a missing
|
||||
manifest is visible and fixed on purpose. Generate the manifests first, then
|
||||
re-run setup:
|
||||
|
||||
```bash
|
||||
npx react-native spm scaffold # writes Package.swift into node_modules/<dep>/
|
||||
npx react-native spm # then inject as usual
|
||||
```
|
||||
|
||||
Because `node_modules` isn't committed, persist each scaffolded manifest with
|
||||
`npx patch-package <dep>` and commit the patch — otherwise the same error
|
||||
returns on every fresh install and in CI. Better still, contribute the manifest
|
||||
upstream. See
|
||||
**If an autolinked dependency ships no `Package.swift`, setup stops with
|
||||
`error: Package.swift is missing for library "<name>"` and exit code 2.** Run
|
||||
`npx react-native spm scaffold`, persist the manifest with `patch-package`, and
|
||||
re-run setup. See
|
||||
[Community packages without a Package.swift](./spm-scripts.md#community-packages-without-a-packageswift).
|
||||
|
||||
See **[spm-scripts.md](./spm-scripts.md)** for the CLI actions and flags,
|
||||
@@ -52,20 +40,20 @@ Three documents cover the design, each owning one area:
|
||||
| Document | Covers |
|
||||
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [spm-scripts.md](./spm-scripts.md) | The tool itself: CLI surface, the six-step pipeline, [every file it creates or modifies](./spm-scripts.md#files-the-tool-touches), the two auto-sync hooks, and how Debug/Release flavor selection works. |
|
||||
| [spm-header-paths-contract.md](./spm-header-paths-contract.md) | How headers and package references resolve. The contract is **zero-`-I`**: no header search paths and no `unsafeFlags` in any generated manifest. Also covers remote mode. |
|
||||
| [spm-header-paths-contract.md](./spm-header-paths-contract.md) | How headers and package references resolve. The contract is **zero-`-I`**: no generated manifest carries a search path into React Native's own headers. Also covers remote mode. |
|
||||
| [spm-autolinking-plugins.md](./spm-autolinking-plugins.md) | The extension seam for frameworks with their own module system (Expo is the first consumer): discovery, the full context/return contract including `flavoredFrameworks`, `watchPaths` and `scriptPhases`, and failure behavior. |
|
||||
|
||||
Two ideas explain most of the architecture:
|
||||
|
||||
- **Headers go through SwiftPM; runtime binaries do not.** A `binaryTarget`
|
||||
cannot vary by build configuration, but React Native ships flavored binaries
|
||||
(a debug `React.framework` carries the dev menu and assertions; release strips
|
||||
them). So the package graph vends headers only, and the flavored frameworks
|
||||
are linked and embedded through generated Xcode build settings instead.
|
||||
cannot vary by build configuration, but React Native ships flavored binaries.
|
||||
So the package graph vends headers only, and generated Xcode build settings
|
||||
link and embed the flavored frameworks. See
|
||||
[Debug/Release flavor is automatic](./spm-scripts.md#debugrelease-flavor-is-automatic).
|
||||
- **Generated state is regenerable, and the injection is reversible.**
|
||||
Everything under `build/` is gitignored and rebuilt from the app's
|
||||
`package.json`; everything written into the `.xcodeproj` is recorded in a
|
||||
`.spm-injected.json` marker so `deinit` can undo precisely that.
|
||||
`package.json`. Every edit to the `.xcodeproj` is recorded in a
|
||||
`.spm-injected.json` marker, so `deinit` can undo exactly that.
|
||||
|
||||
## 🔗 Relationship with other systems
|
||||
|
||||
@@ -83,7 +71,9 @@ Two ideas explain most of the architecture:
|
||||
local `React-GeneratedCode` package rather than a Pod.
|
||||
- **`@react-native-community/cli config`** — supplies the autolinking metadata
|
||||
(`autolinking.json`) that the SwiftPM autolinker turns into a `Package.swift`.
|
||||
Overridable via `--configCommand`.
|
||||
Override it with the `RCT_SPM_AUTOLINKING_CONFIG_COMMAND` environment
|
||||
variable, or with `--config-command` when you run `setup-apple-spm.js`
|
||||
directly.
|
||||
|
||||
### Uses this
|
||||
|
||||
|
||||
@@ -22,18 +22,18 @@ The documented extension points don't cover a framework:
|
||||
re-run autolinking on every dependency change. A framework's contribution must
|
||||
run _whenever autolinking runs_.
|
||||
|
||||
A plugin is exactly that. It is invoked from `generate-spm-autolinking.js`'s
|
||||
`main()` — the single function that both `add` / `update` **and** the build-time
|
||||
`sync` call — so the contribution is regenerated on every build and never goes
|
||||
stale.
|
||||
A plugin does exactly that. `generate-spm-autolinking.js`'s `main()` invokes it.
|
||||
`add` / `update` **and** the build-time `sync` all call that one function. So
|
||||
the contribution is regenerated on every build and never goes stale, and the
|
||||
build-time path needs no separate hook.
|
||||
|
||||
(This is the SwiftPM analog of the seams CocoaPods gave Expo: the Podfile,
|
||||
`use_expo_modules!`, and `react_native_post_install` hooks.)
|
||||
This is the SwiftPM analog of the seams CocoaPods gave Expo: the Podfile,
|
||||
`use_expo_modules!`, and `react_native_post_install` hooks.
|
||||
|
||||
## Discovery — transitive, zero app config
|
||||
|
||||
A dependency opts in from its **own** package.json, so installing the framework
|
||||
is enough (mirrors how CocoaPods pulls in `use_expo_modules!` transitively):
|
||||
is enough. This mirrors how CocoaPods pulls in `use_expo_modules!` transitively:
|
||||
|
||||
```json
|
||||
// node_modules/expo/package.json
|
||||
@@ -42,12 +42,16 @@ is enough (mirrors how CocoaPods pulls in `use_expo_modules!` transitively):
|
||||
}
|
||||
```
|
||||
|
||||
The autolinker reads every dependency's SwiftPM settings; any that declares
|
||||
`autolinkingPlugin` is `require`d and invoked. No app-level registration or
|
||||
The autolinker reads every dependency's SwiftPM settings. It `require`s and
|
||||
invokes each one that declares `autolinkingPlugin`. No app-level registration or
|
||||
allowlist is required. The deprecated `spm.autolinkingPlugin` in
|
||||
`react-native.config.js` is still read — see
|
||||
[Migrating from react-native.config.js](spm-scripts.md#where-swiftpm-settings-live).
|
||||
|
||||
A dependency that declares a plugin owns its native contribution. React Native
|
||||
does not build it as an autolinked target, so it needs no `Package.swift` of its
|
||||
own.
|
||||
|
||||
**Opt-out escape hatch.** An app can exclude a plugin from its own package.json:
|
||||
|
||||
```json
|
||||
@@ -117,6 +121,29 @@ module.exports = function plugin(context) {
|
||||
};
|
||||
```
|
||||
|
||||
### `generatedSources` — sources wired into the app target
|
||||
|
||||
The merge writes `.spm-plugin-generated-sources.json`. The `spm add`/`update`
|
||||
xcodeproj injector (`generate-spm-xcodeproj.js`) reads it and wires each source
|
||||
**into the app target**: a `PBXFileReference`, a `PBXBuildFile`, and a
|
||||
Sources-build-phase entry, all under one "SPM Generated Sources" navigator
|
||||
group.
|
||||
|
||||
This is what makes an `@objc` class (e.g. Expo's `ExpoModulesProvider`) reach
|
||||
the ObjC classlist. A class inside the static Autolinked aggregate never does,
|
||||
so `NSClassFromString` discovery would fail.
|
||||
|
||||
- Paths are stored SRCROOT-relative when they are under the app root (the usual
|
||||
`build/generated/…` case), else absolute (`sourceTree = "<absolute>"`).
|
||||
- All UUIDs are namespaced on the normalized path, so injection is deterministic
|
||||
and idempotent. They are recorded in the `.spm-injected.json` marker's
|
||||
`generatedSources` map. `deinit` reverts them, and `update` reconciles entries
|
||||
that left the manifest.
|
||||
- A target without a Sources phase logs loudly and skips the wiring. The rest of
|
||||
the injection succeeds.
|
||||
- v1 targets only the injected app target and assumes `.swift` in practice.
|
||||
`.m`/`.mm` are mapped as future-proofing.
|
||||
|
||||
### `flavoredFrameworks` — per-configuration precompiled frameworks
|
||||
|
||||
Each entry is
|
||||
@@ -127,24 +154,29 @@ agree across flavors. Static binaries, nested frameworks, duplicate IDs, and
|
||||
duplicate embedded framework names are fatal.
|
||||
|
||||
The declarations are recorded to
|
||||
`<outputDir>/.spm-plugin-flavored-frameworks.json`, normalized into the same
|
||||
immutable app-local slots as React Native, and added to Xcode's exact linker and
|
||||
embed settings. They are not emitted as SwiftPM product dependencies. Adding or
|
||||
removing one requires `spm update`; the build-time `spm sync` intentionally does
|
||||
not mutate runtime framework settings. When the frameworks that plugins provide
|
||||
and the frameworks that the project links disagree, sync fails the build. An
|
||||
`error:` line names each framework and the command to run.
|
||||
`<outputDir>/.spm-plugin-flavored-frameworks.json`. They are normalized into the
|
||||
same immutable app-local slots as React Native and added to Xcode's exact linker
|
||||
and embed settings. They are not emitted as SwiftPM product dependencies. Adding
|
||||
or removing one requires `spm update`: the build-time `spm sync` intentionally
|
||||
does not mutate runtime framework settings. When the frameworks that plugins
|
||||
provide and the frameworks that the project links disagree, sync fails the
|
||||
build. An `error:` line names each framework and the command to run.
|
||||
|
||||
### `watchPaths` — plugin staleness inputs
|
||||
|
||||
`watchPaths` is an array of **absolute** paths (dirs **or** files) the Xcode
|
||||
auto-sync hooks watch to decide whether they must re-sync. RN already watches
|
||||
each module's source dir plus every npm dep's checked-in `Package.swift` and
|
||||
`.react-native/` dir; a plugin adds the inputs only it knows about — e.g.
|
||||
`packages/expo/Package.swift`, `expo-module.config.json`, and per-module
|
||||
manifests. On the next build the phase re-syncs when a watched **file** is newer
|
||||
than the last sync, a watched **dir** has a newer child, or a watched path has
|
||||
**vanished** (a rename forces a re-sync so the config error surfaces).
|
||||
`watchPaths` is an array of **absolute** paths (dirs **or** files). The Xcode
|
||||
auto-sync hooks watch them to decide whether they must re-sync. RN already
|
||||
watches each module's source dir, plus every npm dep's checked-in
|
||||
`Package.swift` and `.react-native/` dir. A plugin adds the inputs only it knows
|
||||
about, e.g. `packages/expo/Package.swift`, `expo-module.config.json`, and
|
||||
per-module manifests.
|
||||
|
||||
On the next build, the phase re-syncs when:
|
||||
|
||||
- a watched **file** is newer than the last sync,
|
||||
- a watched **dir** has a newer child, or
|
||||
- a watched path has **vanished**. A rename forces a re-sync, so the config
|
||||
error surfaces.
|
||||
|
||||
A watched path that does not exist yet is watched for **appearing**. When it is
|
||||
created, the next build re-syncs. So a plugin that builds precompiled modules
|
||||
@@ -152,21 +184,26 @@ should list their output folder, even when a fresh clone does not have it yet.
|
||||
List only folders that the Xcode build itself does not write to, or every build
|
||||
re-syncs.
|
||||
|
||||
Unlike `flavoredFrameworks`, watch paths are best-effort: a non-array is ignored
|
||||
with a warning (never fatal), and each non-string / empty / **relative** entry
|
||||
is dropped with a warning. Absolute-only, because the generated phase tests
|
||||
these paths with no cwd context. The kept paths are folded in with RN's own,
|
||||
deduped, and sorted: paths that exist go to `<outputDir>/.spm-sync-watch-paths`,
|
||||
and paths that do not exist yet go to `<outputDir>/.spm-sync-watch-absent`.
|
||||
Unlike `flavoredFrameworks`, watch paths are best-effort. A non-array is ignored
|
||||
with a warning (never fatal). Each non-string, empty, or **relative** entry is
|
||||
dropped with a warning. Paths must be absolute because the generated phase tests
|
||||
them with no cwd context. The kept paths are folded in with RN's own, deduped,
|
||||
and sorted: paths that exist go to `<outputDir>/.spm-sync-watch-paths`, and
|
||||
paths that do not exist yet go to `<outputDir>/.spm-sync-watch-absent`. Only
|
||||
paths that exist when the sync runs are written; a missing path is dropped
|
||||
silently. So the **vanished** check applies only to paths that existed at the
|
||||
last sync.
|
||||
|
||||
### `scriptPhases` — build-time shell phases on the app target
|
||||
|
||||
SwiftPM has no equivalent of CocoaPods' `script_phase`, so a framework that must
|
||||
run a script during the app's build — `expo-constants` writing
|
||||
`EXConstants.bundle/app.config` is the first consumer — declares it here. Each
|
||||
entry is recorded to `<outputDir>/.spm-plugin-script-phases.json`, which
|
||||
`spm add` / `spm update` reads to emit one `PBXShellScriptBuildPhase` per entry
|
||||
on the injected app target:
|
||||
SwiftPM has no equivalent of CocoaPods' `script_phase`. A framework that must
|
||||
run a script during the app's build declares it here. The first consumer is
|
||||
`expo-constants`, which writes `EXConstants.bundle/app.config`.
|
||||
|
||||
The merge always rewrites `<outputDir>/.spm-plugin-script-phases.json` — `[]`
|
||||
when no plugin declares any, so removing a plugin clears stale entries.
|
||||
`spm add` / `spm update` read that sidecar and emit one
|
||||
`PBXShellScriptBuildPhase` per entry on the injected app target:
|
||||
|
||||
| Key | Meaning |
|
||||
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
@@ -177,69 +214,80 @@ on the injected app target:
|
||||
| `inputPaths` / `outputPaths` | Optional Xcode input/output file lists, which is what lets Xcode skip an up-to-date phase. |
|
||||
| `alwaysOutOfDate` | Optional; when `true` the phase runs on every build regardless of its file lists. |
|
||||
|
||||
**Placement.** `'end'` appends at the true end of the target's `buildPhases` —
|
||||
after the app's own JS-bundle phase. `'beforeCompile'` lands directly after the
|
||||
"Sync SPM Autolinking" phase, which stays first because it regenerates the
|
||||
content everything else reads, and always **before Sources**: React Native never
|
||||
re-seats its own sync phase, so if you have dragged that below Sources your
|
||||
`beforeCompile` phases are seated ahead of Sources instead of following it.
|
||||
Phases sharing a position keep their declared order.
|
||||
**Placement.**
|
||||
|
||||
- `'end'` appends at the true end of the target's `buildPhases`, after the app's
|
||||
own JS-bundle phase.
|
||||
- `'beforeCompile'` lands directly after the "Sync SPM Autolinking" phase, and
|
||||
always **before Sources**. The sync phase stays first because it regenerates
|
||||
the content everything else reads. React Native never re-seats its own sync
|
||||
phase. If you have dragged it below Sources, your `beforeCompile` phases sit
|
||||
ahead of Sources instead of following it.
|
||||
|
||||
Phases that share a position keep their declared order.
|
||||
|
||||
**Position is enforced on every sync.** `add`/`update` compares where the plugin
|
||||
phases actually sit in `buildPhases` against the declared placement and, **only
|
||||
when the two differ**, lifts their membership lines and re-seats them in
|
||||
declared order. So changing `position` — or swapping two phases that share one —
|
||||
takes effect on the next `spm add`/`update`, with no remove + re-add. When they
|
||||
agree nothing is rewritten, which is what keeps an unchanged declaration
|
||||
re-syncing to a byte-identical project. The consequence worth knowing: a phase
|
||||
you **drag somewhere else in Xcode is moved back** to its declared position on
|
||||
the next sync, because the plugin's declaration is the source of truth. Only the
|
||||
`id` behaves differently — it is a key, not a label, so renaming it is a remove
|
||||
|
||||
- add.
|
||||
phases sit in `buildPhases` with the declared placement. **Only when the two
|
||||
differ** does it lift their membership lines and re-seat them in declared order.
|
||||
So a change to `position`, or a swap of two phases that share one, takes effect
|
||||
on the next `spm add`/`update`, with no remove + re-add. When they agree nothing
|
||||
is rewritten, so an unchanged declaration re-syncs to a byte-identical project.
|
||||
The plugin's declaration is the source of truth: a phase you **drag somewhere
|
||||
else in Xcode is moved back** to its declared position on the next sync.
|
||||
|
||||
Phases are injected by `spm add` / `spm update` **only**. The build-time `sync`
|
||||
rewrites the sidecar but never touches the `.xcodeproj`, so a newly declared
|
||||
rewrites the sidecar but never touches the `.xcodeproj`. So a newly declared
|
||||
phase appears on the next `add`/`update`, not on the next build. Each phase's
|
||||
UUID is derived from its `id` and recorded in the `.spm-injected.json` marker's
|
||||
`scriptPhases` map, so a re-run refreshes the phase's `name`, `script`, path
|
||||
lists, `alwaysOutOfDate` and placement in place, `update` removes phases that
|
||||
`scriptPhases` map. So a re-run refreshes the phase's `name`, `script`, path
|
||||
lists, `alwaysOutOfDate` and placement in place. `update` removes phases that
|
||||
left the sidecar, and `deinit` reverts all of them.
|
||||
|
||||
Validation is **fatal**, like `flavoredFrameworks` and unlike `watchPaths`: a
|
||||
non-array `scriptPhases`, a malformed entry, or a duplicate `id` (within one
|
||||
plugin or across plugins) aborts the run. A silently dropped phase would produce
|
||||
a green build whose generated content was never written — a runtime failure with
|
||||
no build-time signal — and two phases sharing an `id` would collapse onto one
|
||||
ledger key. `__proto__`, `constructor`, and `prototype` are rejected as ids even
|
||||
though the charset admits them: as keys of that ledger they never become own
|
||||
properties, so the phase would look recorded, disappear when the marker is
|
||||
serialized, and be unremovable by `deinit`.
|
||||
Validation is **fatal**, like `flavoredFrameworks` and unlike `watchPaths`.
|
||||
`invokePlugins` checks the `id` charset, a single-line `name`, a required
|
||||
`script`, the `position` enum, and the optional path lists and
|
||||
`alwaysOutOfDate`. A non-array `scriptPhases`, a malformed entry, or a duplicate
|
||||
`id` (within one plugin or across plugins) aborts the run.
|
||||
|
||||
**Hostile names.** A `name` reaches the project file twice. In the `name` field
|
||||
— what Xcode displays — it lands verbatim, escaped as an OpenStep string, so any
|
||||
single-line string is expressible. Beside the phase's UUID, on the object's
|
||||
definition line and on its `buildPhases` member line, it also becomes a
|
||||
`/* … */` comment; those comments are cosmetic (Xcode regenerates them from the
|
||||
`name` field) but the text around them is scanned by delimiter, so the name is
|
||||
**normalized** there: `{}(),;="*/`, tabs and whitespace runs collapse to single
|
||||
spaces (`spm-pbxproj.js`'s `commentSafe`), falling back to the phase `id` —
|
||||
normalized the same way — and then to no comment at all if nothing survives
|
||||
either. Without that, a `{` in a comment would make the injector read the next
|
||||
object's body as this one's, and a `,` would make `deinit` delete the wrong line
|
||||
— corruption with no error. Only a line break is therefore rejected outright; a
|
||||
name is a display name, and no Xcode phase name spans lines.
|
||||
- A silently dropped phase would produce a green build whose generated content
|
||||
was never written — a runtime failure with no build-time signal.
|
||||
- Two phases that share an `id` would collapse onto one ledger key.
|
||||
- `__proto__`, `constructor`, and `prototype` are rejected as ids even though
|
||||
the charset admits them. As keys of that ledger they never become own
|
||||
properties. The phase would look recorded, disappear when the marker is
|
||||
serialized, and be unremovable by `deinit`.
|
||||
|
||||
The injector's read of the sidecar is deliberately lenient — the file does not
|
||||
**Hostile names.** A `name` reaches the project file twice:
|
||||
|
||||
- In the `name` field, which Xcode displays, it lands verbatim, escaped as an
|
||||
OpenStep string. Any single-line string is expressible there.
|
||||
- Beside the phase's UUID, on the object's definition line and on its
|
||||
`buildPhases` member line, it becomes a `/* … */` comment. Xcode regenerates
|
||||
these comments from the `name` field, so they are cosmetic. But the injector
|
||||
scans the text around them by delimiter, so the name is **normalized** there.
|
||||
`{}(),;="*/`, tabs and whitespace runs collapse to single spaces
|
||||
(`spm-pbxproj.js`'s `commentSafe`). If nothing survives, the comment falls
|
||||
back to the phase `id`, normalized the same way, and then to no comment at
|
||||
all.
|
||||
|
||||
Without that normalization, a `{` in a comment would make the injector read the
|
||||
next object's body as this one's. A `,` would make `deinit` delete the wrong
|
||||
line. Both are corruption with no error. So only a line break is rejected
|
||||
outright: a name is a display name, and no Xcode phase name spans lines.
|
||||
|
||||
The injector's read of the sidecar is deliberately lenient. The file does not
|
||||
exist yet on a first `spm add`, and a stale or hand-edited copy must not break
|
||||
injection. An absent file yields no phases silently, an unparseable one warns,
|
||||
and a single entry failing the same checks (bad or reserved `id`, empty or
|
||||
multi-line `name`, missing `script`, unknown `position`, duplicate `id`) is
|
||||
**skipped, never coerced** — the sidecar is the only gate on a hand edit, so it
|
||||
enforces exactly the rules the plugin contract does.
|
||||
injection.
|
||||
|
||||
- An absent file yields no phases, silently.
|
||||
- An unparseable file warns.
|
||||
- An entry that fails the same checks (bad or reserved `id`, empty or multi-line
|
||||
`name`, missing `script`, unknown `position`, duplicate `id`) is **skipped,
|
||||
never coerced**. The sidecar is the only gate on a hand edit, so it enforces
|
||||
exactly the rules the plugin contract does.
|
||||
|
||||
**Gating is the script's job.** The phase runs for every configuration and
|
||||
platform the target builds; if it should be a no-op for some of them (Release
|
||||
platform the target builds. If it should be a no-op for some of them (Release
|
||||
only, simulator only, …), the script must check `$CONFIGURATION` /
|
||||
`$PLATFORM_NAME` and exit early.
|
||||
|
||||
@@ -257,9 +305,9 @@ only, simulator only, …), the script must check `$CONFIGURATION` /
|
||||
#### `context.react` — depending on React
|
||||
|
||||
A plugin that emits its own `Package.swift` must declare React as a dependency.
|
||||
Rather than re-deriving React Native's package path, identity, and product names
|
||||
— which differ between local and remote mode and **move as RN repackages** —
|
||||
take them from `context.react`:
|
||||
React Native's package path, identity, and product names differ between local
|
||||
and remote mode, and they **move as RN repackages**. So take them from
|
||||
`context.react` rather than re-deriving them:
|
||||
|
||||
```js
|
||||
react: {
|
||||
@@ -275,19 +323,21 @@ react: {
|
||||
}
|
||||
```
|
||||
|
||||
Local vs remote is signalled by which `packageRef` keys are present (`path` xor
|
||||
`url`+`version`). `packageRef.path` is **absolute** — always correct no matter
|
||||
which subdirectory of `outputDir` the plugin writes its own manifest into (the
|
||||
generated manifests are gitignored and regenerated every sync, so there's no
|
||||
portability cost); `relPath` (relative to `outputDir`) is provided as a
|
||||
convenience. `products` is the set React Native wires into **its own**
|
||||
autolinked targets (so a plugin's target compiles against exactly RN's React
|
||||
surface), filtered to those resolvable this run — every listed product is safe
|
||||
to reference without guarding. Note the fourth entry: `ReactAppHeaders` lives in
|
||||
the separate `React-GeneratedCode` package (per-app codegen), which a
|
||||
hand-rolled plugin would miss, and which is omitted when that package is absent.
|
||||
Because RN derives this list from one source of truth alongside its own product
|
||||
wiring, it stays correct across repackaging.
|
||||
- The `packageRef` keys signal local or remote mode: `path` xor `url`+`version`.
|
||||
- `packageRef.path` is **absolute**, so it is correct in any subdirectory of
|
||||
`outputDir` the plugin writes its manifest into. The generated manifests are
|
||||
gitignored and regenerated every sync, so this has no portability cost.
|
||||
`relPath` (relative to `outputDir`) is a convenience.
|
||||
- `products` is the set React Native wires into **its own** autolinked targets,
|
||||
so a plugin's target compiles against exactly RN's React surface. It is
|
||||
filtered to the products resolvable this run, so every listed product is safe
|
||||
to reference without a guard.
|
||||
- The fourth entry, `ReactAppHeaders`, lives in the separate
|
||||
`React-GeneratedCode` package (per-app codegen). A hand-rolled plugin would
|
||||
miss it. It is omitted when that package is absent.
|
||||
|
||||
RN derives this list from one source of truth alongside its own product wiring,
|
||||
so it stays correct across repackaging.
|
||||
|
||||
### Return (contributions, all optional)
|
||||
|
||||
@@ -298,11 +348,13 @@ wiring, it stays correct across repackaging.
|
||||
| `generatedSources` | Recorded for the codegen step to register (e.g. a module-registry `.swift`). |
|
||||
| `flavoredFrameworks` | Mandatory Debug/Release dynamic XCFramework pairs normalized outside SwiftPM. Malformed or incomplete entries are fatal. |
|
||||
| `scriptPhases` | Recorded for `spm add` / `update` to emit one `PBXShellScriptBuildPhase` per entry on the app target. Malformed entries and duplicate `id`s are fatal. |
|
||||
| `watchPaths` | The auto-sync staleness inputs (see [`watchPaths`](#watchpaths--plugin-staleness-inputs)). Invalid entries are dropped with a warning, not fatal. |
|
||||
|
||||
The plugin returns **data** — it never writes into React Native's generated
|
||||
tree. RN owns the merge, so a re-sync reproduces the same `Package.swift`
|
||||
byte-for-byte (idempotent). Package and product contributions are **deduped by
|
||||
name** across plugins.
|
||||
The plugin returns **data**. It never writes into React Native's generated tree.
|
||||
RN owns the merge, so a re-sync reproduces the same `Package.swift`
|
||||
byte-for-byte (idempotent). Across plugins, package contributions are **deduped
|
||||
by name** and product contributions by **package and name**. The first
|
||||
contribution wins.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
@@ -316,51 +368,32 @@ Xcode "Sync SPM Autolinking" ──┘ │
|
||||
└─ 4. merge results → aggregator Package.swift
|
||||
```
|
||||
|
||||
Because steps 1–4 run in the one `main()`, everything above shares the same seam
|
||||
— there is no separate hook to wire for the build-time path.
|
||||
|
||||
## Failure behavior
|
||||
|
||||
Fail-closed and **named**: a plugin that fails to load, doesn't export a
|
||||
function, throws, or returns a malformed contribution aborts the run with a
|
||||
message identifying the framework. A framework silently dropping its modules (a
|
||||
green build missing native code) is worse than a loud stop.
|
||||
Failures are fail-closed and **named**. A plugin that fails to load, doesn't
|
||||
export a function, throws, or returns a malformed contribution aborts the run.
|
||||
The message identifies the framework. A framework that silently drops its
|
||||
modules (a green build missing native code) is worse than a loud stop.
|
||||
|
||||
A plugin's host dependency is also a hard error when another library lists it in
|
||||
`swiftpmConfig.dependencies` and that library has no `Package.swift` of its own
|
||||
(shipped or scaffolded). React Native builds no target for the host, so there is
|
||||
nothing to depend on. Remove the entry: the plugin already links its products
|
||||
into the app.
|
||||
|
||||
## Status & open items (Preview)
|
||||
|
||||
- **Implemented & tested:** discovery (transitive + deny-list), invocation,
|
||||
package + product merge, fail-closed validation, and dual-flavor framework
|
||||
normalization/link/embed outside SwiftPM.
|
||||
- **Implemented & tested:** `generatedSources` **app-target wiring**. The merge
|
||||
writes `.spm-plugin-generated-sources.json`; the `spm add`/`update` xcodeproj
|
||||
injector (generate-spm-xcodeproj.js) reads it and wires each source **into the
|
||||
app target** — a `PBXFileReference` + `PBXBuildFile` + a Sources-build-phase
|
||||
entry, parented under one "SPM Generated Sources" navigator group. This is
|
||||
what makes an `@objc` class (e.g. Expo's `ExpoModulesProvider`) reach the ObjC
|
||||
classlist: a class inside the static Autolinked aggregate never does, so
|
||||
`NSClassFromString` discovery would fail. Paths are stored SRCROOT-relative
|
||||
when under the app root (the usual `build/generated/…` case), else absolute
|
||||
(`sourceTree = "<absolute>"`). All UUIDs are namespaced on the normalized path
|
||||
(deterministic/idempotent) and recorded in the `.spm-injected.json` marker's
|
||||
`generatedSources` map, so `deinit` reverts them and `update` reconciles
|
||||
entries that left the manifest. A target without a Sources phase logs loudly
|
||||
and skips the wiring (injection otherwise succeeds). v1 targets only the
|
||||
injected app target and assumes `.swift` in practice (`.m`/`.mm` are mapped as
|
||||
future-proofing).
|
||||
- **Implemented & tested:** `scriptPhases`, contract through injection.
|
||||
`invokePlugins` validates every entry fatally (`id` charset plus the reserved
|
||||
`__proto__`/`constructor`/`prototype` names, a single-line `name`, a required
|
||||
`script`, the `position` enum, optional path lists and `alwaysOutOfDate`, plus
|
||||
duplicate `id`s), and the merge always rewrites
|
||||
`.spm-plugin-script-phases.json` — `[]` when no plugin declares any, so
|
||||
removing a plugin clears stale entries. The `spm add`/`update` xcodeproj
|
||||
injector reads that sidecar and emits one `PBXShellScriptBuildPhase` per entry
|
||||
on the app target at the requested position, recording the id→UUID map in the
|
||||
`.spm-injected.json` marker so a re-run refreshes each phase's content in
|
||||
place, re-seats it when its declared position or order changed, `update`
|
||||
removes phases that left the sidecar, and `deinit` reverts them. Like
|
||||
`flavoredFrameworks`, the build-time `sync` only rewrites the sidecar; it
|
||||
never mutates the project.
|
||||
package + product merge, and fail-closed validation.
|
||||
- **Implemented & tested:** dual-flavor framework normalization/link/embed
|
||||
outside SwiftPM
|
||||
([`flavoredFrameworks`](#flavoredframeworks--per-configuration-precompiled-frameworks)).
|
||||
- **Implemented & tested:**
|
||||
[`generatedSources`](#generatedsources--sources-wired-into-the-app-target)
|
||||
**app-target wiring**.
|
||||
- **Implemented & tested:**
|
||||
[`scriptPhases`](#scriptphases--build-time-shell-phases-on-the-app-target),
|
||||
from the contract through injection.
|
||||
- **Co-design with Expo (not final):** codegen **provider ordering** — codegen
|
||||
must consume the same discovered module set the plugin contributes — is
|
||||
intentionally left for the first real plugin to drive to a stable shape.
|
||||
|
||||
@@ -1,100 +1,131 @@
|
||||
# SPM headers & package references — how they resolve
|
||||
|
||||
React Native's SPM consumption is **zero-I**: no `-I` / `-F` header search paths
|
||||
and no `unsafeFlags` in any generated manifest. Headers are served by SPM
|
||||
products/binary targets, and every generated `Package.swift` references the
|
||||
React Native + codegen packages with plain, fixed-relative paths computed at
|
||||
generation time (no runtime discovery). This document is the single source of
|
||||
truth for how that resolves.
|
||||
React Native's SPM consumption is **zero-I**: no generated manifest carries a
|
||||
`-I` / `-F` header search path into React Native's own headers. SPM products and
|
||||
binary targets serve those headers, with no clang VFS overlay. Every generated
|
||||
`Package.swift` references the React Native and codegen packages by plain,
|
||||
fixed-relative paths. This document is the single source of truth for how that
|
||||
resolves.
|
||||
|
||||
> History: earlier iterations materialized two header trees and fed them to
|
||||
> consumers as `-I` flags read from `spm-paths.json` /
|
||||
> `.react-native/paths.json` via an inlined Swift loader. That whole mechanism
|
||||
> (the loader `renderRNPathsLoader`, the `writeAppPathsJson` /
|
||||
> `writeSharedPathsJson` writers, and both JSON files) has been **deleted** —
|
||||
> manifests are now declarative. If you find a reference to those files, it is
|
||||
> stale.
|
||||
Generated manifests may still reach into their own tree:
|
||||
|
||||
- Scaffolded manifests, local-module wrappers, and the codegen package use
|
||||
`.headerSearchPath` into their own tree.
|
||||
- Scaffolded manifests may use `.unsafeFlags` for podspec compiler flags and a
|
||||
prefix header.
|
||||
|
||||
Manifests are declarative. The files `spm-paths.json` and
|
||||
`.react-native/paths.json`, their writers (`writeAppPathsJson`,
|
||||
`writeSharedPathsJson`), and the Swift loader `renderRNPathsLoader` no longer
|
||||
exist. A reference to any of them is stale.
|
||||
|
||||
## How headers resolve (no search paths)
|
||||
|
||||
React Native uses CocoaPods-style imports (`#import <React/RCTBridge.h>`) that
|
||||
SwiftPM does not natively support. These products serve them:
|
||||
|
||||
| Namespace | Served by | Mechanism |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Objective-C `<React/...>` / Swift `import React` | `ReactHeaders` Clang source target | Canonical Debug/Release-identical React headers staged under `ReactHeadersTarget/include/React`, with a plain `module React` module map. |
|
||||
| Lowercase C++ `<react/...>` and everything else: `<ReactCommon/...>`, `<jsi/...>`, `<react/renderer/...>`, `<yoga/...>`, folly/glog/boost/fmt/double-conversion | `ReactNativeHeaders.xcframework` plus `ReactNativeDependenciesHeaders.xcframework` | Header-only invariant binary targets keep lowercase `react` separate from Objective-C `React` and propagate their search paths through product dependencies. |
|
||||
| `<ReactCodegen/...>`, `ReactAppDependencyProvider`, this app's generated specs | `ReactAppHeaders` SPM target in the codegen package | SPM `publicHeadersPath` propagation — a real target dependency, not a flag. |
|
||||
|
||||
`ReactHeaders` stages its copy only after it proves that Debug and Release
|
||||
expose identical public headers; its module map uses `React/`-prefixed paths.
|
||||
`ReactNativeHeaders` is a headers-only (LIBRARY-type) binaryTarget, and the deps
|
||||
sidecar uses the same mechanism: SwiftPM serves each slice's `Headers/` to
|
||||
dependents. The deps sidecar also carries `fast_float/` and `SocketRocket/`. It
|
||||
exists because the binary `ReactNativeDependencies.xcframework` is
|
||||
framework-type and cannot expose those headers to SwiftPM. Targets that compile
|
||||
against React take all four products in the table as product dependencies.
|
||||
|
||||
The one remaining materialized header tree is the per-app farm at
|
||||
`<appRoot>/build/generated/ios/ReactAppHeaders` (built by
|
||||
`buildPerAppHeaderTree` in `spm-utils.js`, called from the orchestrators). It is
|
||||
vended as the `ReactAppHeaders` SPM target — consumers reach it through a
|
||||
product dependency, never through `-I`.
|
||||
`<appRoot>/build/generated/ios/ReactAppHeaders`. `buildPerAppHeaderTree` in
|
||||
`spm-utils.js` builds it, called from the orchestrators. It is vended as the
|
||||
`ReactAppHeaders` SPM target, so consumers reach it through a product
|
||||
dependency, never through `-I`.
|
||||
|
||||
`autolinking.json` (the `@react-native-community/cli config` output) is an INPUT
|
||||
used to generate the manifests; it is never read by a manifest.
|
||||
used to generate the manifests. No manifest reads it.
|
||||
|
||||
## How each manifest references the React + codegen packages
|
||||
|
||||
Every generated manifest sits at a known depth inside the app and is regenerated
|
||||
on every `react-native spm` run, so package references are plain fixed-relative
|
||||
paths — no walk-up, no JSON, no `import Foundation`.
|
||||
on every `react-native spm` run. So package references are computed at
|
||||
generation time as plain fixed-relative paths — no runtime discovery, no
|
||||
walk-up, no JSON, no `import Foundation`.
|
||||
|
||||
| Manifest | Location | How it references the React + codegen packages |
|
||||
| ------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| Autolinked aggregator | `build/generated/autolinking/Package.swift` | `.package(path: "../../xcframeworks")` + `"../ios"` (only when it has inline `spmModule` targets) |
|
||||
| Per-dep synth wrapper | `build/generated/autolinking/packages/<Name>/` | `.package(path: "../../../../xcframeworks")` + `"../../../ios"` |
|
||||
| Codegen template | `build/generated/ios/Package.swift` | `.package(path: "../../xcframeworks")` (or the remote url) |
|
||||
| App target (pbxproj) | `<App>.xcodeproj` | local `XCLocalSwiftPackageReference` (or `XCRemoteSwiftPackageReference` in remote mode) |
|
||||
| Scaffolded community lib | `node_modules/<dep>/Package.swift` | scaffold-time relative paths to the app's xcframeworks + codegen packages (or `.package(url:exact:)` in remote mode) |
|
||||
| Manifest | Location | How it references the React + codegen packages |
|
||||
| ------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Autolinked aggregator | `build/generated/autolinking/Package.swift` | Neither: it has no inline targets, and references only its dependencies' packages (`packages/<Name>`, `libs/<Name>`, plugin packages) |
|
||||
| Local-module wrapper | `build/generated/autolinking/packages/<Name>/` | `.package(path: "../../../../xcframeworks")` + `"../../../ios"` (only for `swiftpmConfig.modules` entries) |
|
||||
| Codegen template | `build/generated/ios/Package.swift` | `.package(path: "../../xcframeworks")` (or the remote url) |
|
||||
| App target (pbxproj) | `<App>.xcodeproj` | local `XCLocalSwiftPackageReference` (or `XCRemoteSwiftPackageReference` in remote mode) |
|
||||
| Scaffolded community lib | `node_modules/<dep>/Package.swift` | scaffold-time relative paths to the app's xcframeworks + codegen packages (or `.package(url:exact:)` in remote mode) |
|
||||
|
||||
## Remote-package mode
|
||||
|
||||
Remote mode is gated by a **URL alone** — `RN_SPM_REMOTE_URL` (or the persisted
|
||||
`url`). When set, the whole app graph flips to a single remote React Native
|
||||
package identity: `.package(path: build/xcframeworks)` becomes
|
||||
`.package(url:exact:)` everywhere (aggregator/synth/codegen template/pbxproj),
|
||||
and the local artifact download + compose is skipped. SPM's
|
||||
one-version-per-package rule then unifies app + every library on one resolved
|
||||
React Native. The package identity is derived from the URL tail (swift-tools 6
|
||||
dropped `.package(name:url:)`) — nothing hardcodes a repo name.
|
||||
A **URL alone** turns remote mode on: `RN_SPM_REMOTE_URL`, or the persisted
|
||||
`url`. The whole app graph then uses a single remote React Native package
|
||||
identity. `.package(path: build/xcframeworks)` becomes `.package(url:exact:)`
|
||||
everywhere it appears (synth, codegen template, pbxproj). The local artifact
|
||||
download and the compose of `build/xcframeworks` still run. SPM's
|
||||
one-version-per-package rule then unifies the app and every library on one
|
||||
resolved React Native.
|
||||
|
||||
The package identity comes from the URL tail, because swift-tools 6 dropped
|
||||
`.package(name:url:)`. Nothing hardcodes a repo name.
|
||||
|
||||
**Version is derived from npm, not pinned by hand.** The SPM graph must compile
|
||||
against the same React Native that the JS and native code use. So the app (the
|
||||
graph root) pins EXACT to the _installed_ React Native version, read from
|
||||
`node_modules/react-native/package.json`.
|
||||
|
||||
**Version is derived from npm, not pinned by hand.** The SPM-pinned RN version
|
||||
is not a free parameter: the SPM graph must compile against the same React
|
||||
Native the JS/native code uses, so the app (graph root) pins EXACT to the
|
||||
_installed_ RN version, read from `node_modules/react-native/package.json`.
|
||||
`RN_SPM_REMOTE_VERSION` and the persisted `versionOverride` are **overrides**,
|
||||
not the source of truth — they're only needed when the installed version isn't
|
||||
publishable (e.g. the monorepo `1000.0.0` dev placeholder, which has no remote
|
||||
tag). A _derived_ version is never persisted, so an `npm install` that upgrades
|
||||
RN auto-re-pins the SPM graph on the next `spm` run; an _override_ is persisted
|
||||
as `versionOverride` so it survives Xcode-phase re-syncs without the env.
|
||||
|
||||
Persisted schema is `{url, versionOverride?}`. Legacy `{url, version}` is still
|
||||
read, with `version` honored as an override (back-compat). If remote mode is on
|
||||
but no usable version can be resolved — react-native isn't installed, or it's a
|
||||
non-publishable dev placeholder and no override is set — the tooling errors
|
||||
(exit 2, a hard Xcode build error) directing you to set `RN_SPM_REMOTE_VERSION`
|
||||
or install a released react-native, rather than silently pinning an unpublished
|
||||
not the source of truth. You need them only when the installed version is not
|
||||
publishable, e.g. the monorepo `1000.0.0` dev placeholder, which has no remote
|
||||
tag.
|
||||
|
||||
- A _derived_ version is never persisted. An `npm install` that upgrades React
|
||||
Native re-pins the SPM graph on the next `spm` run.
|
||||
- An _override_ is persisted as `versionOverride`, so it survives Xcode-phase
|
||||
re-syncs without the environment variable.
|
||||
|
||||
The settings persist in `build/generated/autolinking/spm-remote.json`. The file
|
||||
is written only when the settings come from the environment variables. It lives
|
||||
under `build/`, so deleting `build/` turns remote mode off until you set the
|
||||
variables again. The persisted schema is `{url, versionOverride?}`. The legacy
|
||||
`{url, version}` is still read, with `version` honored as an override.
|
||||
|
||||
If remote mode is on but no usable version resolves, the tooling stops with exit
|
||||
2, a hard Xcode build error. This happens when react-native is not installed, or
|
||||
when it is a non-publishable dev placeholder and no override is set. The error
|
||||
tells you to set `RN_SPM_REMOTE_VERSION` or install a released react-native. The
|
||||
tooling never silently pins an unpublished tag.
|
||||
|
||||
## Hand-authored community library contract
|
||||
|
||||
A library that ships its own `Package.swift` (no scaffolder/autolinker marker)
|
||||
is left untouched by the tooling. It needs only two things, and **no discovery
|
||||
code**:
|
||||
The tooling leaves untouched a library that ships its own `Package.swift` (no
|
||||
scaffolder or autolinker marker). That library needs only two things, and **no
|
||||
discovery code**:
|
||||
|
||||
1. Depend on the React Native SPM package and its products — in remote mode
|
||||
`.package(url: "<repo>", exact: "<version>")` +
|
||||
`.product(name: "ReactNative", …)` and
|
||||
`.product(name: "ReactNativeHeaders", …)`. (Libraries should declare a
|
||||
version RANGE in production; the consuming app pins EXACT.)
|
||||
`.product(name: "ReactHeaders", package: "<identity>")`,
|
||||
`.product(name: "ReactNativeHeaders", package: "<identity>")`, and
|
||||
`.product(name: "ReactNativeDependenciesHeaders", package: "<identity>")`,
|
||||
where `<identity>` is the URL tail, lowercased, without `.git`. A scaffolded
|
||||
manifest depends on the same React Native products. Libraries should declare
|
||||
a version RANGE in production; the consuming app pins EXACT.
|
||||
2. Ship its own generated code: set `codegenConfig.includesGeneratedCode: true`
|
||||
and generate with
|
||||
`generate-codegen-artifacts.js --path . --targetPlatform ios --source library`.
|
||||
Output lands at `<outputDir>/build/generated/ios/ReactCodegen/`, reachable
|
||||
from the manifest with one safe `.headerSearchPath(...)` into the library's
|
||||
own tree. The app-side codegen then skips the lib's spec (no duplicate
|
||||
symbols).
|
||||
The output lands at `<outputDir>/build/generated/ios/ReactCodegen/`. The
|
||||
manifest reaches it with one safe `.headerSearchPath(...)` into the library's
|
||||
own tree. The app-side codegen then skips the library's spec, so there are no
|
||||
duplicate symbols.
|
||||
|
||||
This makes the library self-contained — it carries no app-layout knowledge and
|
||||
needs no per-app codegen headers from the consuming app. Proven with
|
||||
`@chrfalch/react-native-calculator` (a hand-authored Fabric/TurboModule lib).
|
||||
The library is then self-contained. It carries no app-layout knowledge and needs
|
||||
no per-app codegen headers from the consuming app.
|
||||
`@chrfalch/react-native-calculator` (a hand-authored Fabric/TurboModule library)
|
||||
proves this.
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user