From 08804f4d467a18d3dd76f4d83c7b7cbd5e6302af Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 19:37:45 -0600 Subject: [PATCH 01/16] fix: let bare apps import React headers by name --- src/generate/bareIncludes.ts | 83 +++++++++++++++++++++++++++++++++ src/generate/iosXtool.ts | 12 ++++- src/generate/packageSwift.ts | 2 +- tests/generate.test.ts | 90 ++++++++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 src/generate/bareIncludes.ts diff --git a/src/generate/bareIncludes.ts b/src/generate/bareIncludes.ts new file mode 100644 index 0000000..51c2f0e --- /dev/null +++ b/src/generate/bareIncludes.ts @@ -0,0 +1,83 @@ +import { existsSync, readFileSync, statSync } from "node:fs"; +import { readdir, realpath, stat } from "node:fs/promises"; +import { join } from "node:path"; +import { readXcframeworkSlices } from "../pipeline/rnArtifacts.js"; + +/** The scaffold's per-library directory of `` forwards (POD_HEADERS_DIR in scaffold-package-swift.js). */ +export const POD_HEADERS_DIR = "rn-spm-pod-headers"; + +const isDir = (p: string): boolean => { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +}; + +/** Each `header ""` a module map names (umbrella, textual and private ones too; excluded ones not), in order. */ +function moduleMapHeaders(text: string): string[] { + return [...text.matchAll(/(?:^|\s)(exclude\s+)?(?:(?:umbrella|textual|private)\s+)*header\s+"([^"]+)"/g)] + .filter((m) => m[1] === undefined) + .map((m) => m[2]!); +} + +/** + * The directories that hold React Native's public Objective-C headers in `xcframeworks` (the generated + * `ios/build/xcframeworks`), so a bare app's `#import ` resolves as CocoaPods' per-pod header search + * paths allow: ReactHeadersTarget's flat `include/React`, then each directory of the device slice of + * ReactNativeHeaders.xcframework whose headers its module map names directly (`React_RCTAppDelegate/RCTAppDelegate.h` + * → `React_RCTAppDelegate`), in module map order. Headers deeper than that (`react/debug/flags.h`) keep their path + * spelling. Only existing directories; empty before the headers are staged. + */ +export function reactNativeBareIncludeDirs(xcframeworks: string): string[] { + const dirs: string[] = []; + const react = join(xcframeworks, "ReactHeadersTarget", "include", "React"); + if (isDir(react)) dirs.push(react); + const xcframework = join(xcframeworks, "ReactNativeHeaders.xcframework"); + if (!existsSync(join(xcframework, "Info.plist"))) return dirs; + // xtool builds for the device: the slice without a platform variant. + const device = readXcframeworkSlices(xcframework).find((s) => s.SupportedPlatform === "ios" && s.SupportedPlatformVariant === undefined); + if (device === undefined) return dirs; + const headers = join(xcframework, device.LibraryIdentifier, device.HeadersPath ?? "Headers"); + let map: string; + try { + map = readFileSync(join(headers, "module.modulemap"), "utf8"); + } catch { + return dirs; + } + const seen = new Set(); + for (const header of moduleMapHeaders(map)) { + const parts = header.split("/"); + if (parts.length !== 2 || parts[0] === "" || parts[0] === "." || parts[0] === ".." || seen.has(parts[0]!)) continue; + seen.add(parts[0]!); + const dir = join(headers, parts[0]!); + if (isDir(dir)) dirs.push(dir); + } + return dirs; +} + +/** + * The scaffold's `` forwards (a pod table entry's `forwardHeaders`, e.g. ``) of every + * autolinked library that has them: `/rn-spm-pod-headers`, read at React Native's `/libs/` + * aliases and resolved to the real library directory, in lib-name order. CocoaPods puts those headers in + * `Headers/Public//`, which the app sees. Empty without libs/. + */ +export async function podHeaderForwardDirs(autolinkingDir: string): Promise { + const libsDir = join(autolinkingDir, "libs"); + let names: string[]; + try { + names = (await readdir(libsDir)).sort(); + } catch { + return []; + } + const dirs: string[] = []; + for (const name of names) { + try { + const dir = join(await realpath(join(libsDir, name)), POD_HEADERS_DIR); + if ((await stat(dir)).isDirectory()) dirs.push(dir); + } catch { + continue; + } + } + return dirs; +} diff --git a/src/generate/iosXtool.ts b/src/generate/iosXtool.ts index 026909c..b2f2192 100644 --- a/src/generate/iosXtool.ts +++ b/src/generate/iosXtool.ts @@ -11,6 +11,7 @@ import { AmbiguousProjectError, openPbxproj, resolveSetting, type Pbxproj } from import { packageRoot } from "../tools/exec.js"; import { IOS_MIN } from "../versions.js"; import { APP_ICON_FILE, findAppIcon, type IconRecord } from "./appIcon.js"; +import { podHeaderForwardDirs, reactNativeBareIncludeDirs } from "./bareIncludes.js"; import { copyBareTarget } from "./bareSources.js"; import { expoClangImporterInputs } from "./expoImporter.js"; import { DEV_SUPPORT_TARGET, renderPackageSwift, type AppTargetInputs } from "./packageSwift.js"; @@ -105,11 +106,20 @@ async function writeAppSources(ctx: GenerateContext, headersDir: string, resourc const copied = await copyBareTarget( project.bare, paths.ios, project.iosTargetDir, paths.sources, resourcesDir, ctx.log ?? console.log, ); + // As CocoaPods' per-pod header search paths do: React Native's headers and the pods' forwards by bare name, after + // the app's own paths so an app header of the same name wins. + const headerSearchPaths = [ + ...new Set([ + ...copied.headerSearchPaths, + ...reactNativeBareIncludeDirs(paths.xcframeworks), + ...(await podHeaderForwardDirs(paths.autolinking)), + ]), + ]; const app: AppTargetInputs = { mixed: project.bare.mixed, bridgingHeader: copied.bridgingHeader, defines: project.bare.defines, - headerSearchPaths: copied.headerSearchPaths, + headerSearchPaths, cxxStandard: project.bare.cxxStandard, swiftHeadersDir: headersDir, }; diff --git a/src/generate/packageSwift.ts b/src/generate/packageSwift.ts index f317c4b..4c07913 100644 --- a/src/generate/packageSwift.ts +++ b/src/generate/packageSwift.ts @@ -21,7 +21,7 @@ export interface AppTargetInputs { bridgingHeader?: string; /** `KEY` or `KEY=VALUE`, as in GCC_PREPROCESSOR_DEFINITIONS. */ defines: string[]; - /** Absolute. */ + /** Absolute. Bare: the app's own, then React Native's bare-name dirs and the pods' forwards (`bareIncludes.ts`). */ headerSearchPaths: string[]; /** CLANG_CXX_LANGUAGE_STANDARD, e.g. `gnu++20`. */ cxxStandard?: string; diff --git a/tests/generate.test.ts b/tests/generate.test.ts index 8a02ca5..cb96630 100644 --- a/tests/generate.test.ts +++ b/tests/generate.test.ts @@ -11,6 +11,7 @@ import { IMPORTER_MARKER, scaffoldedImporterPaths } from "../src/generate/scaffo import { PODSPEC_FIXTURES, VENDORED_RN_SPM, scaffoldLibraries } from "./support/rnScaffold.js"; import { projectPaths, swiftHeadersDir } from "../src/paths.js"; import { openPbxproj, readTargetContent } from "../src/project/pbxproj.js"; +import { headersXcframeworkInfoPlist } from "../src/pipeline/rnArtifacts.js"; import type { ProjectInfo } from "../src/project/index.js"; import type { RuntimeFramework } from "../src/frameworks.js"; import { parse as parseYaml } from "yaml"; @@ -1225,6 +1226,95 @@ describe("writeIosXtool", () => { expect(await readFile(join(paths.iosXtool, "Package.swift"), "utf8")).toBe(before); }); + /** + * React Native's headers in `xcframeworks` as the vendored scripts stage them: ReactHeadersTarget's flat React/ dir + * and ReactNativeHeaders.xcframework, whose module map names per-module headers (simulator slice listed first). + */ + async function reactHeadersFarm(xcframeworks: string) { + const react = join(xcframeworks, "ReactHeadersTarget", "include", "React"); + await mkdir(react, { recursive: true }); + await writeFile(join(react, "RCTBundleURLProvider.h"), "@interface RCTBundleURLProvider : NSObject\n@end\n"); + const xc = join(xcframeworks, "ReactNativeHeaders.xcframework"); + const slices = [ + { LibraryIdentifier: "ios-arm64_x86_64-simulator", SupportedPlatform: "ios", SupportedPlatformVariant: "simulator", SupportedArchitectures: ["arm64", "x86_64"] }, + { LibraryIdentifier: "ios-arm64", SupportedPlatform: "ios", SupportedArchitectures: ["arm64"] }, + ]; + await mkdir(xc, { recursive: true }); + await writeFile(join(xc, "Info.plist"), headersXcframeworkInfoPlist("ReactNativeHeaders", slices)); + const map = + 'module React_RCTAppDelegate {\n header "React_RCTAppDelegate/RCTAppDelegate.h"\n export *\n}\n\n' + + 'module ReactNativeHeaders_react {\n header "react/debug/flags.h"\n export *\n}\n\n' + + 'module yoga {\n header "yoga/Yoga.h"\n export *\n}\n'; + for (const { LibraryIdentifier } of slices) { + const headers = join(xc, LibraryIdentifier, "Headers"); + for (const h of ["React_RCTAppDelegate/RCTAppDelegate.h", "react/debug/flags.h", "yoga/Yoga.h", "jsi/jsi.h"]) { + await mkdir(join(headers, h, ".."), { recursive: true }); + await writeFile(join(headers, h), "// header\n"); + } + await writeFile(join(headers, "module.modulemap"), map); + } + const device = join(xc, "ios-arm64", "Headers"); + return { react, appDelegate: join(device, "React_RCTAppDelegate"), yoga: join(device, "yoga"), device }; + } + /** The `-I` list of a rendered manifest's App cSettings, and the `-Xcc -I` list of its bridging-header flags. */ + const appIncludes = (pkg: string) => { + const c = pkg.slice(pkg.indexOf("cSettings: ["), pkg.indexOf("cxxSettings: [")); + const swift = pkg.slice(pkg.indexOf("-import-objc-header"), pkg.indexOf("linkerSettings: [")); + return { + clang: [...c.matchAll(/"-I", "([^"]+)"/g)].map((m) => m[1]!), + cxx: [...pkg.slice(pkg.indexOf("cxxSettings: ["), pkg.indexOf("swiftSettings: [")).matchAll(/"-I", "([^"]+)"/g)].map((m) => m[1]!), + bridging: [...swift.slice(0, swift.indexOf("]),")).matchAll(/"-Xcc", "-I([^"]+)"/g)].map((m) => m[1]!), + }; + }; + + it("gives a bare app's Objective-C and bridging header React Native's headers by bare name, after the app's own", async () => { + const { paths, ctx } = await bareProject(); + const farm = await reactHeadersFarm(paths.xcframeworks); + await writeIosXtool(ctx); + const { clang, cxx, bridging } = appIncludes(await readFile(join(paths.iosXtool, "Package.swift"), "utf8")); + const own = [join(paths.sources, "include"), join(paths.ios, "Vendor", "include")]; + // React/ for ; the module map's per-module dirs (device slice) for . + const react = [farm.react, farm.appDelegate, farm.yoga]; + expect(clang).toEqual([...own, ...react, swiftHeadersDir(paths.iosXtool)]); + expect(cxx).toEqual(clang); + expect(bridging).toEqual([...own, ...react]); + // Nested C++ headers keep their path spelling (); dirs the module map does not name stay out. + expect(clang).not.toContain(join(farm.device, "react", "debug")); + expect(clang).not.toContain(join(farm.device, "jsi")); + }); + + it("gives a bare app's Objective-C and bridging header the libraries' forwards, after React Native's", async () => { + const { root, paths, ctx } = await bareProject(); + const farm = await reactHeadersFarm(paths.xcframeworks); + const appAuth = await autolinkedLib(paths, root, "ReactNativeAppAuth"); + await mkdir(join(appAuth, "rn-spm-pod-headers", "AppAuth"), { recursive: true }); + await writeFile(join(appAuth, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "@import AppAuthCore;\n@import AppAuth;\n"); + await autolinkedLib(paths, root, "RNSVG"); + await writeIosXtool(ctx); + const { clang, bridging } = appIncludes(await readFile(join(paths.iosXtool, "Package.swift"), "utf8")); + const pods = join(appAuth, "rn-spm-pod-headers"); + expect(clang.slice(-2)).toEqual([pods, swiftHeadersDir(paths.iosXtool)]); + expect(bridging.at(-1)).toBe(pods); + expect(clang.indexOf(farm.yoga)).toBeLessThan(clang.indexOf(pods)); + expect(clang.filter((p) => p.includes("RNSVG"))).toEqual([]); + }); + + it("leaves an Expo app's flags without React Native's bare-name dirs and the pod forwards", async () => { + const { paths, ctx } = await expoProject("ios-target"); + const before = await (async () => { + await writeIosXtool(ctx); + return readFile(join(paths.iosXtool, "Package.swift"), "utf8"); + })(); + const farm = await reactHeadersFarm(paths.xcframeworks); + const lib = await autolinkedLib(paths, ctx.project.root, "ReactNativeAppAuth"); + await mkdir(join(lib, "rn-spm-pod-headers", "AppAuth"), { recursive: true }); + await writeFile(join(lib, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "@import AppAuth;\n"); + await writeIosXtool(ctx); + const pkg = await readFile(join(paths.iosXtool, "Package.swift"), "utf8"); + expect(pkg).toBe(before); + expect(pkg).not.toContain(farm.react); + }); + it("names a file the app target lists but the disk lacks", async () => { const { app, ctx } = await bareProject(); await rm(join(app, "Fonts", "Inter.ttf")); From ea8b8fae793a8ddb4a71c129ed22bfc240737736 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 19:38:26 -0600 Subject: [PATCH 02/16] docs: describe bare-name React header imports --- CHANGELOG.md | 3 +++ docs/bare-react-native.md | 9 +++++++++ docs/troubleshooting.md | 9 +++++++++ 3 files changed, 21 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b06f347..43ea314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea compile: every header the project references under `ios/`, outside `Pods/`, is copied with its forward in `Sources/App/include`. A referenced header that does not exist is skipped with an `ℹ` line instead of stopping the build. +- A bare app target's Objective-C sources and bridging header find React Native's headers by bare name + (`#import `) and the pod table's `` forwards (`#import `), as with + CocoaPods, instead of stopping with "'RCTAppDelegate.h' file not found"; the app's own headers still come first. ## [0.1.0-alpha.6] - 2026-11-05 diff --git a/docs/bare-react-native.md b/docs/bare-react-native.md index 8a5cf9a..389f38b 100644 --- a/docs/bare-react-native.md +++ b/docs/bare-react-native.md @@ -253,6 +253,15 @@ Swift Build names the generated Swift header `App-Swift.h` (the SwiftPM target i where `` is `PRODUCT_MODULE_NAME`, or `PRODUCT_NAME` with characters other than letters, digits and `_` turned into `_`. +React Native's public Objective-C headers are importable by their bare name (`#import `) as well as +by module (`#import `), as CocoaPods' per-pod header search paths allow, and so are the +`` spellings of the pod table's `forwardHeaders` (`#import `). The app's Objective-C +sources and its bridging header search the app's own headers and `HEADER_SEARCH_PATHS` first, then +`ios/build/xcframeworks/ReactHeadersTarget/include/React`, then each per-module directory of +`ReactNativeHeaders.xcframework` that its module map names (`React_RCTAppDelegate`, `RCTImage`, `yoga`, …), then each +autolinked library's `rn-spm-pod-headers`, so an app header with the same name wins. React Native's C++ headers keep +their path spelling (``, ``). + ## Resources The Resources phase is copied to `ios-xtool/Resources` (by file name; `*.lproj/` and `*.bundle/` stay whole) and listed diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d1dd63f..7d3dcd0 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -875,6 +875,15 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin forward in `Sources/App/include`, so `#import "AppDelegate.h"` resolves as with Xcode's header map. A header outside `ios/` is still not copied: move it into `ios/` and add it to the project. See [Sources](bare-react-native.md#sources). +- **"'RCTAppDelegate.h' file not found"** (bare React Native, compiling the app's `AppDelegate.h` or another + Objective-C source of the app target): the app imports a React Native header by its bare name + (`#import `, the spelling of the React Native 0.7x templates), which CocoaPods resolves through its + per-pod header search paths. rn-xtool 0.1.0-alpha.6 and earlier give the App target only the `` spelling. + Later releases also search React Native's header directories by bare name, after the app's own paths. A sibling + symptom is "'AppAuth/AppAuth.h' file not found" (react-native-app-auth's README has the app import it): later + releases also search each autolinked library's `rn-spm-pod-headers`, where the scaffold writes the pod table's + `forwardHeaders`. See + [Mixed Swift + Objective-C/C++ app target](bare-react-native.md#mixed-swift--objective-cc-app-target). - **"rn-xtool could not patch ":** your project has a different version of a package than the one this release of rn-xtool patches, and the patch does not apply to it (on SDK 57 or 58, a newer patch of the SDK that changed a patched file; on bare React Native, a newer patch of its line). The message names the versions. On SDK 58 (Expo From f4a2eb1a76eb35e700bed2afdece1512983df5e7 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 19:49:09 -0600 Subject: [PATCH 03/16] fix: pass the C++ standard to app ObjC++ files --- src/generate/packageSwift.ts | 25 ++++++++++++++++----- tests/generate.test.ts | 43 ++++++++++++++++++++++++++++++------ 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/src/generate/packageSwift.ts b/src/generate/packageSwift.ts index 4c07913..cecac0b 100644 --- a/src/generate/packageSwift.ts +++ b/src/generate/packageSwift.ts @@ -87,11 +87,22 @@ const CXX_VERSIONS: Record = { "1z": "1z", "17": "17", "2a": "20", "20": "20", "2b": "2b", "23": "2b", }; -function cxxLanguageStandard(value: string | undefined): string { +/** The app's C++ standard, C++20 when absent or unknown. */ +function cxxStandard(value: string | undefined): { gnu: boolean; version: string } { const m = value?.match(/^(gnu|c)\+\+(\w+)$/); const version = m ? CXX_VERSIONS[m[2]!] : undefined; - if (!m || !version) return ".cxx20"; - return `.${m[1] === "gnu" ? "gnucxx" : "cxx"}${version}`; + return m && version ? { gnu: m[1] === "gnu", version } : { gnu: false, version: "20" }; +} + +function cxxLanguageStandard(value: string | undefined): string { + const { gnu, version } = cxxStandard(value); + return `.${gnu ? "gnucxx" : "cxx"}${version}`; +} + +/** The same standard as a clang flag, e.g. `-std=gnu++20`. */ +function cxxStandardFlag(value: string | undefined): string { + const { gnu, version } = cxxStandard(value); + return `-std=${gnu ? "gnu" : "c"}++${version}`; } function cDefine(entry: string): string { @@ -132,6 +143,9 @@ function importerSwiftSettings(app: AppTargetInputs): string { * Objective-C/C++ settings; `-I swiftHeadersDir` lets them `#import "App-Swift.h"`. In a hybrid project that header * does `@import Expo;`, so they also get what Swift's clang importer gets (as clang flags, without `-Xcc`): the * compile-interfaces frameworks (``) and the importer's include dirs and module maps. + * Swift Build does not apply the package's `cxxLanguageStandard` to a mixed target, so its ObjC++/C++ files get the + * standard as `-std=` (C++ only: on a C/Objective-C file the flag is rejected) or compile with clang's default and + * fail on React Native's C++20 headers. */ function appClangSettings(app: AppTargetInputs, expo: ExpoPackageInputs | undefined): string { if (!app.mixed) return ""; @@ -141,8 +155,9 @@ function appClangSettings(app: AppTargetInputs, expo: ExpoPackageInputs | undefi ...(importer?.moduleMaps ?? []).map((m) => `-fmodule-map-file=${m}`), ...(expo ? ["-F", expo.compileInterfacesDir] : []), ]; - const body = settingLines([...app.defines.map(cDefine), flags(includes)]); - return ["cSettings", "cxxSettings"].map((name) => ` ${name}: [\n${body} ],\n`).join(""); + const shared = [...app.defines.map(cDefine), flags(includes)]; + const section = (name: string, lines: string[]) => ` ${name}: [\n${settingLines(lines)} ],\n`; + return section("cSettings", shared) + section("cxxSettings", [...shared, flags([cxxStandardFlag(app.cxxStandard)])]); } export function renderPackageSwift(i: PackageSwiftInput): RenderedPackageSwift { diff --git a/tests/generate.test.ts b/tests/generate.test.ts index cb96630..ad8a4ff 100644 --- a/tests/generate.test.ts +++ b/tests/generate.test.ts @@ -58,6 +58,10 @@ describe("renderPackageSwift", () => { it("sets language modes, platform and dependencies", () => { expect(out).toContain("swiftLanguageModes: [.v5]"); expect(out).toContain("cxxLanguageStandard: .cxx20"); + // An Expo app target is Swift-only: no C-family settings, no explicit -std. + expect(out).not.toContain("cSettings"); + expect(out).not.toContain("cxxSettings"); + expect(out).not.toContain("-std="); expect(out).toContain('platforms: [.iOS("16.4")]'); expect(out).toContain('.package(name: "ReactNative", path: "/p/ios/build/xcframeworks")'); }); @@ -230,6 +234,8 @@ describe("renderPackageSwift", () => { expect(o.manifest).not.toContain("compile-interfaces"); expect(o.manifest).not.toContain("/p/ci"); expect(o.manifest).not.toContain("cSettings"); + expect(o.manifest).not.toContain("cxxSettings"); + expect(o.manifest).not.toContain("-std="); expect(o.manifest).not.toContain("resources:"); expect(o.manifest).toContain('.package(name: "Autolinked", path: "/p/ios/build/generated/autolinking")'); expect(o.manifest).toContain('.define("DEBUG", .when(configuration: .debug))'); @@ -274,15 +280,38 @@ describe("renderPackageSwift", () => { expect(rest65.join("\n")).toBe(manifest.split("\n").slice(1).join("\n")); }); + const section = (manifest: string, name: string) => { + const start = manifest.indexOf(`${name}: [`); + expect(start).toBeGreaterThan(-1); + return manifest.slice(start + name.length, manifest.indexOf(" ],", start)); + }; + it("gives C and C++ the same defines and include paths", () => { - const section = (name: string) => { - const start = mixed.manifest.indexOf(`${name}: [`); - expect(start).toBeGreaterThan(-1); - return mixed.manifest.slice(start + name.length, mixed.manifest.indexOf(" ],", start)); + const stdLine = ' .unsafeFlags(["-std=gnu++20"]),\n'; + expect(section(mixed.manifest, "cxxSettings")).toBe(section(mixed.manifest, "cSettings") + stdLine); + expect(section(mixed.manifest, "cSettings")).toContain('.define("DEBUG", to: "1")'); + expect(section(mixed.manifest, "cSettings")).toContain('"-I", "/x/Sources/App/include"'); + }); + + // Swift Build does not apply the package's cxxLanguageStandard to a mixed target's ObjC++/C++ files. + it("passes the project's C++ standard to Objective-C++/C++ only", () => { + expect(section(mixed.manifest, "cxxSettings")).toContain('.unsafeFlags(["-std=gnu++20"]),'); + expect(section(mixed.manifest, "cSettings")).not.toContain("-std="); + expect(mixed.manifest.match(/-std=/g)).toHaveLength(1); + }); + + it("maps the C++ standard flag like cxxLanguageStandard, C++20 when absent or unknown", () => { + const flag = (cxxStandard?: string) => { + const { manifest } = renderPackageSwift({ iosDir: "/p/ios", frameworks: [], iosMin: "16.4", app: { ...noApp, mixed: true, cxxStandard } }); + return section(manifest, "cxxSettings").match(/"-std=([^"]+)"/)![1]; }; - expect(section("cSettings")).toBe(section("cxxSettings")); - expect(section("cSettings")).toContain('.define("DEBUG", to: "1")'); - expect(section("cSettings")).toContain('"-I", "/x/Sources/App/include"'); + expect(flag(undefined)).toBe("c++20"); + expect(flag("c++2a")).toBe("c++20"); + expect(flag("c++20")).toBe("c++20"); + expect(flag("gnu++20")).toBe("gnu++20"); + expect(flag("gnu++14")).toBe("gnu++14"); + expect(flag("c++0x")).toBe("c++11"); + expect(flag("compiler-default")).toBe("c++20"); }); it("lets the bridging header see the target's include paths and defines", () => { From e1a56e61409bae6d395570b5ce468f007d8b8777 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 19:49:39 -0600 Subject: [PATCH 04/16] docs: describe the app target's C++ standard --- CHANGELOG.md | 3 +++ docs/bare-react-native.md | 4 +++- docs/troubleshooting.md | 7 +++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43ea314..33048c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea - A bare app target's Objective-C sources and bridging header find React Native's headers by bare name (`#import `) and the pod table's `` forwards (`#import `), as with CocoaPods, instead of stopping with "'RCTAppDelegate.h' file not found"; the app's own headers still come first. +- A bare app target's Objective-C++ and C++ files (an `AppDelegate.mm` importing ``) compile with + the project's `CLANG_CXX_LANGUAGE_STANDARD` (C++20 when unset), instead of clang's default, which stopped on React + Native's C++20 headers with "unknown type name 'Hashable'" in `react/utils/hash_combine.h`. ## [0.1.0-alpha.6] - 2026-11-05 diff --git a/docs/bare-react-native.md b/docs/bare-react-native.md index 389f38b..e7a0671 100644 --- a/docs/bare-react-native.md +++ b/docs/bare-react-native.md @@ -245,7 +245,9 @@ remove `main.swift` from the app target. If the target compiles any `.m`, `.mm`, `.c` or `.cpp` file, it is built as one mixed-language target, the same mechanism as the scaffolded mixed libraries (the two manifests described in [How it works](how-it-works.md#mixed-language-manifests)). The bridging header is passed with `-import-objc-header` -and your header search paths and defines are applied. Verified on a device with an Objective-C module next to a Swift +and your header search paths and defines are applied. The target's `.mm` and `.cpp` files compile with the project's +`CLANG_CXX_LANGUAGE_STANDARD` (C++20 when unset), passed to them as `-std=` because Swift Build does not apply the +package's `cxxLanguageStandard` to a mixed target. Verified on a device with an Objective-C module next to a Swift module. Swift Build names the generated Swift header `App-Swift.h` (the SwiftPM target is `App`), so `build` also writes diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 7d3dcd0..9604bb1 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -884,6 +884,13 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin releases also search each autolinked library's `rn-spm-pod-headers`, where the scaffold writes the pod table's `forwardHeaders`. See [Mixed Swift + Objective-C/C++ app target](bare-react-native.md#mixed-swift--objective-cc-app-target). +- **"react/utils/hash_combine.h: … unknown type name 'Hashable'"** (bare React Native, compiling the app's + `AppDelegate.mm` or another Objective-C++ source of the app target, often with fold-expression errors from the same + header): `#import ` pulls in React Native's C++20 headers, and the file compiles with clang's + default standard (gnu++17). Swift Build does not apply the package's `cxxLanguageStandard` to a mixed-language target, + and rn-xtool 0.1.0-alpha.6 and earlier pass no `-std=` to the App target. Later releases pass the project's + `CLANG_CXX_LANGUAGE_STANDARD` (C++20 when unset) to the app's `.mm` and `.cpp` files. See + [Mixed Swift + Objective-C/C++ app target](bare-react-native.md#mixed-swift--objective-cc-app-target). - **"rn-xtool could not patch ":** your project has a different version of a package than the one this release of rn-xtool patches, and the patch does not apply to it (on SDK 57 or 58, a newer patch of the SDK that changed a patched file; on bare React Native, a newer patch of its line). The message names the versions. On SDK 58 (Expo From 91db030d285fa5035c0025618829725b6e9b87f5 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 20:04:57 -0600 Subject: [PATCH 05/16] fix: make pod header forwarders textual --- data/pods.json | 36 ++++- patches/react-native+0.88.0.patch | 138 +++++++++++--------- patches/react-native+0.88.1.patch | 138 +++++++++++--------- src/config.ts | 23 +++- tests/config.test.ts | 24 +++- tests/generate.test.ts | 4 +- tests/patches.test.ts | 4 +- tests/podTable.test.ts | 37 +++++- tests/rn-scaffolder.test.ts | 51 ++++++-- tests/rnSpm.test.ts | 3 +- vendor/rn-spm/spm/scaffold-package-swift.js | 76 +++++++---- 11 files changed, 358 insertions(+), 176 deletions(-) diff --git a/data/pods.json b/data/pods.json index 3c62a3f..599773b 100644 --- a/data/pods.json +++ b/data/pods.json @@ -4,7 +4,41 @@ "url": "https://github.com/openid/AppAuth-iOS", "exact": "3.0.0", "products": ["AppAuth"], - "forwardHeaders": { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] } + "forwardHeaders": { + "AppAuth/AppAuth.h": [ + "OIDAuthState.h", + "OIDAuthStateChangeDelegate.h", + "OIDAuthStateErrorDelegate.h", + "OIDAuthorizationRequest.h", + "OIDAuthorizationResponse.h", + "OIDAuthorizationService.h", + "OIDError.h", + "OIDErrorUtilities.h", + "OIDExternalUserAgent.h", + "OIDExternalUserAgentRequest.h", + "OIDExternalUserAgentSession.h", + "OIDGrantTypes.h", + "OIDIDToken.h", + "OIDRegistrationRequest.h", + "OIDRegistrationResponse.h", + "OIDResponseTypes.h", + "OIDScopes.h", + "OIDScopeUtilities.h", + "OIDServiceConfiguration.h", + "OIDServiceDiscovery.h", + "OIDTokenRequest.h", + "OIDTokenResponse.h", + "OIDTokenUtilities.h", + "OIDURLSessionProvider.h", + "OIDEndSessionRequest.h", + "OIDEndSessionResponse.h", + "iOS/OIDAuthState+IOS.h", + "iOS/OIDAuthorizationService+IOS.h", + "iOS/OIDExternalUserAgentIOS.h", + "iOS/OIDExternalUserAgentIOSCustomBrowser.h", + "iOS/OIDExternalUserAgentCatalyst.h" + ] + } }, "GTMSessionFetcher": { "url": "https://github.com/google/gtm-session-fetcher", diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index c4c6cd2..a28a9e2 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..f5ff25c 100644 +index cf7e587..ede4f34 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -1298,7 +1298,7 @@ index cf7e587..f5ff25c 100644 + throw new Error(`pods.${pod}.subspecs is not an object of product lists`); + } + if (forwardHeaders !== undefined && !isNameLists(forwardHeaders)) { -+ throw new Error(`pods.${pod}.forwardHeaders is not an object of module lists`); ++ throw new Error(`pods.${pod}.forwardHeaders is not an object of header lists`); + } + // $FlowFixMe[incompatible-return] checked above + return { @@ -1461,7 +1461,7 @@ index cf7e587..f5ff25c 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +414,353 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +414,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1638,38 +1638,58 @@ index cf7e587..f5ff25c 100644 + +// A pod's umbrella header that its SwiftPM package leaves outside every target +// (AppAuth-iOS's Sources/AppAuth.h), so neither `` nor -+// `"AppAuth.h"` resolves, while `@import AppAuth;` does. CocoaPods copies the -+// header into Headers/Public//. A pod table entry's `forwardHeaders` -+// (`{"AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"]}`) makes the scaffold -+// write that path under this directory, holding the `@import` lines, and put -+// the directory on the target's header search path. ++// `"AppAuth.h"` resolves. CocoaPods copies the header into ++// Headers/Public//. A pod table entry's `forwardHeaders` maps that path to ++// the headers the umbrella includes, as paths under the public header ++// directories of the pod's SwiftPM targets, which are on every importer's ++// include path (`{"AppAuth/AppAuth.h": ["OIDAuthState.h", …, ++// "iOS/OIDAuthState+IOS.h", …]}`). The scaffold writes that path under this ++// directory, holding one `#import
` per entry, and puts the directory ++// on the target's header search path. The forwarder is textual: Objective-C++ ++// compiles with -fmodules -fno-cxx-modules (Xcode's default), so an `@import` ++// in it would stop every `.mm` that includes it, while in Objective-C the ++// `#import` of a header of a module still imports the module. +const POD_HEADERS_DIR = 'rn-spm-pod-headers'; +const MODULE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/; ++const HEADER_PATH_RE = /^[A-Za-z0-9_+.-]+(\/[A-Za-z0-9_+.-]+)*\.h$/; ++ ++// A relative path ending in .h without empty, `.` or `..` segments. ++function isRelativeHeader(header /*: string */) /*: boolean */ { ++ return ( ++ /\.h$/.test(header) && ++ !path.posix.isAbsolute(header) && ++ !header.includes('\\') && ++ !header.split('/').some(seg => seg === '' || seg === '.' || seg === '..') ++ ); ++} + +// The forwarders of one pod's `forwardHeaders`; throws naming a header key -+// that is not a relative path ending in .h inside the directory, or a module -+// list that is not one. ++// that is not a relative path ending in .h inside the directory, or a header ++// list that is not one of such paths (a module name, the format before the ++// forwarders were textual, gets its own message). +function podHeaderForwarders( + pod /*: string */, + forwardHeaders /*: ?{[header: string]: Array} */, -+) /*: Array<{pod: string, header: string, modules: Array}> */ { ++) /*: Array<{pod: string, header: string, headers: Array}> */ { + return Object.keys(forwardHeaders ?? {}).map(header => { -+ const modules = forwardHeaders?.[header]; -+ const segments = header.split('/'); -+ if ( -+ !/\.h$/.test(header) || -+ path.posix.isAbsolute(header) || -+ header.includes('\\') || -+ segments.some(seg => seg === '' || seg === '.' || seg === '..') || -+ !Array.isArray(modules) || -+ modules.length === 0 || -+ !modules.every(m => typeof m === 'string' && MODULE_NAME_RE.test(m)) -+ ) { -+ throw new Error( -+ `react-native spm scaffold: pods.${pod}.forwardHeaders.${header} must be a list of module names, under a relative path ending in .h`, -+ ); ++ const headers = forwardHeaders?.[header]; ++ const where = `react-native spm scaffold: pods.${pod}.forwardHeaders.${header}`; ++ const shape = `${where} must be a list of the pod's public headers (relative paths ending in .h), under a relative path ending in .h`; ++ if (!isRelativeHeader(header) || !Array.isArray(headers) || headers.length === 0) { ++ throw new Error(shape); ++ } ++ for (const h of headers) { ++ if (typeof h === 'string' && !/\.h$/.test(h) && MODULE_NAME_RE.test(h)) { ++ throw new Error( ++ `${where} lists the module ${h}; list the pod's public headers instead (relative paths ending in .h), ` + ++ 'which the forwarder includes textually: Objective-C++ compiles without modules, so it cannot @import', ++ ); ++ } ++ if (typeof h !== 'string' || !HEADER_PATH_RE.test(h) || !isRelativeHeader(h)) { ++ throw new Error(shape); ++ } + } -+ return {pod, header, modules}; ++ return {pod, header, headers}; + }); +} + @@ -1815,7 +1835,7 @@ index cf7e587..f5ff25c 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +783,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +803,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1844,7 +1864,7 @@ index cf7e587..f5ff25c 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +881,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +901,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1857,7 +1877,7 @@ index cf7e587..f5ff25c 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +961,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +981,92 @@ function translatePodspecToSpmTarget( } } @@ -1876,7 +1896,7 @@ index cf7e587..f5ff25c 100644 const siblingNames /*: Array */ = []; - const selfPodspecName = model.name; + const externalPackages /*: Array<{pod: string, url: string, exact: string, products: Array, package: string}> */ = []; -+ const podForwarders /*: Array<{pod: string, header: string, modules: Array}> */ = []; ++ const podForwarders /*: Array<{pod: string, header: string, headers: Array}> */ = []; + // Pods built from prebuilt binaries (fix 27), each once, in podspec order. + const binaryPods /*: Array<{pod: string, product: string}> */ = []; + const unmappedPods /*: Array */ = []; @@ -1978,7 +1998,7 @@ index cf7e587..f5ff25c 100644 } } -@@ -427,15 +1112,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1132,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2036,7 +2056,7 @@ index cf7e587..f5ff25c 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1222,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1242,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2088,7 +2108,7 @@ index cf7e587..f5ff25c 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1288,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1308,101 @@ function translatePodspecToSpmTarget( ); } @@ -2190,7 +2210,7 @@ index cf7e587..f5ff25c 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1391,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1411,201 @@ function translatePodspecToSpmTarget( } } @@ -2394,7 +2414,7 @@ index cf7e587..f5ff25c 100644 warnings, }; } -@@ -565,6 +1610,9 @@ type EmitContext = { +@@ -565,6 +1630,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2404,7 +2424,7 @@ index cf7e587..f5ff25c 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1677,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1697,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2431,7 +2451,7 @@ index cf7e587..f5ff25c 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1786,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1806,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2464,7 +2484,7 @@ index cf7e587..f5ff25c 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1829,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1849,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2476,7 +2496,7 @@ index cf7e587..f5ff25c 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1849,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1869,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2550,7 +2570,7 @@ index cf7e587..f5ff25c 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1924,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1944,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2559,7 +2579,7 @@ index cf7e587..f5ff25c 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1934,13 @@ let package = Package( +@@ -778,13 +1954,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2576,7 +2596,7 @@ index cf7e587..f5ff25c 100644 ) `; } -@@ -844,6 +2000,65 @@ function reportSwiftName( +@@ -844,6 +2020,65 @@ function reportSwiftName( } } @@ -2642,7 +2662,7 @@ index cf7e587..f5ff25c 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2168,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2188,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2655,7 +2675,7 @@ index cf7e587..f5ff25c 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2189,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2209,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2664,7 +2684,7 @@ index cf7e587..f5ff25c 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2217,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2237,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2709,7 +2729,7 @@ index cf7e587..f5ff25c 100644 } catch (e) { return { depName, -@@ -1012,35 +2266,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2286,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2754,7 +2774,7 @@ index cf7e587..f5ff25c 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2308,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2328,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2762,7 +2782,7 @@ index cf7e587..f5ff25c 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2320,19 @@ function scaffoldPackageSwiftForDep( +@@ -1083,6 +2340,19 @@ function scaffoldPackageSwiftForDep( if (!ctx.dryRun) { fs.writeFileSync(pkgSwiftPath, content, 'utf8'); @@ -2782,7 +2802,7 @@ index cf7e587..f5ff25c 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2349,99 @@ function scaffoldPackageSwiftForDep( +@@ -1099,16 +2369,99 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2871,20 +2891,20 @@ index cf7e587..f5ff25c 100644 + if (fs.existsSync(podHeadersDir) && ownPodHeadersDir(podHeadersDir)) { + fs.rmSync(podHeadersDir, {recursive: true, force: true}); + } -+ for (const {pod, header, modules} of spec.podForwarders ?? []) { ++ for (const {pod, header, headers} of spec.podForwarders ?? []) { + const file = path.join(podHeadersDir, ...header.split('/')); + fs.mkdirSync(path.dirname(file), {recursive: true}); + fs.writeFileSync( + file, -+ `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the SwiftPM modules of the pod ${pod}.\n` + -+ modules.map(m => `@import ${m};\n`).join(''), ++ `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + ++ headers.map(h => `#import <${h}>\n`).join(''), + 'utf8', + ); + } } reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2474,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2494,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2893,7 +2913,7 @@ index cf7e587..f5ff25c 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2495,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2515,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2902,7 +2922,7 @@ index cf7e587..f5ff25c 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2627,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2647,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2914,7 +2934,7 @@ index cf7e587..f5ff25c 100644 }; */ -@@ -1323,6 +2661,17 @@ function scaffoldAll( +@@ -1323,6 +2681,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2932,7 +2952,7 @@ index cf7e587..f5ff25c 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2679,23 @@ function scaffoldAll( +@@ -1330,24 +2699,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2968,7 +2988,7 @@ index cf7e587..f5ff25c 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2734,9 @@ function scaffoldAll( +@@ -1386,6 +2754,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -2978,7 +2998,7 @@ index cf7e587..f5ff25c 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2755,9 @@ function scaffoldAll( +@@ -1404,6 +2775,9 @@ function scaffoldAll( } module.exports = { diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index c4c6cd2..a28a9e2 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..f5ff25c 100644 +index cf7e587..ede4f34 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -1298,7 +1298,7 @@ index cf7e587..f5ff25c 100644 + throw new Error(`pods.${pod}.subspecs is not an object of product lists`); + } + if (forwardHeaders !== undefined && !isNameLists(forwardHeaders)) { -+ throw new Error(`pods.${pod}.forwardHeaders is not an object of module lists`); ++ throw new Error(`pods.${pod}.forwardHeaders is not an object of header lists`); + } + // $FlowFixMe[incompatible-return] checked above + return { @@ -1461,7 +1461,7 @@ index cf7e587..f5ff25c 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +414,353 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +414,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1638,38 +1638,58 @@ index cf7e587..f5ff25c 100644 + +// A pod's umbrella header that its SwiftPM package leaves outside every target +// (AppAuth-iOS's Sources/AppAuth.h), so neither `` nor -+// `"AppAuth.h"` resolves, while `@import AppAuth;` does. CocoaPods copies the -+// header into Headers/Public//. A pod table entry's `forwardHeaders` -+// (`{"AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"]}`) makes the scaffold -+// write that path under this directory, holding the `@import` lines, and put -+// the directory on the target's header search path. ++// `"AppAuth.h"` resolves. CocoaPods copies the header into ++// Headers/Public//. A pod table entry's `forwardHeaders` maps that path to ++// the headers the umbrella includes, as paths under the public header ++// directories of the pod's SwiftPM targets, which are on every importer's ++// include path (`{"AppAuth/AppAuth.h": ["OIDAuthState.h", …, ++// "iOS/OIDAuthState+IOS.h", …]}`). The scaffold writes that path under this ++// directory, holding one `#import
` per entry, and puts the directory ++// on the target's header search path. The forwarder is textual: Objective-C++ ++// compiles with -fmodules -fno-cxx-modules (Xcode's default), so an `@import` ++// in it would stop every `.mm` that includes it, while in Objective-C the ++// `#import` of a header of a module still imports the module. +const POD_HEADERS_DIR = 'rn-spm-pod-headers'; +const MODULE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/; ++const HEADER_PATH_RE = /^[A-Za-z0-9_+.-]+(\/[A-Za-z0-9_+.-]+)*\.h$/; ++ ++// A relative path ending in .h without empty, `.` or `..` segments. ++function isRelativeHeader(header /*: string */) /*: boolean */ { ++ return ( ++ /\.h$/.test(header) && ++ !path.posix.isAbsolute(header) && ++ !header.includes('\\') && ++ !header.split('/').some(seg => seg === '' || seg === '.' || seg === '..') ++ ); ++} + +// The forwarders of one pod's `forwardHeaders`; throws naming a header key -+// that is not a relative path ending in .h inside the directory, or a module -+// list that is not one. ++// that is not a relative path ending in .h inside the directory, or a header ++// list that is not one of such paths (a module name, the format before the ++// forwarders were textual, gets its own message). +function podHeaderForwarders( + pod /*: string */, + forwardHeaders /*: ?{[header: string]: Array} */, -+) /*: Array<{pod: string, header: string, modules: Array}> */ { ++) /*: Array<{pod: string, header: string, headers: Array}> */ { + return Object.keys(forwardHeaders ?? {}).map(header => { -+ const modules = forwardHeaders?.[header]; -+ const segments = header.split('/'); -+ if ( -+ !/\.h$/.test(header) || -+ path.posix.isAbsolute(header) || -+ header.includes('\\') || -+ segments.some(seg => seg === '' || seg === '.' || seg === '..') || -+ !Array.isArray(modules) || -+ modules.length === 0 || -+ !modules.every(m => typeof m === 'string' && MODULE_NAME_RE.test(m)) -+ ) { -+ throw new Error( -+ `react-native spm scaffold: pods.${pod}.forwardHeaders.${header} must be a list of module names, under a relative path ending in .h`, -+ ); ++ const headers = forwardHeaders?.[header]; ++ const where = `react-native spm scaffold: pods.${pod}.forwardHeaders.${header}`; ++ const shape = `${where} must be a list of the pod's public headers (relative paths ending in .h), under a relative path ending in .h`; ++ if (!isRelativeHeader(header) || !Array.isArray(headers) || headers.length === 0) { ++ throw new Error(shape); ++ } ++ for (const h of headers) { ++ if (typeof h === 'string' && !/\.h$/.test(h) && MODULE_NAME_RE.test(h)) { ++ throw new Error( ++ `${where} lists the module ${h}; list the pod's public headers instead (relative paths ending in .h), ` + ++ 'which the forwarder includes textually: Objective-C++ compiles without modules, so it cannot @import', ++ ); ++ } ++ if (typeof h !== 'string' || !HEADER_PATH_RE.test(h) || !isRelativeHeader(h)) { ++ throw new Error(shape); ++ } + } -+ return {pod, header, modules}; ++ return {pod, header, headers}; + }); +} + @@ -1815,7 +1835,7 @@ index cf7e587..f5ff25c 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +783,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +803,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1844,7 +1864,7 @@ index cf7e587..f5ff25c 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +881,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +901,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1857,7 +1877,7 @@ index cf7e587..f5ff25c 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +961,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +981,92 @@ function translatePodspecToSpmTarget( } } @@ -1876,7 +1896,7 @@ index cf7e587..f5ff25c 100644 const siblingNames /*: Array */ = []; - const selfPodspecName = model.name; + const externalPackages /*: Array<{pod: string, url: string, exact: string, products: Array, package: string}> */ = []; -+ const podForwarders /*: Array<{pod: string, header: string, modules: Array}> */ = []; ++ const podForwarders /*: Array<{pod: string, header: string, headers: Array}> */ = []; + // Pods built from prebuilt binaries (fix 27), each once, in podspec order. + const binaryPods /*: Array<{pod: string, product: string}> */ = []; + const unmappedPods /*: Array */ = []; @@ -1978,7 +1998,7 @@ index cf7e587..f5ff25c 100644 } } -@@ -427,15 +1112,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1132,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2036,7 +2056,7 @@ index cf7e587..f5ff25c 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1222,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1242,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2088,7 +2108,7 @@ index cf7e587..f5ff25c 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1288,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1308,101 @@ function translatePodspecToSpmTarget( ); } @@ -2190,7 +2210,7 @@ index cf7e587..f5ff25c 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1391,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1411,201 @@ function translatePodspecToSpmTarget( } } @@ -2394,7 +2414,7 @@ index cf7e587..f5ff25c 100644 warnings, }; } -@@ -565,6 +1610,9 @@ type EmitContext = { +@@ -565,6 +1630,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2404,7 +2424,7 @@ index cf7e587..f5ff25c 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1677,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1697,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2431,7 +2451,7 @@ index cf7e587..f5ff25c 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1786,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1806,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2464,7 +2484,7 @@ index cf7e587..f5ff25c 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1829,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1849,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2476,7 +2496,7 @@ index cf7e587..f5ff25c 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1849,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1869,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2550,7 +2570,7 @@ index cf7e587..f5ff25c 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1924,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1944,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2559,7 +2579,7 @@ index cf7e587..f5ff25c 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1934,13 @@ let package = Package( +@@ -778,13 +1954,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2576,7 +2596,7 @@ index cf7e587..f5ff25c 100644 ) `; } -@@ -844,6 +2000,65 @@ function reportSwiftName( +@@ -844,6 +2020,65 @@ function reportSwiftName( } } @@ -2642,7 +2662,7 @@ index cf7e587..f5ff25c 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2168,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2188,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2655,7 +2675,7 @@ index cf7e587..f5ff25c 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2189,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2209,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2664,7 +2684,7 @@ index cf7e587..f5ff25c 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2217,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2237,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2709,7 +2729,7 @@ index cf7e587..f5ff25c 100644 } catch (e) { return { depName, -@@ -1012,35 +2266,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2286,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2754,7 +2774,7 @@ index cf7e587..f5ff25c 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2308,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2328,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2762,7 +2782,7 @@ index cf7e587..f5ff25c 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2320,19 @@ function scaffoldPackageSwiftForDep( +@@ -1083,6 +2340,19 @@ function scaffoldPackageSwiftForDep( if (!ctx.dryRun) { fs.writeFileSync(pkgSwiftPath, content, 'utf8'); @@ -2782,7 +2802,7 @@ index cf7e587..f5ff25c 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2349,99 @@ function scaffoldPackageSwiftForDep( +@@ -1099,16 +2369,99 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2871,20 +2891,20 @@ index cf7e587..f5ff25c 100644 + if (fs.existsSync(podHeadersDir) && ownPodHeadersDir(podHeadersDir)) { + fs.rmSync(podHeadersDir, {recursive: true, force: true}); + } -+ for (const {pod, header, modules} of spec.podForwarders ?? []) { ++ for (const {pod, header, headers} of spec.podForwarders ?? []) { + const file = path.join(podHeadersDir, ...header.split('/')); + fs.mkdirSync(path.dirname(file), {recursive: true}); + fs.writeFileSync( + file, -+ `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the SwiftPM modules of the pod ${pod}.\n` + -+ modules.map(m => `@import ${m};\n`).join(''), ++ `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + ++ headers.map(h => `#import <${h}>\n`).join(''), + 'utf8', + ); + } } reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2474,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2494,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2893,7 +2913,7 @@ index cf7e587..f5ff25c 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2495,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2515,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2902,7 +2922,7 @@ index cf7e587..f5ff25c 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2627,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2647,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2914,7 +2934,7 @@ index cf7e587..f5ff25c 100644 }; */ -@@ -1323,6 +2661,17 @@ function scaffoldAll( +@@ -1323,6 +2681,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2932,7 +2952,7 @@ index cf7e587..f5ff25c 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2679,23 @@ function scaffoldAll( +@@ -1330,24 +2699,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2968,7 +2988,7 @@ index cf7e587..f5ff25c 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2734,9 @@ function scaffoldAll( +@@ -1386,6 +2754,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -2978,7 +2998,7 @@ index cf7e587..f5ff25c 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2755,9 @@ function scaffoldAll( +@@ -1404,6 +2775,9 @@ function scaffoldAll( } module.exports = { diff --git a/src/config.ts b/src/config.ts index babac62..d16b7dc 100644 --- a/src/config.ts +++ b/src/config.ts @@ -36,7 +36,10 @@ export interface PodEntry { product?: string; /** `/` dependency → its products. */ subspecs?: Record; - /** A header the package leaves outside its targets (`AppAuth/AppAuth.h`) → the modules a forwarder `@import`s. */ + /** + * A header the package leaves outside its targets (`AppAuth/AppAuth.h`) → the headers a forwarder `#import`s, as paths + * under the public header directories of the package's targets (`OIDAuthState.h`, `iOS/OIDAuthState+IOS.h`). + */ forwardHeaders?: Record; /** * Why a pin outside a podspec's requirement was checked and is meant: the pin check prints an ℹ line with it instead @@ -86,6 +89,8 @@ const TARGET_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; /** A relative path ending in .h, without empty, `.` or `..` segments. */ const isHeaderKey = (h: string): boolean => h.endsWith(".h") && !h.includes("\\") && h.split("/").every((seg) => seg !== "" && seg !== "." && seg !== ".."); +/** A header a forwarder `#import`s: a header key in characters that cannot end the `#import <…>` line. */ +const HEADER_PATH = /^[A-Za-z0-9_+.-]+(?:\/[A-Za-z0-9_+.-]+)*\.h$/; /** * Throws a ConfigError naming `file` and the key when `pods` is not an object of pod names, each mapped to @@ -122,9 +127,19 @@ export function checkPodEntries(file: string, pods: unknown): void { } if (e.forwardHeaders !== undefined) { if (!isRecord(e.forwardHeaders)) fail(`pods.${pod}.forwardHeaders`, "an object of header paths"); - for (const [header, modules] of Object.entries(e.forwardHeaders as Record)) { - if (!isHeaderKey(header) || !isNames(modules, MODULE_NAME)) { - fail(`pods.${pod}.forwardHeaders.${header}`, "a list of module names, under a relative path ending in .h"); + for (const [header, headers] of Object.entries(e.forwardHeaders as Record)) { + const key = `pods.${pod}.forwardHeaders.${header}`; + const shape = "a list of the pod's public headers (relative paths ending in .h), under a relative path ending in .h"; + if (!isHeaderKey(header) || !Array.isArray(headers) || headers.length === 0) fail(key, shape); + for (const h of headers as unknown[]) { + // The format before forwarders were textual: an `@import` stops every Objective-C++ file that includes it. + if (typeof h === "string" && !h.endsWith(".h") && MODULE_NAME.test(h)) { + throw new ConfigError( + `${file}: ${key} lists the module ${h}; list the pod's public headers instead (relative paths ending in .h), ` + + "which the forwarder includes textually: Objective-C++ compiles without modules, so it cannot @import", + ); + } + if (typeof h !== "string" || !HEADER_PATH.test(h) || !isHeaderKey(h)) fail(key, shape); } } } diff --git a/tests/config.test.ts b/tests/config.test.ts index fa0b570..a54719f 100644 --- a/tests/config.test.ts +++ b/tests/config.test.ts @@ -64,7 +64,7 @@ describe("loadConfig", () => { url: "https://github.com/openid/AppAuth-iOS", exact: "3.0.0", products: ["AppAuth"], - forwardHeaders: { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] }, + forwardHeaders: { "AppAuth/AppAuth.h": ["OIDAuthState.h", "iOS/OIDAuthState+IOS.h"] }, }; it("reads pods", async () => { @@ -101,7 +101,11 @@ describe("loadConfig", () => { const PRODUCTS = "pods.AppAuth.products must be a list of product names"; const OUTSIDE = "pods.AppAuth.outsideRequirement must be a sentence saying why the pin is outside the requirement"; const EMPTY_TARGETS = "pods.AppAuth.emptyTargets must be a list of target names"; - const FORWARD = (h: string) => `pods.AppAuth.forwardHeaders.${h} must be a list of module names, under a relative path ending in .h`; + const FORWARD = (h: string) => + `pods.AppAuth.forwardHeaders.${h} must be a list of the pod's public headers (relative paths ending in .h), under a relative path ending in .h`; + const MODULE = (m: string) => + `pods.AppAuth.forwardHeaders.AppAuth/AppAuth.h lists the module ${m}; list the pod's public headers instead (relative ` + + "paths ending in .h), which the forwarder includes textually: Objective-C++ compiles without modules, so it cannot @import"; it.each<[string, unknown, string]>([ ["a list", ["AppAuth"], OBJECT], ["null", null, OBJECT], @@ -123,11 +127,17 @@ describe("loadConfig", () => { ["an empty product", { AppAuth: { url: APPAUTH.url, exact: "3.0.0", product: "" } }, PRODUCTS], ["a subspec without a list", entry({ subspecs: { Core: "AppAuthCore" } }), "pods.AppAuth.subspecs.Core must be a list of product names"], ["a subspec with an empty list", entry({ subspecs: { Core: [] } }), "pods.AppAuth.subspecs.Core must be a list of product names"], - ["a header key that leaves the folder", entry({ forwardHeaders: { "../x.h": ["AppAuth"] } }), FORWARD("../x.h")], - ["an absolute header key", entry({ forwardHeaders: { "/abs.h": ["AppAuth"] } }), FORWARD("/abs.h")], - ["a header key that is not a header", entry({ forwardHeaders: { "AppAuth/AppAuth.m": ["AppAuth"] } }), FORWARD("AppAuth/AppAuth.m")], - ["a header without modules", entry({ forwardHeaders: { "AppAuth/AppAuth.h": [] } }), FORWARD("AppAuth/AppAuth.h")], - ["a module that is not a module name", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["App Auth"] } }), FORWARD("AppAuth/AppAuth.h")], + ["a header key that leaves the folder", entry({ forwardHeaders: { "../x.h": ["OIDAuthState.h"] } }), FORWARD("../x.h")], + ["an absolute header key", entry({ forwardHeaders: { "/abs.h": ["OIDAuthState.h"] } }), FORWARD("/abs.h")], + ["a header key that is not a header", entry({ forwardHeaders: { "AppAuth/AppAuth.m": ["OIDAuthState.h"] } }), FORWARD("AppAuth/AppAuth.m")], + ["a forwarded header without headers", entry({ forwardHeaders: { "AppAuth/AppAuth.h": [] } }), FORWARD("AppAuth/AppAuth.h")], + ["a module name, the old form", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] } }), MODULE("AppAuthCore")], + ["a submodule name", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["OIDAuthState.h", "AppAuth.Core"] } }), MODULE("AppAuth.Core")], + ["a header that leaves the include path", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["../x.h"] } }), FORWARD("AppAuth/AppAuth.h")], + ["an absolute header", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["/abs.h"] } }), FORWARD("AppAuth/AppAuth.h")], + ["a header with a space", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["App Auth.h"] } }), FORWARD("AppAuth/AppAuth.h")], + ["a header that would end the #import", entry({ forwardHeaders: { "AppAuth/AppAuth.h": ["x.h>\n#import { const farm = await reactHeadersFarm(paths.xcframeworks); const appAuth = await autolinkedLib(paths, root, "ReactNativeAppAuth"); await mkdir(join(appAuth, "rn-spm-pod-headers", "AppAuth"), { recursive: true }); - await writeFile(join(appAuth, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "@import AppAuthCore;\n@import AppAuth;\n"); + await writeFile(join(appAuth, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "#import \n#import \n"); await autolinkedLib(paths, root, "RNSVG"); await writeIosXtool(ctx); const { clang, bridging } = appIncludes(await readFile(join(paths.iosXtool, "Package.swift"), "utf8")); @@ -1337,7 +1337,7 @@ describe("writeIosXtool", () => { const farm = await reactHeadersFarm(paths.xcframeworks); const lib = await autolinkedLib(paths, ctx.project.root, "ReactNativeAppAuth"); await mkdir(join(lib, "rn-spm-pod-headers", "AppAuth"), { recursive: true }); - await writeFile(join(lib, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "@import AppAuth;\n"); + await writeFile(join(lib, "rn-spm-pod-headers", "AppAuth", "AppAuth.h"), "#import \n"); await writeIosXtool(ctx); const pkg = await readFile(join(paths.iosXtool, "Package.swift"), "utf8"); expect(pkg).toBe(before); diff --git a/tests/patches.test.ts b/tests/patches.test.ts index 1a81080..288dacf 100644 --- a/tests/patches.test.ts +++ b/tests/patches.test.ts @@ -1065,8 +1065,8 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the const root = await project(); await installPkg(root, "react-native-app-auth", "8.5.1"); const forwarder = - "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the SwiftPM modules of the pod AppAuth.\n" + - "@import AppAuthCore;\n@import AppAuth;\n"; + "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the public headers of the pod AppAuth.\n" + + "#import \n#import \n"; const current = { "Package.swift": manifest(4, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; await put(root, "patches/react-native-app-auth+8.5.1.patch", newFilesPatch("react-native-app-auth", current)); await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(3, "0.87.1")); diff --git a/tests/podTable.test.ts b/tests/podTable.test.ts index 62f60f0..5988524 100644 --- a/tests/podTable.test.ts +++ b/tests/podTable.test.ts @@ -16,7 +16,42 @@ const APPAUTH = { url: "https://github.com/openid/AppAuth-iOS", exact: "3.0.0", products: ["AppAuth"], - forwardHeaders: { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] }, + // AppAuth-iOS 3.0.0's Sources/AppAuth.h: its imports, then its iOS and Mac Catalyst branch (Sources/AppAuth/iOS). + forwardHeaders: { + "AppAuth/AppAuth.h": [ + "OIDAuthState.h", + "OIDAuthStateChangeDelegate.h", + "OIDAuthStateErrorDelegate.h", + "OIDAuthorizationRequest.h", + "OIDAuthorizationResponse.h", + "OIDAuthorizationService.h", + "OIDError.h", + "OIDErrorUtilities.h", + "OIDExternalUserAgent.h", + "OIDExternalUserAgentRequest.h", + "OIDExternalUserAgentSession.h", + "OIDGrantTypes.h", + "OIDIDToken.h", + "OIDRegistrationRequest.h", + "OIDRegistrationResponse.h", + "OIDResponseTypes.h", + "OIDScopes.h", + "OIDScopeUtilities.h", + "OIDServiceConfiguration.h", + "OIDServiceDiscovery.h", + "OIDTokenRequest.h", + "OIDTokenResponse.h", + "OIDTokenUtilities.h", + "OIDURLSessionProvider.h", + "OIDEndSessionRequest.h", + "OIDEndSessionResponse.h", + "iOS/OIDAuthState+IOS.h", + "iOS/OIDAuthorizationService+IOS.h", + "iOS/OIDExternalUserAgentIOS.h", + "iOS/OIDExternalUserAgentIOSCustomBrowser.h", + "iOS/OIDExternalUserAgentCatalyst.h", + ], + }, }; const INTROSPECT = { url: "https://github.com/siteline/swiftui-introspect", exact: "1.5.0", products: ["SwiftUIIntrospect"] }; /** ML Kit's source pods (spec goal 3.1; the product names G1 linked). */ diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 724e080..9631405 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -168,7 +168,11 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(src("scaffold-package-swift.js")).toMatch(/const REACT_CORE_DEP_EXACT = \[[^\]]*'ReactNativeDependencies'/); }); it("scaffold-package-swift.js has the pod header forwarder hunk", () => { - expect(src("scaffold-package-swift.js")).toContain("const POD_HEADERS_DIR = 'rn-spm-pod-headers'"); + const f = src("scaffold-package-swift.js"); + expect(f).toContain("const POD_HEADERS_DIR = 'rn-spm-pod-headers'"); + // Textual forwarders: Objective-C++ compiles without modules. + expect(f).toContain("headers.map(h => `#import <${h}>\\n`)"); + expect(f).not.toContain("@import ${m};"); }); it("scaffold-package-swift.js has the fix 27 hunk", () => { const f = src("scaffold-package-swift.js"); @@ -2145,14 +2149,17 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { }); describe("13: pod umbrella header forwarders", () => { - const FORWARD = { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] }; + const FORWARD = { "AppAuth/AppAuth.h": ["OIDAuthState.h", "iOS/OIDAuthState+IOS.h"] }; const forwarding = (forwardHeaders: unknown) => tableFile({ AppAuth: { ...APPAUTH, forwardHeaders } }); const FORWARDER = [ - "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the SwiftPM modules of the pod AppAuth.", - "@import AppAuthCore;", - "@import AppAuth;", + "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the public headers of the pod AppAuth.", + "#import ", + "#import ", "", ].join("\n"); + const SHAPE = (key: string) => + `react-native spm scaffold: pods.AppAuth.forwardHeaders.${key} must be a list of the pod's public headers ` + + "(relative paths ending in .h), under a relative path ending in .h"; const settings = (pkg: string, key: string) => pkg.split("\n").find((l) => l.trim().startsWith(`${key}:`)) ?? ""; it("13: writes a forwarding header for each forwardHeaders entry (AppAuth's shape)", () => { @@ -2164,6 +2171,13 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { expect(Object.keys(run.files).filter((k) => k.includes("rn-spm-pod-headers"))).toEqual(["foo/rn-spm-pod-headers/AppAuth/AppAuth.h"]); }); + it("13: the forwarder includes the pod's headers textually, without @import (Objective-C++ compiles without modules)", () => { + const run = scaffold(APPAUTH_DEP, forwarding(FORWARD)); + const text = run.files["foo/rn-spm-pod-headers/AppAuth/AppAuth.h"]!; + expect(text.split("\n").filter((l) => l.startsWith("#import "))).toEqual(["#import ", "#import "]); + expect(text).not.toContain("@import"); + }); + it("13: the forwarder holds no absolute path", () => { const run = scaffold(APPAUTH_DEP, forwarding(FORWARD)); const text = readFileSync(path.join(run.roots["foo"]!, "rn-spm-pod-headers/AppAuth/AppAuth.h"), "utf8"); @@ -2192,19 +2206,32 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { it.each(["../x.h", "/abs.h", "AppAuth/../../x.h", "AppAuth/AppAuth.m", "./AppAuth.h"])( "13: refuses a header key that leaves the folder or is not a header (%s)", (key) => { - const run = scaffold(APPAUTH_DEP, forwarding({ [key]: ["AppAuth"] })); + const run = scaffold(APPAUTH_DEP, forwarding({ [key]: ["OIDAuthState.h"] })); expect(run.statuses["foo"]).toBe("error"); - expect(run.results[0]!.reason).toBe( - `react-native spm scaffold: pods.AppAuth.forwardHeaders.${key} must be a list of module names, under a relative path ending in .h`, - ); + expect(run.results[0]!.reason).toBe(SHAPE(key)); expect(existsSync(path.join(run.roots["foo"]!, "rn-spm-pod-headers"))).toBe(false); }, ); - it("13: refuses a module name that is not one", () => { - const run = scaffold(APPAUTH_DEP, forwarding({ "AppAuth/AppAuth.h": ["AppAuth;\n#import "] })); + it.each([[["OIDAuthState.h>\n#import { + const run = scaffold(APPAUTH_DEP, forwarding({ "AppAuth/AppAuth.h": headers })); + expect(run.statuses["foo"]).toBe("error"); + expect(run.results[0]!.reason).toBe(SHAPE("AppAuth/AppAuth.h")); + expect(existsSync(path.join(run.roots["foo"]!, "rn-spm-pod-headers"))).toBe(false); + }, + ); + + it("13: refuses a module name in a header list, saying to list the pod's public headers", () => { + const run = scaffold(APPAUTH_DEP, forwarding({ "AppAuth/AppAuth.h": ["OIDAuthState.h", "AppAuthCore", "AppAuth"] })); expect(run.statuses["foo"]).toBe("error"); - expect(run.results[0]!.reason).toContain("pods.AppAuth.forwardHeaders.AppAuth/AppAuth.h must be a list of module names"); + expect(run.results[0]!.reason).toBe( + "react-native spm scaffold: pods.AppAuth.forwardHeaders.AppAuth/AppAuth.h lists the module AppAuthCore; list the " + + "pod's public headers instead (relative paths ending in .h), which the forwarder includes textually: " + + "Objective-C++ compiles without modules, so it cannot @import", + ); + expect(existsSync(path.join(run.roots["foo"]!, "rn-spm-pod-headers"))).toBe(false); }); }); diff --git a/tests/rnSpm.test.ts b/tests/rnSpm.test.ts index 5094e92..0f41080 100644 --- a/tests/rnSpm.test.ts +++ b/tests/rnSpm.test.ts @@ -426,7 +426,8 @@ describe("runRnSpm", () => { for (const c of rnRuns) expect(c.env?.["RN_SPM_POD_TABLE"]).toBe(POD_TABLE); // The table is written once, before the first run: the config's entry over rn-xtool's own and the scaffolder's. expect(h.tables).toEqual([mergedPodTable(pods)]); - expect(h.tables[0]!.pods["AppAuth"]).toEqual({ ...pods.AppAuth, forwardHeaders: { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] } }); + const shipped = JSON.parse(readFileSync(path.join(packageRoot(), "data", "pods.json"), "utf8")).pods.AppAuth; + expect(h.tables[0]!.pods["AppAuth"]).toEqual({ ...pods.AppAuth, forwardHeaders: shipped.forwardHeaders }); expect(h.tables[0]!.source["AppAuth"]).toBe("config"); } // Without a config entry, still the shipped table. diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index f5ff25c..ede4f34 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -222,7 +222,7 @@ function podTableEntry( throw new Error(`pods.${pod}.subspecs is not an object of product lists`); } if (forwardHeaders !== undefined && !isNameLists(forwardHeaders)) { - throw new Error(`pods.${pod}.forwardHeaders is not an object of module lists`); + throw new Error(`pods.${pod}.forwardHeaders is not an object of header lists`); } // $FlowFixMe[incompatible-return] checked above return { @@ -587,38 +587,58 @@ const REACT_BARE_HEADERS_DIR = 'rn-spm-react-headers'; // A pod's umbrella header that its SwiftPM package leaves outside every target // (AppAuth-iOS's Sources/AppAuth.h), so neither `` nor -// `"AppAuth.h"` resolves, while `@import AppAuth;` does. CocoaPods copies the -// header into Headers/Public//. A pod table entry's `forwardHeaders` -// (`{"AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"]}`) makes the scaffold -// write that path under this directory, holding the `@import` lines, and put -// the directory on the target's header search path. +// `"AppAuth.h"` resolves. CocoaPods copies the header into +// Headers/Public//. A pod table entry's `forwardHeaders` maps that path to +// the headers the umbrella includes, as paths under the public header +// directories of the pod's SwiftPM targets, which are on every importer's +// include path (`{"AppAuth/AppAuth.h": ["OIDAuthState.h", …, +// "iOS/OIDAuthState+IOS.h", …]}`). The scaffold writes that path under this +// directory, holding one `#import
` per entry, and puts the directory +// on the target's header search path. The forwarder is textual: Objective-C++ +// compiles with -fmodules -fno-cxx-modules (Xcode's default), so an `@import` +// in it would stop every `.mm` that includes it, while in Objective-C the +// `#import` of a header of a module still imports the module. const POD_HEADERS_DIR = 'rn-spm-pod-headers'; const MODULE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/; +const HEADER_PATH_RE = /^[A-Za-z0-9_+.-]+(\/[A-Za-z0-9_+.-]+)*\.h$/; + +// A relative path ending in .h without empty, `.` or `..` segments. +function isRelativeHeader(header /*: string */) /*: boolean */ { + return ( + /\.h$/.test(header) && + !path.posix.isAbsolute(header) && + !header.includes('\\') && + !header.split('/').some(seg => seg === '' || seg === '.' || seg === '..') + ); +} // The forwarders of one pod's `forwardHeaders`; throws naming a header key -// that is not a relative path ending in .h inside the directory, or a module -// list that is not one. +// that is not a relative path ending in .h inside the directory, or a header +// list that is not one of such paths (a module name, the format before the +// forwarders were textual, gets its own message). function podHeaderForwarders( pod /*: string */, forwardHeaders /*: ?{[header: string]: Array} */, -) /*: Array<{pod: string, header: string, modules: Array}> */ { +) /*: Array<{pod: string, header: string, headers: Array}> */ { return Object.keys(forwardHeaders ?? {}).map(header => { - const modules = forwardHeaders?.[header]; - const segments = header.split('/'); - if ( - !/\.h$/.test(header) || - path.posix.isAbsolute(header) || - header.includes('\\') || - segments.some(seg => seg === '' || seg === '.' || seg === '..') || - !Array.isArray(modules) || - modules.length === 0 || - !modules.every(m => typeof m === 'string' && MODULE_NAME_RE.test(m)) - ) { - throw new Error( - `react-native spm scaffold: pods.${pod}.forwardHeaders.${header} must be a list of module names, under a relative path ending in .h`, - ); + const headers = forwardHeaders?.[header]; + const where = `react-native spm scaffold: pods.${pod}.forwardHeaders.${header}`; + const shape = `${where} must be a list of the pod's public headers (relative paths ending in .h), under a relative path ending in .h`; + if (!isRelativeHeader(header) || !Array.isArray(headers) || headers.length === 0) { + throw new Error(shape); + } + for (const h of headers) { + if (typeof h === 'string' && !/\.h$/.test(h) && MODULE_NAME_RE.test(h)) { + throw new Error( + `${where} lists the module ${h}; list the pod's public headers instead (relative paths ending in .h), ` + + 'which the forwarder includes textually: Objective-C++ compiles without modules, so it cannot @import', + ); + } + if (typeof h !== 'string' || !HEADER_PATH_RE.test(h) || !isRelativeHeader(h)) { + throw new Error(shape); + } } - return {pod, header, modules}; + return {pod, header, headers}; }); } @@ -972,7 +992,7 @@ function translatePodspecToSpmTarget( let coreReactNative = false; const siblingNames /*: Array */ = []; const externalPackages /*: Array<{pod: string, url: string, exact: string, products: Array, package: string}> */ = []; - const podForwarders /*: Array<{pod: string, header: string, modules: Array}> */ = []; + const podForwarders /*: Array<{pod: string, header: string, headers: Array}> */ = []; // Pods built from prebuilt binaries (fix 27), each once, in podspec order. const binaryPods /*: Array<{pod: string, product: string}> */ = []; const unmappedPods /*: Array */ = []; @@ -2432,13 +2452,13 @@ function scaffoldPackageSwiftForDep( if (fs.existsSync(podHeadersDir) && ownPodHeadersDir(podHeadersDir)) { fs.rmSync(podHeadersDir, {recursive: true, force: true}); } - for (const {pod, header, modules} of spec.podForwarders ?? []) { + for (const {pod, header, headers} of spec.podForwarders ?? []) { const file = path.join(podHeadersDir, ...header.split('/')); fs.mkdirSync(path.dirname(file), {recursive: true}); fs.writeFileSync( file, - `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the SwiftPM modules of the pod ${pod}.\n` + - modules.map(m => `@import ${m};\n`).join(''), + `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + + headers.map(h => `#import <${h}>\n`).join(''), 'utf8', ); } From 94a7073382aef646415208c185971a23af9e8b5c Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 20:07:55 -0600 Subject: [PATCH 06/16] chore: bump the scaffold revision to 5 --- docs/troubleshooting.md | 28 ++++---- patches/react-native+0.88.0.patch | 70 ++++++++++--------- patches/react-native+0.88.1.patch | 70 ++++++++++--------- src/pipeline/patches.ts | 2 +- tests/capabilities.test.ts | 2 +- .../datetimepicker/Package.swift | 2 +- .../Package.swift | 2 +- .../react-native-pager-view/Package.swift | 2 +- .../Package@swift-6.5.swift | 2 +- .../react-native-screens/Package.swift | 2 +- .../react-native-svg/Package.swift | 2 +- .../react-native-webview/Package.swift | 2 +- tests/patches.test.ts | 52 +++++++------- tests/rn-scaffolder.test.ts | 18 ++--- vendor/rn-spm/spm/scaffold-package-swift.js | 6 +- 15 files changed, 137 insertions(+), 125 deletions(-) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 9604bb1..4a3a688 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -807,18 +807,20 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin `npm install`, and the next build applies the patch again. A nested package's patch (`+++.patch`) is named ` => `. A package installed at another version than its patch's is not skipped: patch-package applies the patch with its own version warning. -- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 4); delete it so rn-xtool +- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 5); delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old Package.swift)":** the `patches` step found a persisted scaffold patch from an older scaffolder. Revision 1 patches lack the Swift importer - paths of mixed libraries, revision 2 patches lack those of clang-only libraries and their module map, and revision 3 - patches lack fixes 20–22 and 24 (fixes 17 to 24 in [the scaffolder fixes](upstream/react-native-scaffolder.md)). - Without them, Swift code that imports a scaffolded library (the app, or expo-router importing react-native-screens) - can fail with `'RNSReactBaseView.h' file not found` (a mixed library, such as react-native-screens 4.26) or - `'RNSDefines.h' file not found` (a clang-only one, such as react-native-screens 4.30). Do what the warning says: - delete the patch, remove the library from `node_modules` and reinstall it, then build; rn-xtool scaffolds it again and - persists the new patch. This release's scaffolder is revision 4, so each scaffold patch persisted before it gets the - line at every build until it is regenerated, for example `⚠ patches/react-native-screens+4.30.0.patch was written by - an older rn-xtool scaffolder (revision 3, now 4); delete it so rn-xtool regenerates it (also remove + paths of mixed libraries, revision 2 patches lack those of clang-only libraries and their module map, revision 3 + patches lack fixes 20–22 and 24 (fixes 17 to 24 in [the scaffolder fixes](upstream/react-native-scaffolder.md)), and + revision 4 patches hold pod header forwarders that `@import` modules (fix 13). Without those fixes, Swift code that + imports a scaffolded library (the app, or expo-router importing react-native-screens) can fail with + `'RNSReactBaseView.h' file not found` (a mixed library, such as react-native-screens 4.26) or `'RNSDefines.h' file + not found` (a clang-only one, such as react-native-screens 4.30), and an Objective-C++ file that imports + `` stops with `use of '@import' when modules are disabled`. Do what the warning says: delete the + patch, remove the library from `node_modules` and reinstall it, then build; rn-xtool scaffolds it again and persists + the new patch. This release's scaffolder is revision 5, so each scaffold patch persisted before it gets the line at + every build until it is regenerated, for example `⚠ patches/react-native-screens+4.30.0.patch was written by an + older rn-xtool scaffolder (revision 4, now 5); delete it so rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)`. Until then the build goes on with the older manifest. - **"⚠ patches/ was scaffolded for React Native ; delete it so rn-xtool regenerates it for @@ -827,21 +829,21 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin Do the same as for the revision warning above. Both warnings also read patches with the marker's name before the rename, `expo-xtool-scaffold-revision` (apps scaffolded before 0.1.0-alpha.1). - **"ℹ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 4, React Native ): rn-xtool replaced it with the persisted one":** a teammate + patches/ (revision 5, React Native ): rn-xtool replaced it with the persisted one":** a teammate committed a regenerated scaffold patch, and your `node_modules` still had the copy an older patch wrote (patch-package does not replace a file that exists). rn-xtool owns these generated files, so the `patches` step removes the files the current patch creates and patch-package writes them again; the line is printed once patch-package has done so. Nothing to do; files the older scaffold wrote and the current one does not stay in place. This happens only when the patch holds nothing but scaffolded new files. - **"⚠ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 4, React Native ), and that patch also changes the library's own files, so + patches/ (revision 5, React Native ), and that patch also changes the library's own files, so rn-xtool does not replace it: run rm -rf node_modules/ && npm install, then build again":** the same case, but the persisted patch also holds your own fix to the library. rn-xtool persists a scaffold with `patch-package `, which writes everything that differs from the published package into one patch. Removing only the scaffold files would leave a patch that patch-package can apply neither forward nor backward, so rn-xtool changes nothing and the build goes on with the older manifest. Run the command: the reinstall gives the published package, and the next build applies the whole patch. -- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 4)" (or +- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 5)" (or "was scaffolded for React Native , not "), followed by "rn-xtool removed it so the rn-spm step scaffolds it again":** a library has no persisted patch, and the manifest rn-xtool generated for it is out of date, for example after you deleted a stale patch but kept the package installed. The `rn-spm` step scaffolds it again diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index a28a9e2..761d1d6 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..ede4f34 100644 +index cf7e587..b41cd3e 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -1186,7 +1186,7 @@ index cf7e587..ede4f34 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +114,274 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +114,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -1200,8 +1200,10 @@ index cf7e587..ede4f34 100644 +// (CLANG_MODULE_MAP). Revision 4 (fixes 20–24): dependencies on packages that +// are not linked for iOS left out, with the subspecs that declare them; the +// Swift 5 language mode; the umbrella-directory shim; the codegen header's -+// bare spelling; and Swift compilation conditions. -+const RN_XTOOL_SCAFFOLD_REVISION = 4; ++// bare spelling; and Swift compilation conditions. Revision 5: pod header ++// forwarders that `#import` the pod's public headers instead of `@import`ing ++// its modules, which stopped every Objective-C++ file that included them. ++const RN_XTOOL_SCAFFOLD_REVISION = 5; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -1461,7 +1463,7 @@ index cf7e587..ede4f34 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +414,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +416,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1835,7 +1837,7 @@ index cf7e587..ede4f34 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +803,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +805,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1864,7 +1866,7 @@ index cf7e587..ede4f34 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +901,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +903,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1877,7 +1879,7 @@ index cf7e587..ede4f34 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +981,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +983,92 @@ function translatePodspecToSpmTarget( } } @@ -1998,7 +2000,7 @@ index cf7e587..ede4f34 100644 } } -@@ -427,15 +1132,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1134,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2056,7 +2058,7 @@ index cf7e587..ede4f34 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1242,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1244,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2108,7 +2110,7 @@ index cf7e587..ede4f34 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1308,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1310,101 @@ function translatePodspecToSpmTarget( ); } @@ -2210,7 +2212,7 @@ index cf7e587..ede4f34 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1411,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1413,201 @@ function translatePodspecToSpmTarget( } } @@ -2414,7 +2416,7 @@ index cf7e587..ede4f34 100644 warnings, }; } -@@ -565,6 +1630,9 @@ type EmitContext = { +@@ -565,6 +1632,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2424,7 +2426,7 @@ index cf7e587..ede4f34 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1697,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1699,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2451,7 +2453,7 @@ index cf7e587..ede4f34 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1806,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1808,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2484,7 +2486,7 @@ index cf7e587..ede4f34 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1849,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1851,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2496,7 +2498,7 @@ index cf7e587..ede4f34 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1869,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1871,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2570,7 +2572,7 @@ index cf7e587..ede4f34 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1944,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1946,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2579,7 +2581,7 @@ index cf7e587..ede4f34 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1954,13 @@ let package = Package( +@@ -778,13 +1956,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2596,7 +2598,7 @@ index cf7e587..ede4f34 100644 ) `; } -@@ -844,6 +2020,65 @@ function reportSwiftName( +@@ -844,6 +2022,65 @@ function reportSwiftName( } } @@ -2662,7 +2664,7 @@ index cf7e587..ede4f34 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2188,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2675,7 +2677,7 @@ index cf7e587..ede4f34 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2209,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2684,7 +2686,7 @@ index cf7e587..ede4f34 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2237,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2729,7 +2731,7 @@ index cf7e587..ede4f34 100644 } catch (e) { return { depName, -@@ -1012,35 +2286,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2288,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2774,7 +2776,7 @@ index cf7e587..ede4f34 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2328,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2330,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2782,7 +2784,7 @@ index cf7e587..ede4f34 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2340,19 @@ function scaffoldPackageSwiftForDep( +@@ -1083,6 +2342,19 @@ function scaffoldPackageSwiftForDep( if (!ctx.dryRun) { fs.writeFileSync(pkgSwiftPath, content, 'utf8'); @@ -2802,7 +2804,7 @@ index cf7e587..ede4f34 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2369,99 @@ function scaffoldPackageSwiftForDep( +@@ -1099,16 +2371,99 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2904,7 +2906,7 @@ index cf7e587..ede4f34 100644 } reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2494,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2496,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2913,7 +2915,7 @@ index cf7e587..ede4f34 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2515,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2517,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2922,7 +2924,7 @@ index cf7e587..ede4f34 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2647,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2649,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2934,7 +2936,7 @@ index cf7e587..ede4f34 100644 }; */ -@@ -1323,6 +2681,17 @@ function scaffoldAll( +@@ -1323,6 +2683,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2952,7 +2954,7 @@ index cf7e587..ede4f34 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2699,23 @@ function scaffoldAll( +@@ -1330,24 +2701,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2988,7 +2990,7 @@ index cf7e587..ede4f34 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2754,9 @@ function scaffoldAll( +@@ -1386,6 +2756,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -2998,7 +3000,7 @@ index cf7e587..ede4f34 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2775,9 @@ function scaffoldAll( +@@ -1404,6 +2777,9 @@ function scaffoldAll( } module.exports = { diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index a28a9e2..761d1d6 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..ede4f34 100644 +index cf7e587..b41cd3e 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -1186,7 +1186,7 @@ index cf7e587..ede4f34 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +114,274 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +114,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -1200,8 +1200,10 @@ index cf7e587..ede4f34 100644 +// (CLANG_MODULE_MAP). Revision 4 (fixes 20–24): dependencies on packages that +// are not linked for iOS left out, with the subspecs that declare them; the +// Swift 5 language mode; the umbrella-directory shim; the codegen header's -+// bare spelling; and Swift compilation conditions. -+const RN_XTOOL_SCAFFOLD_REVISION = 4; ++// bare spelling; and Swift compilation conditions. Revision 5: pod header ++// forwarders that `#import` the pod's public headers instead of `@import`ing ++// its modules, which stopped every Objective-C++ file that included them. ++const RN_XTOOL_SCAFFOLD_REVISION = 5; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -1461,7 +1463,7 @@ index cf7e587..ede4f34 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +414,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +416,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1835,7 +1837,7 @@ index cf7e587..ede4f34 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +803,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +805,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1864,7 +1866,7 @@ index cf7e587..ede4f34 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +901,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +903,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1877,7 +1879,7 @@ index cf7e587..ede4f34 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +981,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +983,92 @@ function translatePodspecToSpmTarget( } } @@ -1998,7 +2000,7 @@ index cf7e587..ede4f34 100644 } } -@@ -427,15 +1132,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1134,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2056,7 +2058,7 @@ index cf7e587..ede4f34 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1242,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1244,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2108,7 +2110,7 @@ index cf7e587..ede4f34 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1308,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1310,101 @@ function translatePodspecToSpmTarget( ); } @@ -2210,7 +2212,7 @@ index cf7e587..ede4f34 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1411,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1413,201 @@ function translatePodspecToSpmTarget( } } @@ -2414,7 +2416,7 @@ index cf7e587..ede4f34 100644 warnings, }; } -@@ -565,6 +1630,9 @@ type EmitContext = { +@@ -565,6 +1632,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2424,7 +2426,7 @@ index cf7e587..ede4f34 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1697,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1699,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2451,7 +2453,7 @@ index cf7e587..ede4f34 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1806,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1808,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2484,7 +2486,7 @@ index cf7e587..ede4f34 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1849,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1851,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2496,7 +2498,7 @@ index cf7e587..ede4f34 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1869,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1871,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2570,7 +2572,7 @@ index cf7e587..ede4f34 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1944,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1946,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2579,7 +2581,7 @@ index cf7e587..ede4f34 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1954,13 @@ let package = Package( +@@ -778,13 +1956,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2596,7 +2598,7 @@ index cf7e587..ede4f34 100644 ) `; } -@@ -844,6 +2020,65 @@ function reportSwiftName( +@@ -844,6 +2022,65 @@ function reportSwiftName( } } @@ -2662,7 +2664,7 @@ index cf7e587..ede4f34 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2188,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2675,7 +2677,7 @@ index cf7e587..ede4f34 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2209,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2684,7 +2686,7 @@ index cf7e587..ede4f34 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2237,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2729,7 +2731,7 @@ index cf7e587..ede4f34 100644 } catch (e) { return { depName, -@@ -1012,35 +2286,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2288,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2774,7 +2776,7 @@ index cf7e587..ede4f34 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2328,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2330,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2782,7 +2784,7 @@ index cf7e587..ede4f34 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2340,19 @@ function scaffoldPackageSwiftForDep( +@@ -1083,6 +2342,19 @@ function scaffoldPackageSwiftForDep( if (!ctx.dryRun) { fs.writeFileSync(pkgSwiftPath, content, 'utf8'); @@ -2802,7 +2804,7 @@ index cf7e587..ede4f34 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2369,99 @@ function scaffoldPackageSwiftForDep( +@@ -1099,16 +2371,99 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2904,7 +2906,7 @@ index cf7e587..ede4f34 100644 } reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2494,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2496,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2913,7 +2915,7 @@ index cf7e587..ede4f34 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2515,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2517,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2922,7 +2924,7 @@ index cf7e587..ede4f34 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2647,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2649,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2934,7 +2936,7 @@ index cf7e587..ede4f34 100644 }; */ -@@ -1323,6 +2681,17 @@ function scaffoldAll( +@@ -1323,6 +2683,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2952,7 +2954,7 @@ index cf7e587..ede4f34 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2699,23 @@ function scaffoldAll( +@@ -1330,24 +2701,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2988,7 +2990,7 @@ index cf7e587..ede4f34 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2754,9 @@ function scaffoldAll( +@@ -1386,6 +2756,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -2998,7 +3000,7 @@ index cf7e587..ede4f34 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2775,9 @@ function scaffoldAll( +@@ -1404,6 +2777,9 @@ function scaffoldAll( } module.exports = { diff --git a/src/pipeline/patches.ts b/src/pipeline/patches.ts index 8af8e03..40d813a 100644 --- a/src/pipeline/patches.ts +++ b/src/pipeline/patches.ts @@ -359,7 +359,7 @@ const SLOT_LABEL_RE = /^\+\/\/ Cache slot: (\S+)\/dual-flavor\s*$/m; const REVISION_RE = /^\+\/\/ (?:rn|expo)-xtool-scaffold-revision: (\d+)\s*$/m; /** The scaffolder's RN_XTOOL_SCAFFOLD_REVISION (patches/react-native+0.88.{0,1}.patch and vendor/rn-spm). */ -export const SCAFFOLD_REVISION = 4; +export const SCAFFOLD_REVISION = 5; const PATCH_PODS_RE = /^\+\/\/ rn-xtool-pods: (.*?)\s*$/m; const MANIFEST_PODS_RE = /^\/\/ rn-xtool-pods: (.*?)\s*$/m; diff --git a/tests/capabilities.test.ts b/tests/capabilities.test.ts index 19a6080..e2b7bab 100644 --- a/tests/capabilities.test.ts +++ b/tests/capabilities.test.ts @@ -605,7 +605,7 @@ describe("detectCapabilities", () => { }); const lines = [ "// AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package.", - "// rn-xtool-scaffold-revision: 4", + "// rn-xtool-scaffold-revision: 5", "// rn-xtool-pods: AppAuth=3.0.0", "// Cache slot: 0.88.1/dual-flavor", ]; diff --git a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift index e4a7425..fe8832e 100644 --- a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift +++ b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["ios","ios/fabric","ios/fabric/cpp/react/renderer/components/RNDateTimePicker","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift index f7c21e9..8a94b2f 100644 --- a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["apple/Handlers","apple","shared/runtime","shared/shadowNodes/react/renderer/components/rngesturehandler_codegen","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift index 7c03a4c..efafa95 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.4;(experimentalMultiLang) // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift index eecc097..3a221f3 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.5 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift index 1288787..df191ac 100644 --- a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["common/cpp","common/cpp/react/renderer/components/rnscreens","common/cpp/react/renderer/components/rnscreens/utils","cpp","ios","ios/bridging","ios/conversion","ios/events","ios/helpers/container","ios/helpers/image","ios/helpers/scroll-view","ios/integrations","ios/safe-area","ios/stubs","ios/tabs","ios/tabs/bottom-accessory","ios/tabs/extensions","ios/tabs/host","ios/tabs/screen","ios/utils","ios/utils/extensions",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift index d0156ed..36f04fe 100644 --- a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["common/cpp","apple/Brushes","apple/Elements","apple/Filters/MetalCI","apple/Filters","apple","apple/Shapes","apple/Text","apple/Utils","apple/ViewManagers","common/cpp/react/renderer/components/rnsvg",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift index 6a48ac8..c68d3c5 100644 --- a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 4 +// rn-xtool-scaffold-revision: 5 // rn-xtool-swift-importer-paths: ["apple","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/patches.test.ts b/tests/patches.test.ts index 288dacf..9b3fa33 100644 --- a/tests/patches.test.ts +++ b/tests/patches.test.ts @@ -871,7 +871,7 @@ describe("patch-package failure detection", () => { describe("scaffold patches from another React Native version", () => { /** A persisted scaffold patch; `revision: null` is a hand-made patch without rn-xtool's marker. */ - const scaffoldPatch = (slot: string | null, revision: number | null = 4) => + const scaffoldPatch = (slot: string | null, revision: number | null = SCAFFOLD_REVISION) => [ "diff --git a/node_modules/lib/Package.swift b/node_modules/lib/Package.swift", "new file mode 100644", @@ -916,7 +916,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "@scope+lib+1.0.0.patch"), scaffoldPatch(null, 1)); // Revision 2 wrote no importer paths for a clang-only target. await writeFile(path.join(root, "patches", "react-native-screens+4.30.1.patch"), scaffoldPatch("0.87.1", 2)); - await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 4)); + await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 5)); // Both stale: the slot warning wins, one line per patch. await writeFile(path.join(root, "patches", "react-native-safe-area-context+5.6.0.patch"), scaffoldPatch("0.86.3", 1)); await installPkg(root, "react-native-screens"); @@ -924,15 +924,15 @@ describe("scaffold patches from another React Native version", () => { await installPkg(root, "react-native-svg"); await installPkg(root, "react-native-safe-area-context"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 4); delete it so rn-xtool " + + "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it so rn-xtool " + "regenerates it (also remove node_modules/@scope/lib and reinstall: that copy still has the old Package.swift)", "⚠ patches/react-native-safe-area-context+5.6.0.patch was scaffolded for React Native 0.86.3; delete it so rn-xtool " + "regenerates it for 0.87.1 (also remove node_modules/react-native-safe-area-context and reinstall: that copy still has " + "the old Package.swift)", - "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 4); delete it so " + + "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", - "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 4); delete it so " + + "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 5); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -945,7 +945,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.88.1", 3)); await installPkg(root, "react-native-svg"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 4); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 5); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -963,7 +963,7 @@ describe("scaffold patches from another React Native version", () => { expect(scaffoldPatchWarnings(root)).toEqual([ "⚠ patches/react-native-screens+4.30.0.patch was scaffolded for React Native 0.88.0; delete it so rn-xtool regenerates " + "it for 0.88.1 (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)", - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 4); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -1038,7 +1038,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("replaces an older node_modules copy of a current persisted patch (a teammate's pull)", async () => { const root = await project(); await installPkg(root, "react-native-screens", "4.30.0"); - const current = { "Package.swift": manifest(4, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; + const current = { "Package.swift": manifest(5, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; await put(root, "patches/react-native-screens+4.30.0.patch", newFilesPatch("react-native-screens", current)); // What the old patch left in node_modules: revision 1, slot 0.86.3, a stub the new scaffold no longer writes. await put(root, "node_modules/react-native-screens/Package.swift", manifest(1, "0.86.3")); @@ -1051,7 +1051,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(existsSync(path.join(root, "node_modules/react-native-screens/include/rnscreens/Gone.h"))).toBe(true); expect(lines).toEqual([ "ℹ node_modules/react-native-screens/Package.swift was scaffolded with revision 1 for React Native 0.86.3, " + - "older than patches/react-native-screens+4.30.0.patch (revision 4, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-screens+4.30.0.patch (revision 5, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); // Idempotent: the next build changes nothing. @@ -1067,7 +1067,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the const forwarder = "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the public headers of the pod AppAuth.\n" + "#import \n#import \n"; - const current = { "Package.swift": manifest(4, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; + const current = { "Package.swift": manifest(5, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; await put(root, "patches/react-native-app-auth+8.5.1.patch", newFilesPatch("react-native-app-auth", current)); await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(3, "0.87.1")); await put(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h", forwarder); @@ -1077,7 +1077,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h")).toBe(forwarder); expect(lines).toEqual([ "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded with revision 3 for React Native 0.87.1, " + - "older than patches/react-native-app-auth+8.5.1.patch (revision 4, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-app-auth+8.5.1.patch (revision 5, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); }, 30_000); @@ -1100,7 +1100,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the " line 3", "", ].join("\n"); - await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(4, "0.87.1") }) + fix); + await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(5, "0.87.1") }) + fix); await put(root, "node_modules/lib/Package.swift", manifest(1, "0.86.3")); await put(root, "node_modules/lib/ios/Foo.m", "line 1\nnew\nline 3\n"); for (const run of [1, 2]) { @@ -1109,7 +1109,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/lib/Package.swift"), `run ${run}`).toBe(manifest(1, "0.86.3")); expect(lines, `run ${run}`).toEqual([ "⚠ node_modules/lib/Package.swift was scaffolded with revision 1 for React Native 0.86.3, older than " + - "patches/lib+1.0.0.patch (revision 4, React Native 0.87.1), and that patch also changes the library's own " + + "patches/lib+1.0.0.patch (revision 5, React Native 0.87.1), and that patch also changes the library's own " + "files, so rn-xtool does not replace it: run rm -rf node_modules/lib && npm install, then build again", ]); } @@ -1118,14 +1118,14 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("treats the pre-rename marker in node_modules as an older revision", async () => { const root = await project(); await installPkg(root, "react-native-svg", "15.16.0"); - await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(4, "0.87.1") })); + await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(5, "0.87.1") })); await put(root, "node_modules/react-native-svg/Package.swift", manifest(1, "0.87.1", "expo-xtool-scaffold-revision")); const lines: string[] = []; await applyPatches(root, undefined, { ...noBundled, log: (l) => lines.push(l) }); - expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(4, "0.87.1")); + expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(5, "0.87.1")); expect(lines).toEqual([ "ℹ node_modules/react-native-svg/Package.swift was scaffolded with revision 1 for React Native 0.87.1, older than " + - "patches/react-native-svg+15.16.0.patch (revision 4, React Native 0.87.1): rn-xtool replaced it with the " + + "patches/react-native-svg+15.16.0.patch (revision 5, React Native 0.87.1): rn-xtool replaced it with the " + "persisted one", ]); }, 30_000); @@ -1133,28 +1133,32 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("removes a stale scaffold with no persisted patch, so the rn-spm step scaffolds it again", async () => { const root = await project(); await put(root, "node_modules/react-native-webview/Package.swift", manifest(2, "0.87.1")); - await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(4, "0.86.3")); + await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(5, "0.86.3")); await put(root, "node_modules/legacy-lib/Package.swift", manifest(1, null, "expo-xtool-scaffold-revision")); + // Revision 4 (0.1.0-alpha.6) wrote pod header forwarders with @import, which Objective-C++ cannot compile. + await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(4, "0.87.1")); const lines: string[] = []; await applyPatches(root, async () => ({ exitCode: 0 }), { ...noBundled, log: (l) => lines.push(l) }); - for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib"]) { + for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib", "react-native-app-auth"]) { expect(existsSync(path.join(root, "node_modules", pkg, "Package.swift")), pkg).toBe(false); } expect(lines).toEqual([ "ℹ node_modules/@react-native-community/datetimepicker/Package.swift was scaffolded for React Native 0.86.3, not " + "0.87.1: rn-xtool removed it so the rn-spm step scaffolds it again", - "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 4): " + + "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 5): " + "rn-xtool removed it so the rn-spm step scaffolds it again", + "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 4, now " + + "5): rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-webview/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 2, now " + - "4): rn-xtool removed it so the rn-spm step scaffolds it again", + "5): rn-xtool removed it so the rn-spm step scaffolds it again", ]); }); it("leaves current, foreign and stale-patch manifests alone", async () => { const root = await project(); const files: Record = { - // Current: revision 4 on the installed React Native. - "node_modules/current-lib/Package.swift": manifest(4, "0.87.1"), + // Current: revision 5 on the installed React Native. + "node_modules/current-lib/Package.swift": manifest(5, "0.87.1"), // Not rn-xtool's: the upstream scaffolder without rn-xtool's marker (a library may ship it), or hand-written. "node_modules/upstream-lib/Package.swift": manifest(0, null, null), "node_modules/own-lib/Package.swift": "// swift-tools-version: 6.0\nimport PackageDescription\n", @@ -1162,8 +1166,8 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the "node_modules/react-native-screens/Package.swift": manifest(1, "0.86.3"), "patches/react-native-screens+4.30.0.patch": newFilesPatch("react-native-screens", { "Package.swift": manifest(1, "0.86.3") }), // A current patch over a current copy. - "node_modules/react-native-svg/Package.swift": manifest(4, "0.87.1"), - "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(4, "0.87.1") }), + "node_modules/react-native-svg/Package.swift": manifest(5, "0.87.1"), + "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(5, "0.87.1") }), }; for (const [rel, text] of Object.entries(files)) await put(root, rel, text); for (const pkg of ["react-native-screens", "react-native-svg"]) await installPkg(root, pkg); diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 9631405..613149c 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -130,7 +130,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(src("read-podspec.js")).toContain("function rnPodEnvTernary"); expect(src("read-podspec.js")).toContain("env: {...process.env, ...RN_POD_ENV}"); const f = src("scaffold-package-swift.js"); - expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 4"); + expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 5"); expect(f).toContain("rn-xtool-swift-importer-paths"); expect(f).toContain("function importsOwnSwiftHeader"); expect(f).toContain("function clangModuleExcludes"); @@ -1076,7 +1076,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () it("emits the rn-xtool-scaffold-revision marker next to AUTO-SCAFFOLDED-VERSION", () => { const pkg = readFileSync(path.join(fresh(), "Package.swift"), "utf8"); - expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 4$/m); + expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 5$/m); }); it("keeps a scaffold that carries the current marker", () => { @@ -1089,14 +1089,14 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () writeFileSync(file, readFileSync(file, "utf8").replace(/^\/\/ rn-xtool-scaffold-revision: \d+\n/m, "").replace("exact:", "from:")); expect(scaffoldAgain(root)).toBe("written"); const pkg = readFileSync(file, "utf8"); - expect(pkg).toContain("rn-xtool-scaffold-revision: 4"); + expect(pkg).toContain("rn-xtool-scaffold-revision: 5"); expect(pkg).toContain('exact: "1.5.0"'); }); it("regenerates a scaffold whose marker is lower than the current revision", () => { const root = fresh(); const file = path.join(root, "Package.swift"); - writeFileSync(file, readFileSync(file, "utf8").replace("revision: 4", "revision: 3")); + writeFileSync(file, readFileSync(file, "utf8").replace("revision: 5", "revision: 4")); expect(scaffoldAgain(root)).toBe("written"); }); }); @@ -1181,7 +1181,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { // Mixed (pager-view) or clang-only, each of these targets searches beyond its public headers path, so each // manifest records its importer paths right after the revision line. for (const k of manifests) { - expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 4\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); + expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); } expect(now.files).toEqual(golden.files); }, @@ -1282,7 +1282,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { it("17: records the Swift importer paths", () => { for (const manifest of ["Package.swift", "Package@swift-6.5.swift"]) { const pkg = file(`react-native-screens/${manifest}`); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 4\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("."); expect(paths).toContain("ios/bridging"); @@ -1297,7 +1297,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { expect(pkg.split("\n")[0]).toBe("// swift-tools-version: 6.0"); expect(files["react-native-screens/Package@swift-6.5.swift"]).toBeUndefined(); expect(pkg).toContain('publicHeadersPath: "ios",'); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 4\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("ios/utils"); expect(paths).toEqual(searchPaths(pkg)); @@ -2104,7 +2104,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { const pkg = manifest(scaffold(`${APPAUTH_DEP}\n s.dependency "SwiftUIIntrospect", '~> 1.0'`, table)); // Clang-only, searching beyond its public headers: after the importer-paths line. expect(pkg).toMatch( - /^\/\/ rn-xtool-scaffold-revision: 4\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, + /^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, ); // Pure Swift (no importer-paths line): after the revision line. const swift = tempDir(); @@ -2116,7 +2116,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { `Pod::Spec.new do |s|\n s.name = "Foo"\n s.source_files = "ios/**/*.swift"\n${APPAUTH_DEP}\nend\n`, ); const swiftPkg = manifest(withTable(table, () => scaffoldLibraries(VENDORED_RN_SPM, { foo: swift }))); - expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 4\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); + expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); // No pinned pod, no line. expect(manifest(scaffold("", table))).not.toContain("rn-xtool-pods"); }); diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index ede4f34..b41cd3e 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -124,8 +124,10 @@ const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; // (CLANG_MODULE_MAP). Revision 4 (fixes 20–24): dependencies on packages that // are not linked for iOS left out, with the subspecs that declare them; the // Swift 5 language mode; the umbrella-directory shim; the codegen header's -// bare spelling; and Swift compilation conditions. -const RN_XTOOL_SCAFFOLD_REVISION = 4; +// bare spelling; and Swift compilation conditions. Revision 5: pod header +// forwarders that `#import` the pod's public headers instead of `@import`ing +// its modules, which stopped every Objective-C++ file that included them. +const RN_XTOOL_SCAFFOLD_REVISION = 5; const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; // An importer (Swift, or a Clang module) builds the target's module from its From 70a92a47524ab42de052c7b9d18ce3cbc4078142 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 20:10:39 -0600 Subject: [PATCH 07/16] docs: describe textual pod header forwarders --- CHANGELOG.md | 17 +++++++++ docs/bare-react-native.md | 9 ++--- docs/how-it-works.md | 10 +++--- docs/libraries.md | 2 +- docs/troubleshooting.md | 45 +++++++++++++++++++----- docs/upstream/react-native-scaffolder.md | 20 +++++++---- 6 files changed, 79 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33048c1..e04f728 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea ## [Unreleased] +### Upgrading from 0.1.0-alpha.6 +- The scaffolder is now revision 5, so every scaffold patch rn-xtool persisted in your `patches/` before this release + gets a warning at each `build`: "⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 5); + delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old + Package.swift)". Do what it says. A scaffolded library without a persisted patch is scaffolded again by itself. +- A `pods..forwardHeaders` entry in `rn-xtool.config.json` that lists modules is refused: list the pod's public + headers instead (see Changed). + +### Changed +- `pods..forwardHeaders` maps a forwarded header to the pod's public headers to include, as paths under the + public header directories of its SwiftPM targets (`["OIDAuthState.h", "iOS/OIDAuthState+IOS.h", …]`), instead of + module names; a module name is refused with a message saying to list the headers. rn-xtool's AppAuth entry lists + the headers of AppAuth-iOS 3.0.0's umbrella header. + ### Fixed - A bare app target with an Objective-C `main.m` (the React Native templates before 0.77) builds, instead of stopping in SwiftPM with "library product 'App' should not contain executable targets (it has 'App')": the file is compiled @@ -21,6 +35,9 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea - A bare app target's Objective-C++ and C++ files (an `AppDelegate.mm` importing ``) compile with the project's `CLANG_CXX_LANGUAGE_STANDARD` (C++20 when unset), instead of clang's default, which stopped on React Native's C++20 headers with "unknown type name 'Hashable'" in `react/utils/hash_combine.h`. +- An Objective-C++ file that imports a pod table forward (a bare app's `AppDelegate.mm` with + `#import `) compiles, instead of stopping with "use of '@import' when modules are disabled": the + scaffold's forwarder `#import`s the pod's public headers instead of `@import`ing its modules. ## [0.1.0-alpha.6] - 2026-11-05 diff --git a/docs/bare-react-native.md b/docs/bare-react-native.md index e7a0671..f23ead7 100644 --- a/docs/bare-react-native.md +++ b/docs/bare-react-native.md @@ -255,10 +255,11 @@ Swift Build names the generated Swift header `App-Swift.h` (the SwiftPM target i where `` is `PRODUCT_MODULE_NAME`, or `PRODUCT_NAME` with characters other than letters, digits and `_` turned into `_`. -React Native's public Objective-C headers are importable by their bare name (`#import `) as well as -by module (`#import `), as CocoaPods' per-pod header search paths allow, and so are the -`` spellings of the pod table's `forwardHeaders` (`#import `). The app's Objective-C -sources and its bridging header search the app's own headers and `HEADER_SEARCH_PATHS` first, then +React Native's public Objective-C headers are importable by their bare name (`#import `) as well as by +module (`#import `), as CocoaPods' per-pod header search paths allow, and so are the +`` spellings of the pod table's `forwardHeaders` (`#import `, in `.m` and `.mm` files +alike: the forwarder `#import`s the pod's public headers, since Objective-C++ compiles without modules). The app's +Objective-C sources and its bridging header search the app's own headers and `HEADER_SEARCH_PATHS` first, then `ios/build/xcframeworks/ReactHeadersTarget/include/React`, then each per-module directory of `ReactNativeHeaders.xcframework` that its module map names (`React_RCTAppDelegate`, `RCTImage`, `yoga`, …), then each autolinked library's `rn-spm-pod-headers`, so an app header with the same name wins. React Native's C++ headers keep diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 7d456f5..a6e4b4b 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -407,11 +407,13 @@ The scaffolder classifies each `s.dependency` on an unconditional line of a pods **The pod table** is merged per pod, field by field, in this order, the later winning: the scaffolder's own baseline (SwiftUIIntrospect), rn-xtool's `data/pods.json` (AppAuth, and the source pods ML Kit reaches), then the `pods` of `rn-xtool.config.json`. rn-xtool writes the merged table to `ios/build/rn-xtool-pods.json`, with the binary pods the -`pods` step resolved, and names it in `RN_SPM_POD_TABLE` for every React Native run of the `rn-spm` step; without it -the scaffolder falls back to its baseline. A mapped pod's `forwardHeaders` become -`rn-spm-pod-headers/` files in the library, each holding `@import ;` lines, on the library's +`pods` step resolved, and names it in `RN_SPM_POD_TABLE` for every React Native run of the `rn-spm` step; without it the +scaffolder falls back to its baseline. A mapped pod's `forwardHeaders` become `rn-spm-pod-headers/` files +in the library, each holding one `#import
` per public header the pod's umbrella includes, on the library's header search path: AppAuth's umbrella header is outside its SwiftPM targets, and react-native-app-auth imports it as -``. Each manifest records the pods it pins on a marker line, `// rn-xtool-pods: AppAuth=3.0.0`. +``. The forwarder is textual because Objective-C++ compiles without C++ modules +(`-fmodules -fno-cxx-modules`, Xcode's default), where `@import` is an error. Each manifest records the pods it pins +on a marker line, `// rn-xtool-pods: AppAuth=3.0.0`. **Before the build.** `doctor --project` and `build` run the same classifier, loaded from rn-xtool's vendored copy of the scaffolder, never the project's. They read podspecs as text, with no `pod ipc` and no network. The linked diff --git a/docs/libraries.md b/docs/libraries.md index e60af2a..26f48d4 100644 --- a/docs/libraries.md +++ b/docs/libraries.md @@ -66,7 +66,7 @@ Legend: ✅ works · ⚠️ works with caveats · ❌ fails · ⏳ not tested ye | react-native-video | 6.19.3 | CocoaPods-only, mixed Swift + ObjC++ → auto-scaffold as one mixed-language target | ⏳ | ⏳ | ⏳ | ✅ 2026-11-05 (React Native 0.88.1, on a device) | ⏳ | ⏳ | ⏳ | needed scaffolder fix 21 (Swift 5 language mode; in Swift 6 it failed with strict-concurrency errors). Google IMA ads and video caching, which the podspec adds only when the Podfile sets `$RNVideoUseGoogleIMA` or `$RNVideoUseVideoCaching`, are not wired: their three pods (GoogleAds-IMA-iOS-SDK, SPTPersistentCache, DVAssetLoaderDelegate) have no SwiftPM package, the scaffold prints one "is a CocoaPods pod with no known SwiftPM equivalent" warning for each, and the code behind them is not built. `RCTVideo` is in the binary. On a device a remote MP4 plays with the native controls | | react-native-device-info | 15.0.2 | CocoaPods-only, ObjC → auto-scaffold with the `include/RNDeviceInfo/` shim | build ✅ 2026-11-04 (expo 58.0.23, react-native 0.88.1; device ⏳) | ⏳ | ⏳ | ✅ 2026-11-05 (React Native 0.88.1, on a device) | ⏳ | ⏳ | ⏳ | needed scaffolder fix 22 (its `ios/RNDeviceInfo/RNDeviceInfo.h` umbrella directory sits next to `RNDeviceInfo.xcodeproj/`). Its privacy-manifest resource bundle is built and copied to the app as `RNDeviceInfoPrivacyInfo.bundle` (checked by building, 2026-11-05). On SDK 58 it scaffolds through rn-xtool's driver with Expo's autolinking command, and no other library is re-scaffolded. `RNDeviceInfo` is in the binary. On a device (bare) the model and the iOS version are shown. The real device name needs the restricted `com.apple.developer.device-information.user-assigned-device-name` entitlement, which a free team does not get: without it the name is the generic model name, and with the key in the app's entitlements `build` prints a `⚠` line for it | | @react-native-community/netinfo | 11.5.2 | CocoaPods-only, ObjC++ → auto-scaffold | ⏳ | ⏳ | ⏳ | ✅ 2026-11-05 (React Native 0.88.1, on a device) | ⏳ | ⏳ | ⏳ | needed scaffolder fix 23: `RNCNetInfo.mm` imports its codegen header as `"RNCNetInfoSpec.h"`, which resolves through a forwarder in the per-app header farm. `RNCNetInfo` is in the binary. On a device it reports the type `wifi` and connected `true`. The Wi-Fi network name (SSID) needs the `com.apple.developer.networking.wifi-info` entitlement, which a free team does not get: without it the SSID is empty, and with the key in the app's entitlements `build` prints a `⚠` line for it | -| react-native-app-auth | 8.5.1 | CocoaPods-only, ObjC → auto-scaffold; its pod `AppAuth` → AppAuth-iOS 3.0.0 through the pod table | build ✅ 2026-11-05 (expo 58.0.23, react-native 0.88.1, with the config plugin; device ⏳) | ⏳ | ⏳ | build ✅ 2026-11-05; linked on a device 2026-11-05 (React Native 0.88.1; login flow ⏳) | ⏳ | ⏳ | ⏳ | its podspec depends on `AppAuth >= 1.7.6`; rn-xtool's pod table maps it to `.package(url: "https://github.com/openid/AppAuth-iOS", exact: "3.0.0")` + `.product(name: "AppAuth", package: "appauth-ios")`, fetched by SwiftPM on the first clean build. AppAuth's umbrella header is outside its SwiftPM targets, so the scaffold adds the forwarder `rn-spm-pod-headers/AppAuth/AppAuth.h` (`@import AppAuthCore;`, `@import AppAuth;`) for `#import `. AppAuth's privacy bundles (`AppAuth_AppAuth.bundle`, `AppAuth_AppAuthCore.bundle`) reach `App.app`: they come from the SwiftPM package, not the scaffold. On Expo SDK 58 use 8.5.1: 9.0.0's config plugin stops `expo prebuild` there ([details](troubleshooting.md#libraries-that-depend-on-cocoapods-pods)); with 8.5.1 the plugin's bridging header import compiles. The login's redirect needs its URL scheme in Info.plist (`CFBundleURLTypes`; on Expo the plugin's `redirectUrls`). `RNAppAuth` and `OIDAuthState` are in the binary. On a device (bare) the module is linked (`authorize` is present); the login flow was not run | +| react-native-app-auth | 8.5.1 | CocoaPods-only, ObjC → auto-scaffold; its pod `AppAuth` → AppAuth-iOS 3.0.0 through the pod table | build ✅ 2026-11-05 (expo 58.0.23, react-native 0.88.1, with the config plugin; device ⏳) | ⏳ | ⏳ | build ✅ 2026-11-05; linked on a device 2026-11-05 (React Native 0.88.1; login flow ⏳) | ⏳ | ⏳ | ⏳ | its podspec depends on `AppAuth >= 1.7.6`; rn-xtool's pod table maps it to `.package(url: "https://github.com/openid/AppAuth-iOS", exact: "3.0.0")` + `.product(name: "AppAuth", package: "appauth-ios")`, fetched by SwiftPM on the first clean build. AppAuth's umbrella header is outside its SwiftPM targets, so the scaffold adds the forwarder `rn-spm-pod-headers/AppAuth/AppAuth.h` (one `#import` per header of AppAuth's umbrella, `#import ` to `#import `) for `#import `. AppAuth's privacy bundles (`AppAuth_AppAuth.bundle`, `AppAuth_AppAuthCore.bundle`) reach `App.app`: they come from the SwiftPM package, not the scaffold. On Expo SDK 58 use 8.5.1: 9.0.0's config plugin stops `expo prebuild` there ([details](troubleshooting.md#libraries-that-depend-on-cocoapods-pods)); with 8.5.1 the plugin's bridging header import compiles. The login's redirect needs its URL scheme in Info.plist (`CFBundleURLTypes`; on Expo the plugin's `redirectUrls`). `RNAppAuth` and `OIDAuthState` are in the binary. On a device (bare) the module is linked (`authorize` is present); the login flow was not run | | @react-native-ml-kit/text-recognition | 2.0.0 | CocoaPods-only → auto-scaffold; its pod `GoogleMLKit` → ten CocoaPods binary pods wrapped into `ios/build/pod-binaries`, and four source pods through the pod table | ⏳ | ⏳ | ⏳ | ✅ 2026-11-05 (React Native 0.88.1, on a device: recognized printed text from a photo) | ⏳ | ⏳ | ⏳ | the first build prints what it downloads (10 files, 40.3 MB from dl.google.com, Google's, with the ML Kit Terms URL), records their sha256 in `rn-xtool-pods.lock.json` (commit it) and keeps them in `~/.cache/rn-xtool/pods` ([details](troubleshooting.md#cocoapods-binaries)). Each ML Kit framework becomes a headers-only xcframework, and its thin arm64 archive is linked once with `-force_load` on the App target (nine archives; GoogleMLKit itself is headers only). The source pods are GTMSessionFetcher 3.5.0, GoogleUtilities 8.1.5, GoogleDataTransport 10.1.1 and GoogleToolboxForMac 6.0.1 (outside ML Kit's `< 5.0`: 4.x ships no `Package.swift`; one `ℹ` line says so). The five model bundles (`LatinOCRResources`, `ChineseOCRResources`, `DevanagariOCRResources`, `JapaneseOCRResources`, `KoreanOCRResources`) are at the root of `App.app`, and no ML Kit framework is embedded. `MLKTextRecognizer`, `MLKITx_SRLRegistry`, `TextRecognition` and `GTMLogger` are in the binary, and `App.app` grows by about 53 MB. On a device `TextRecognition.recognize()` returned the text of a photo of printed text; the Japanese, Chinese, Devanagari and Korean models were not tried | "Linkage seen" records how the library reached the SwiftPM graph: Expo source package, Expo diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4a3a688..456365f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -254,7 +254,8 @@ any build after `ios-xtool/.build` is deleted, needs the network for it; an offl SwiftPM's resolve error naming the URL. **Adding a pod.** When the pod has a SwiftPM package (a git repository with a `Package.swift`), add it under `pods` in -`rn-xtool.config.json`. rn-xtool's own AppAuth entry is the example to copy: +`rn-xtool.config.json`. rn-xtool's own AppAuth entry is the example to copy (its `forwardHeaders` list is shortened +here; the shipped one, in `data/pods.json`, has all 31 headers): ```json { @@ -263,7 +264,9 @@ SwiftPM's resolve error naming the URL. "url": "https://github.com/openid/AppAuth-iOS", "exact": "3.0.0", "products": ["AppAuth"], - "forwardHeaders": { "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] } + "forwardHeaders": { + "AppAuth/AppAuth.h": ["OIDAuthState.h", "OIDAuthorizationService.h", "iOS/OIDExternalUserAgentIOS.h"] + } } } } @@ -274,10 +277,19 @@ SwiftPM's resolve error naming the URL. - `products`: the package's products the library links (`"product": "AppAuth"` works for one). - `subspecs` (optional): `{ "": ["", …] }`, the products for a dependency on `/`; any other subspec gets `products`. -- `forwardHeaders` (optional): `{ "": ["", …] }`, for a pod whose umbrella header is not part - of its SwiftPM targets. The scaffolder writes `rn-spm-pod-headers/` into the library, holding one - `@import ;` per module, and adds `rn-spm-pod-headers` to the library's header search paths, so - `#import ` resolves as it does under CocoaPods. +- `forwardHeaders` (optional): `{ "": ["
", …] }`, for a pod whose umbrella header is not part of + its SwiftPM targets. List the headers the umbrella includes, as paths under the public header directories of the + package's targets, which every importer has on its include path: AppAuth-iOS 3.0.0's `Sources/AppAuth.h` gives + `OIDAuthState.h` and 25 more headers from `Sources/AppAuthCore`, then, from its iOS branch, the 5 headers of + `Sources/AppAuth/iOS`, as `iOS/OIDAuthState+IOS.h` and so on. The scaffolder writes + `rn-spm-pod-headers/` into the library, holding one `#import
` per entry, and adds + `rn-spm-pod-headers` to the library's header search paths, so `#import ` resolves as it does under + CocoaPods. The forwarder includes the headers textually because Objective-C++ (`.mm`) files compile without C++ + modules, as in Xcode, so an `@import` there is an error; in Objective-C (`.m`) the `#import` of a module's header + still imports the module. A module name in the list, the form of 0.1.0-alpha.6 (`["AppAuthCore", "AppAuth"]`), is + refused with `pods..forwardHeaders.
lists the module ; list the pod's public headers instead + (relative paths ending in .h), which the forwarder includes textually: Objective-C++ compiles without modules, so it + cannot @import`. - `outsideRequirement` (optional): a sentence saying why `exact` is outside a requirement on purpose, checked by you. The pin check then prints one `ℹ` line with it instead of the `⚠` (rn-xtool's GoogleToolboxForMac entry, [CocoaPods binaries](#warnings-and-information-lines)). It holds for the entry's own `url` and `exact`: a config @@ -295,8 +307,10 @@ be a version such as 3.0.0`, `pods..subspecs must be an object of subspec n `pods..subspecs. must be a list of product names`, `pods..outsideRequirement must be a sentence saying why the pin is outside the requirement`, `pods..emptyTargets must be a list of target names`, `pods..forwardHeaders must be an object of header paths` and `pods..forwardHeaders.
must be a list -of module names, under a relative path ending in .h`. A URL or product that is well formed but wrong is named by -SwiftPM at `xtool-build`, in its resolve error. +of the pod's public headers (relative paths ending in .h), under a relative path ending in .h`. A URL or product that +is well formed but wrong is named by SwiftPM at `xtool-build`, in its resolve error. A header that is well formed but +not in the package is named by clang, when a file that imports the forwarded header compiles: `'
' file not +found`. **Changing a shipped pod.** An entry for a pod rn-xtool's table maps overrides only the fields it names, and the others stay. It still needs `url`, `exact` and `products`. To pin AppAuth 2.1.0: @@ -309,7 +323,9 @@ others stay. It still needs `url`, `exact` and `products`. To pin AppAuth 2.1.0: } ``` -The shipped `forwardHeaders` stay; `"forwardHeaders": {}` removes them, and `"subspecs": {}` removes subspecs. +The shipped `forwardHeaders` stay; `"forwardHeaders": {}` removes them, and `"subspecs": {}` removes subspecs. They +list AppAuth-iOS 3.0.0's headers: if the version you pin moves or renames one, give your own `forwardHeaders` with +that version's umbrella header list. **A pin outside the podspec's requirement.** `doctor --project` (its `pods` line) and the start of `build` print, for example, `⚠ AppAuth 1.0.0 (rn-xtool.config.json) is outside react-native-app-auth's requirement ">= 1.7.6"` @@ -886,6 +902,17 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin releases also search each autolinked library's `rn-spm-pod-headers`, where the scaffold writes the pod table's `forwardHeaders`. See [Mixed Swift + Objective-C/C++ app target](bare-react-native.md#mixed-swift--objective-cc-app-target). +- **"use of '@import' when modules are disabled"** (in `rn-spm-pod-headers/AppAuth/AppAuth.h`, compiling an + Objective-C++ file that imports ``, such as a bare app's `AppDelegate.mm`): the scaffold of + rn-xtool 0.1.0-alpha.6 (scaffolder revision 4) wrote the pod table's `forwardHeaders` as `@import` lines. + Objective-C++ compiles with `-fmodules -fno-cxx-modules`, Xcode's default, so `@import` is an error there; + react-native-app-auth's own `RNAppAuth.m` is Objective-C and compiled. Later releases write the forwarder as one + `#import` per public header of the pod, which compiles in `.m` and `.mm` files alike, and their scaffolder revision 5 + replaces an older scaffold: a copy in `node_modules` without a persisted patch is scaffolded again by itself, and a + persisted patch gets the `⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 5)` line + above, whose steps regenerate it. A `forwardHeaders` entry of your config that still lists modules is refused with + `… lists the module ; list the pod's public headers instead`: list the headers, as in [Libraries that depend + on CocoaPods pods](#libraries-that-depend-on-cocoapods-pods). - **"react/utils/hash_combine.h: … unknown type name 'Hashable'"** (bare React Native, compiling the app's `AppDelegate.mm` or another Objective-C++ source of the app target, often with fold-expression errors from the same header): `#import ` pulls in React Native's C++20 headers, and the file compiles with clang's diff --git a/docs/upstream/react-native-scaffolder.md b/docs/upstream/react-native-scaffolder.md index 900d2ed..b3800eb 100644 --- a/docs/upstream/react-native-scaffolder.md +++ b/docs/upstream/react-native-scaffolder.md @@ -482,12 +482,20 @@ the pins, sorted by pod, on a line after the importer-paths line (or the revisio `// rn-xtool-pods: AppAuth=3.0.0, SwiftUIIntrospect=1.5.0`. A pod whose SwiftPM package leaves its umbrella header outside every target (AppAuth-iOS 3.0.0's `Sources/AppAuth.h`: `@import AppAuth;` works, `` and `"AppAuth.h"` do not, while CocoaPods copies the header into `Headers/Public/AppAuth/`) names the header in -`forwardHeaders` (`{ "AppAuth/AppAuth.h": ["AppAuthCore", "AppAuth"] }`). The scaffold then writes -`rn-spm-pod-headers/AppAuth/AppAuth.h` into the library, holding the banner and `@import AppAuthCore;` and -`@import AppAuth;`, and adds `.headerSearchPath("rn-spm-pod-headers")` to its C and C++ settings. A header key must -be a relative path ending in `.h` without `.` or `..` segments, and each module a module name; otherwise that library -gets the error `react-native spm scaffold: pods..forwardHeaders.
must be a list of module names, under a -relative path ending in .h`. A scaffold without forwarders removes a `rn-spm-pod-headers/` whose files all carry the +`forwardHeaders`, with the headers the umbrella includes, as paths under the public header directories of the +package's targets (`{ "AppAuth/AppAuth.h": ["OIDAuthState.h", …, "iOS/OIDAuthState+IOS.h", …] }`). The scaffold then +writes `rn-spm-pod-headers/AppAuth/AppAuth.h` into the library, holding the banner and one `#import
` per +entry, and adds `.headerSearchPath("rn-spm-pod-headers")` to its C and C++ settings. The forwarder is textual: +Objective-C++ compiles with `-fmodules -fno-cxx-modules`, as Xcode does by default, so an `@import` in it stopped +every `.mm` file that included it with `use of '@import' when modules are disabled`, while in Objective-C the +`#import` of a module's header still imports the module. A header key must be a relative path ending in `.h` without +`.` or `..` segments, and so must each listed header, in letters, digits and `_+.-`; otherwise that library gets the +error `react-native spm scaffold: pods..forwardHeaders.
must be a list of the pod's public headers +(relative paths ending in .h), under a relative path ending in .h`. A module name in the list (the format before the +forwarders were textual) gets `react-native spm scaffold: pods..forwardHeaders.
lists the module ; +list the pod's public headers instead (relative paths ending in .h), which the forwarder includes textually: +Objective-C++ compiles without modules, so it cannot @import`. The textual forwarder ships with +`RN_XTOOL_SCAFFOLD_REVISION` 5. A scaffold without forwarders removes a `rn-spm-pod-headers/` whose files all carry the banner. An unmapped pod gets one warning per pod (subspecs collapse to the root pod): `Dependency "" is a CocoaPods pod with no known SwiftPM equivalent; the scaffolded package may fail to build — add it under "pods" in rn-xtool.config.json: { "pods": { "": { "url": "", "exact": "", "products": [""] } } From ab4e0e6b36e22f8cfa5900615c1b382bb69ff76b Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 20:30:46 -0600 Subject: [PATCH 08/16] fix: persist only the scaffold's files --- patches/react-native+0.88.0.patch | 148 +++++++++++------ patches/react-native+0.88.1.patch | 148 +++++++++++------ scripts/rn-spm-generate.js | 4 +- src/pipeline/rnSpm.ts | 114 ++++++++++++- tests/rn-scaffolder.test.ts | 46 ++++++ tests/rn-spm-generate.test.ts | 4 +- tests/rnSpm.test.ts | 171 ++++++++++++++++++++ vendor/rn-spm/spm/scaffold-package-swift.js | 56 ++++--- vendor/rn-spm/spm/spm-types.js | 3 + 9 files changed, 560 insertions(+), 134 deletions(-) diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index 761d1d6..700e77b 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..b41cd3e 100644 +index cf7e587..a8076ae 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -2598,7 +2598,7 @@ index cf7e587..b41cd3e 100644 ) `; } -@@ -844,6 +2022,65 @@ function reportSwiftName( +@@ -844,6 +2022,61 @@ function reportSwiftName( } } @@ -2624,10 +2624,12 @@ index cf7e587..b41cd3e 100644 + * the Swift umbrella (unless the podspec brings its own bridging header) and + * the `-Swift.h` spellings CocoaPods sources use. The shims import the + * real header with angle brackets so the lookup skips their own directory. ++ * Each file goes through `write`, which records it. + */ +function writeMixedLanguageSupport( + depRoot /*: string */, + mixed /*: {swiftHeader: string, podModule: string, bridgingHeader: string, umbrellaHeaders: ?Array} */, ++ write /*: (file: string, text: string) => void */, +) /*: void */ { + const dir = path.join(depRoot, MIXED_SUPPORT_DIR); + fs.rmSync(dir, {recursive: true, force: true}); @@ -2635,7 +2637,7 @@ index cf7e587..b41cd3e 100644 + const banner = + '// AUTO-SCAFFOLDED by react-native spm scaffold (mixed Swift + Objective-C target).\n'; + if (mixed.umbrellaHeaders != null) { -+ fs.writeFileSync( ++ write( + path.join(dir, MIXED_UMBRELLA_HEADER), + banner + + '// Swift bridging header: what the CocoaPods umbrella gives Swift — Foundation,\n' + @@ -2643,28 +2645,22 @@ index cf7e587..b41cd3e 100644 + '#import \n' + + '#if __has_include()\n#import \n#endif\n' + + mixed.umbrellaHeaders.map(h => `#import "../${h}"\n`).join(''), -+ 'utf8', + ); + } + const forward = `#import <${mixed.swiftHeader}>\n`; -+ fs.writeFileSync( ++ write( + path.join(dir, mixed.podModule, `${mixed.podModule}-Swift.h`), + banner + forward, -+ 'utf8', + ); + if (`${mixed.podModule}-Swift.h` !== mixed.swiftHeader) { -+ fs.writeFileSync( -+ path.join(dir, `${mixed.podModule}-Swift.h`), -+ banner + forward, -+ 'utf8', -+ ); ++ write(path.join(dir, `${mixed.podModule}-Swift.h`), banner + forward); + } +} + // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2186,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2677,7 +2673,7 @@ index cf7e587..b41cd3e 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2207,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2686,7 +2682,7 @@ index cf7e587..b41cd3e 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2235,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2731,7 +2727,7 @@ index cf7e587..b41cd3e 100644 } catch (e) { return { depName, -@@ -1012,35 +2288,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2284,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2776,7 +2772,7 @@ index cf7e587..b41cd3e 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2330,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2326,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2784,16 +2780,28 @@ index cf7e587..b41cd3e 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2342,19 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2336,36 @@ function scaffoldPackageSwiftForDep( + // regens are silent because we're maintaining a file we already own. + const previouslyExisted = fs.existsSync(pkgSwiftPath); ++ // Every file this scaffold writes under the library, relative to its root ++ // (posix), for the result: a patch that persists the scaffold can then hold ++ // these files and no other. What it removes is its own earlier output, which ++ // a clean copy of the library does not hold. ++ const written /*: Set */ = new Set(); ++ const write = (file /*: string */, text /*: string */) => { ++ fs.writeFileSync(file, text, 'utf8'); ++ written.add(path.relative(dep.root, file).split(path.sep).join('/')); ++ }; ++ if (!ctx.dryRun) { - fs.writeFileSync(pkgSwiftPath, content, 'utf8'); +- fs.writeFileSync(pkgSwiftPath, content, 'utf8'); ++ write(pkgSwiftPath, content); + const manifest65Path = path.join(dep.root, MIXED_MANIFEST_6_5); + if (spec.mixedLanguage != null) { -+ fs.writeFileSync( ++ write( + manifest65Path, + content.replace(MIXED_TOOLS_VERSION_LINE, MIXED_TOOLS_VERSION_LINE_6_5), -+ 'utf8', + ); + } else if ( + fs.existsSync(manifest65Path) && @@ -2804,25 +2812,34 @@ index cf7e587..b41cd3e 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2371,99 @@ function scaffoldPackageSwiftForDep( +- fs.writeFileSync( ++ write( + path.join(dep.root, SCAFFOLD_PREFIX_HEADER), + SCAFFOLD_PREFIX_HEADER_CONTENTS, +- 'utf8', + ); + } + // Mirror root-level headers into the generated include// shim +@@ -1099,18 +2375,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { +- fs.writeFileSync( +- path.join(shimDir, header), + // Entries may be nested relative paths (e.g. apple/Handlers/X.h): the + // stub is named by basename and #imports the real header by path. + const name = path.posix.basename(header); - fs.writeFileSync( -- path.join(shimDir, header), ++ write( + path.join(shimDir, name), `// AUTO-SCAFFOLDED by react-native spm scaffold — the namespaced\n` + - `// spelling (<${spec.swiftName}/${header}>) of the package-root header,\n` + + `// spelling (<${spec.swiftName}/${name}>) of the header,\n` + `// matching how CocoaPods header maps expose it.\n` + `#import "../../${header}"\n`, - 'utf8', - ); - } - } +- 'utf8', ++ ); ++ } ++ } + // `header_dir` namespaces: one stub per header in include//. + for (const {dir, headers, names} of spec.headerDirShims) { + const nsDir = path.join(dep.root, 'include', dir); @@ -2830,19 +2847,18 @@ index cf7e587..b41cd3e 100644 + const name = names?.[i] ?? path.posix.basename(header); + const stub = path.join(nsDir, name); + fs.mkdirSync(path.dirname(stub), {recursive: true}); -+ fs.writeFileSync( ++ write( + stub, + `// AUTO-SCAFFOLDED by react-native spm scaffold — the <${dir}/${name}>\n` + + `// spelling CocoaPods' header_dir gives the header.\n` + + `#import "${'../'.repeat(dir.split('/').length + name.split('/').length)}${header}"\n`, -+ 'utf8', + ); + }); + } + } + + if (!ctx.dryRun && spec.mixedLanguage != null) { -+ writeMixedLanguageSupport(dep.root, spec.mixedLanguage); ++ writeMixedLanguageSupport(dep.root, spec.mixedLanguage, write); + } + if (!ctx.dryRun && spec.publicHeadersPath != null) { + const mapPath = path.join( @@ -2852,7 +2868,7 @@ index cf7e587..b41cd3e 100644 + ); + const map = spec.clangModuleMap; + if (map != null) { -+ fs.writeFileSync( ++ write( + mapPath, + `${SCAFFOLDER_MARKER}\n` + + '// The module SwiftPM would make of publicHeadersPath, minus the headers the podspec leaves\n' + @@ -2862,7 +2878,6 @@ index cf7e587..b41cd3e 100644 + map.excludes.map(h => ` exclude header "${h}"\n`).join('') + + ' export *\n' + + '}\n', -+ 'utf8', + ); + } else if ( + fs.existsSync(mapPath) && @@ -2877,17 +2892,16 @@ index cf7e587..b41cd3e 100644 + if (spec.reactBareHeaders.length > 0) { + fs.mkdirSync(bareDir, {recursive: true}); + for (const name of spec.reactBareHeaders) { -+ fs.writeFileSync( ++ write( + path.join(bareDir, name), + `// AUTO-SCAFFOLDED by react-native spm scaffold — the bare "${name}"\n` + + `// spelling CocoaPods' header map resolves to React's public header.\n` + + `#import \n`, -+ 'utf8', -+ ); -+ } -+ } -+ } -+ + ); + } + } + } + + if (!ctx.dryRun) { + const podHeadersDir = path.join(dep.root, POD_HEADERS_DIR); + if (fs.existsSync(podHeadersDir) && ownPodHeadersDir(podHeadersDir)) { @@ -2896,17 +2910,39 @@ index cf7e587..b41cd3e 100644 + for (const {pod, header, headers} of spec.podForwarders ?? []) { + const file = path.join(podHeadersDir, ...header.split('/')); + fs.mkdirSync(path.dirname(file), {recursive: true}); -+ fs.writeFileSync( ++ write( + file, + `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + + headers.map(h => `#import <${h}>\n`).join(''), -+ 'utf8', + ); + } - } - ++ } ++ reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2496,7 @@ function collectAutolinkedDeps( + + // Migration: record a name we derived from the podspec, so the library can +@@ -1120,6 +2474,12 @@ function scaffoldPackageSwiftForDep( + dep.swiftNameSource === 'podspec' + ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) + : undefined; ++ if ( ++ !ctx.dryRun && ++ (swiftpmName === 'created' || swiftpmName === 'inserted') ++ ) { ++ written.add('package.json'); ++ } + + return { + depName, +@@ -1128,6 +2488,7 @@ function scaffoldPackageSwiftForDep( + warnings: spec.warnings, + previouslyExisted, + swiftpmName, ++ files: [...written].sort(), + }; + } + +@@ -1141,7 +2502,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2915,7 +2951,7 @@ index cf7e587..b41cd3e 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2517,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2523,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2924,7 +2960,7 @@ index cf7e587..b41cd3e 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2649,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2655,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2936,7 +2972,7 @@ index cf7e587..b41cd3e 100644 }; */ -@@ -1323,6 +2683,17 @@ function scaffoldAll( +@@ -1323,6 +2689,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2954,7 +2990,7 @@ index cf7e587..b41cd3e 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2701,23 @@ function scaffoldAll( +@@ -1330,24 +2707,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2990,7 +3026,7 @@ index cf7e587..b41cd3e 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2756,9 @@ function scaffoldAll( +@@ -1386,6 +2762,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3000,7 +3036,7 @@ index cf7e587..b41cd3e 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2777,9 @@ function scaffoldAll( +@@ -1404,6 +2783,9 @@ function scaffoldAll( } module.exports = { @@ -3011,7 +3047,7 @@ index cf7e587..b41cd3e 100644 scaffoldAll, scaffoldPackageSwiftForDep, diff --git a/node_modules/react-native/scripts/spm/spm-types.js b/node_modules/react-native/scripts/spm/spm-types.js -index a89142f..51e146e 100644 +index a89142f..73dc6c8 100644 --- a/node_modules/react-native/scripts/spm/spm-types.js +++ b/node_modules/react-native/scripts/spm/spm-types.js @@ -502,6 +502,9 @@ export type SpmScaffoldSpec = { @@ -3024,6 +3060,16 @@ index a89142f..51e146e 100644 // Extra frameworks beyond the autolinker's default UIKit/Foundation/CoreGraphics // set. Merged with the defaults at emit time. extraFrameworks: Array, +@@ -539,6 +542,9 @@ export type ScaffoldResult = + // What became of `swiftpmConfig.name` in the library's package.json. + // Absent when the name was not podspec-derived, so nothing was attempted. + swiftpmName?: SwiftpmNameOutcome, ++ // Every file the scaffold wrote under the library, relative to its root ++ // (posix separators), sorted. ++ files: Array, + } + | { + depName: string, diff --git a/node_modules/react-native/scripts/spm/spm-utils.js b/node_modules/react-native/scripts/spm/spm-utils.js index fc53136..4ffc1e9 100644 --- a/node_modules/react-native/scripts/spm/spm-utils.js diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index 761d1d6..700e77b 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1175,7 +1175,7 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..b41cd3e 100644 +index cf7e587..a8076ae 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -54,6 +54,7 @@ const { @@ -2598,7 +2598,7 @@ index cf7e587..b41cd3e 100644 ) `; } -@@ -844,6 +2022,65 @@ function reportSwiftName( +@@ -844,6 +2022,61 @@ function reportSwiftName( } } @@ -2624,10 +2624,12 @@ index cf7e587..b41cd3e 100644 + * the Swift umbrella (unless the podspec brings its own bridging header) and + * the `-Swift.h` spellings CocoaPods sources use. The shims import the + * real header with angle brackets so the lookup skips their own directory. ++ * Each file goes through `write`, which records it. + */ +function writeMixedLanguageSupport( + depRoot /*: string */, + mixed /*: {swiftHeader: string, podModule: string, bridgingHeader: string, umbrellaHeaders: ?Array} */, ++ write /*: (file: string, text: string) => void */, +) /*: void */ { + const dir = path.join(depRoot, MIXED_SUPPORT_DIR); + fs.rmSync(dir, {recursive: true, force: true}); @@ -2635,7 +2637,7 @@ index cf7e587..b41cd3e 100644 + const banner = + '// AUTO-SCAFFOLDED by react-native spm scaffold (mixed Swift + Objective-C target).\n'; + if (mixed.umbrellaHeaders != null) { -+ fs.writeFileSync( ++ write( + path.join(dir, MIXED_UMBRELLA_HEADER), + banner + + '// Swift bridging header: what the CocoaPods umbrella gives Swift — Foundation,\n' + @@ -2643,28 +2645,22 @@ index cf7e587..b41cd3e 100644 + '#import \n' + + '#if __has_include()\n#import \n#endif\n' + + mixed.umbrellaHeaders.map(h => `#import "../${h}"\n`).join(''), -+ 'utf8', + ); + } + const forward = `#import <${mixed.swiftHeader}>\n`; -+ fs.writeFileSync( ++ write( + path.join(dir, mixed.podModule, `${mixed.podModule}-Swift.h`), + banner + forward, -+ 'utf8', + ); + if (`${mixed.podModule}-Swift.h` !== mixed.swiftHeader) { -+ fs.writeFileSync( -+ path.join(dir, `${mixed.podModule}-Swift.h`), -+ banner + forward, -+ 'utf8', -+ ); ++ write(path.join(dir, `${mixed.podModule}-Swift.h`), banner + forward); + } +} + // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2186,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2677,7 +2673,7 @@ index cf7e587..b41cd3e 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2207,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2686,7 +2682,7 @@ index cf7e587..b41cd3e 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2235,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2731,7 +2727,7 @@ index cf7e587..b41cd3e 100644 } catch (e) { return { depName, -@@ -1012,35 +2288,17 @@ function scaffoldPackageSwiftForDep( +@@ -1012,35 +2284,17 @@ function scaffoldPackageSwiftForDep( const spec = translatePodspecToSpmTarget( model, dep, @@ -2776,7 +2772,7 @@ index cf7e587..b41cd3e 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2330,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2326,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2784,16 +2780,28 @@ index cf7e587..b41cd3e 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1083,6 +2342,19 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2336,36 @@ function scaffoldPackageSwiftForDep( + // regens are silent because we're maintaining a file we already own. + const previouslyExisted = fs.existsSync(pkgSwiftPath); ++ // Every file this scaffold writes under the library, relative to its root ++ // (posix), for the result: a patch that persists the scaffold can then hold ++ // these files and no other. What it removes is its own earlier output, which ++ // a clean copy of the library does not hold. ++ const written /*: Set */ = new Set(); ++ const write = (file /*: string */, text /*: string */) => { ++ fs.writeFileSync(file, text, 'utf8'); ++ written.add(path.relative(dep.root, file).split(path.sep).join('/')); ++ }; ++ if (!ctx.dryRun) { - fs.writeFileSync(pkgSwiftPath, content, 'utf8'); +- fs.writeFileSync(pkgSwiftPath, content, 'utf8'); ++ write(pkgSwiftPath, content); + const manifest65Path = path.join(dep.root, MIXED_MANIFEST_6_5); + if (spec.mixedLanguage != null) { -+ fs.writeFileSync( ++ write( + manifest65Path, + content.replace(MIXED_TOOLS_VERSION_LINE, MIXED_TOOLS_VERSION_LINE_6_5), -+ 'utf8', + ); + } else if ( + fs.existsSync(manifest65Path) && @@ -2804,25 +2812,34 @@ index cf7e587..b41cd3e 100644 // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { -@@ -1099,16 +2371,99 @@ function scaffoldPackageSwiftForDep( +- fs.writeFileSync( ++ write( + path.join(dep.root, SCAFFOLD_PREFIX_HEADER), + SCAFFOLD_PREFIX_HEADER_CONTENTS, +- 'utf8', + ); + } + // Mirror root-level headers into the generated include// shim +@@ -1099,18 +2375,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { +- fs.writeFileSync( +- path.join(shimDir, header), + // Entries may be nested relative paths (e.g. apple/Handlers/X.h): the + // stub is named by basename and #imports the real header by path. + const name = path.posix.basename(header); - fs.writeFileSync( -- path.join(shimDir, header), ++ write( + path.join(shimDir, name), `// AUTO-SCAFFOLDED by react-native spm scaffold — the namespaced\n` + - `// spelling (<${spec.swiftName}/${header}>) of the package-root header,\n` + + `// spelling (<${spec.swiftName}/${name}>) of the header,\n` + `// matching how CocoaPods header maps expose it.\n` + `#import "../../${header}"\n`, - 'utf8', - ); - } - } +- 'utf8', ++ ); ++ } ++ } + // `header_dir` namespaces: one stub per header in include//. + for (const {dir, headers, names} of spec.headerDirShims) { + const nsDir = path.join(dep.root, 'include', dir); @@ -2830,19 +2847,18 @@ index cf7e587..b41cd3e 100644 + const name = names?.[i] ?? path.posix.basename(header); + const stub = path.join(nsDir, name); + fs.mkdirSync(path.dirname(stub), {recursive: true}); -+ fs.writeFileSync( ++ write( + stub, + `// AUTO-SCAFFOLDED by react-native spm scaffold — the <${dir}/${name}>\n` + + `// spelling CocoaPods' header_dir gives the header.\n` + + `#import "${'../'.repeat(dir.split('/').length + name.split('/').length)}${header}"\n`, -+ 'utf8', + ); + }); + } + } + + if (!ctx.dryRun && spec.mixedLanguage != null) { -+ writeMixedLanguageSupport(dep.root, spec.mixedLanguage); ++ writeMixedLanguageSupport(dep.root, spec.mixedLanguage, write); + } + if (!ctx.dryRun && spec.publicHeadersPath != null) { + const mapPath = path.join( @@ -2852,7 +2868,7 @@ index cf7e587..b41cd3e 100644 + ); + const map = spec.clangModuleMap; + if (map != null) { -+ fs.writeFileSync( ++ write( + mapPath, + `${SCAFFOLDER_MARKER}\n` + + '// The module SwiftPM would make of publicHeadersPath, minus the headers the podspec leaves\n' + @@ -2862,7 +2878,6 @@ index cf7e587..b41cd3e 100644 + map.excludes.map(h => ` exclude header "${h}"\n`).join('') + + ' export *\n' + + '}\n', -+ 'utf8', + ); + } else if ( + fs.existsSync(mapPath) && @@ -2877,17 +2892,16 @@ index cf7e587..b41cd3e 100644 + if (spec.reactBareHeaders.length > 0) { + fs.mkdirSync(bareDir, {recursive: true}); + for (const name of spec.reactBareHeaders) { -+ fs.writeFileSync( ++ write( + path.join(bareDir, name), + `// AUTO-SCAFFOLDED by react-native spm scaffold — the bare "${name}"\n` + + `// spelling CocoaPods' header map resolves to React's public header.\n` + + `#import \n`, -+ 'utf8', -+ ); -+ } -+ } -+ } -+ + ); + } + } + } + + if (!ctx.dryRun) { + const podHeadersDir = path.join(dep.root, POD_HEADERS_DIR); + if (fs.existsSync(podHeadersDir) && ownPodHeadersDir(podHeadersDir)) { @@ -2896,17 +2910,39 @@ index cf7e587..b41cd3e 100644 + for (const {pod, header, headers} of spec.podForwarders ?? []) { + const file = path.join(podHeadersDir, ...header.split('/')); + fs.mkdirSync(path.dirname(file), {recursive: true}); -+ fs.writeFileSync( ++ write( + file, + `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + + headers.map(h => `#import <${h}>\n`).join(''), -+ 'utf8', + ); + } - } - ++ } ++ reportSwiftName(dep, spec.swiftName, model); -@@ -1141,7 +2496,7 @@ function collectAutolinkedDeps( + + // Migration: record a name we derived from the podspec, so the library can +@@ -1120,6 +2474,12 @@ function scaffoldPackageSwiftForDep( + dep.swiftNameSource === 'podspec' + ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) + : undefined; ++ if ( ++ !ctx.dryRun && ++ (swiftpmName === 'created' || swiftpmName === 'inserted') ++ ) { ++ written.add('package.json'); ++ } + + return { + depName, +@@ -1128,6 +2488,7 @@ function scaffoldPackageSwiftForDep( + warnings: spec.warnings, + previouslyExisted, + swiftpmName, ++ files: [...written].sort(), + }; + } + +@@ -1141,7 +2502,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2915,7 +2951,7 @@ index cf7e587..b41cd3e 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2517,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2523,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2924,7 +2960,7 @@ index cf7e587..b41cd3e 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2649,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2655,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2936,7 +2972,7 @@ index cf7e587..b41cd3e 100644 }; */ -@@ -1323,6 +2683,17 @@ function scaffoldAll( +@@ -1323,6 +2689,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2954,7 +2990,7 @@ index cf7e587..b41cd3e 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2701,23 @@ function scaffoldAll( +@@ -1330,24 +2707,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -2990,7 +3026,7 @@ index cf7e587..b41cd3e 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2756,9 @@ function scaffoldAll( +@@ -1386,6 +2762,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3000,7 +3036,7 @@ index cf7e587..b41cd3e 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2777,9 @@ function scaffoldAll( +@@ -1404,6 +2783,9 @@ function scaffoldAll( } module.exports = { @@ -3011,7 +3047,7 @@ index cf7e587..b41cd3e 100644 scaffoldAll, scaffoldPackageSwiftForDep, diff --git a/node_modules/react-native/scripts/spm/spm-types.js b/node_modules/react-native/scripts/spm/spm-types.js -index a89142f..51e146e 100644 +index a89142f..73dc6c8 100644 --- a/node_modules/react-native/scripts/spm/spm-types.js +++ b/node_modules/react-native/scripts/spm/spm-types.js @@ -502,6 +502,9 @@ export type SpmScaffoldSpec = { @@ -3024,6 +3060,16 @@ index a89142f..51e146e 100644 // Extra frameworks beyond the autolinker's default UIKit/Foundation/CoreGraphics // set. Merged with the defaults at emit time. extraFrameworks: Array, +@@ -539,6 +542,9 @@ export type ScaffoldResult = + // What became of `swiftpmConfig.name` in the library's package.json. + // Absent when the name was not podspec-derived, so nothing was attempted. + swiftpmName?: SwiftpmNameOutcome, ++ // Every file the scaffold wrote under the library, relative to its root ++ // (posix separators), sorted. ++ files: Array, + } + | { + depName: string, diff --git a/node_modules/react-native/scripts/spm/spm-utils.js b/node_modules/react-native/scripts/spm/spm-utils.js index fc53136..4ffc1e9 100644 --- a/node_modules/react-native/scripts/spm/spm-utils.js diff --git a/scripts/rn-spm-generate.js b/scripts/rn-spm-generate.js index ef12fff..a8d7897 100644 --- a/scripts/rn-spm-generate.js +++ b/scripts/rn-spm-generate.js @@ -220,7 +220,8 @@ async function scaffold(rn, scaffoldAll, opts, resultsPath) { } } -// rn-xtool reads this to tell which named library failed, and why, before anything is persisted. +// rn-xtool reads this to tell which named library failed, and why, before anything is persisted, and +// which files each scaffold wrote, which is what it persists. function writeResults(file, results, autolinkingJsonPath) { let deps = {}; try { @@ -234,6 +235,7 @@ function writeResults(file, results, autolinkingJsonPath) { ...(r.reason != null ? {reason: r.reason} : {}), ...(r.warnings != null && r.warnings.length > 0 ? {warnings: r.warnings} : {}), ...(typeof root === 'string' ? {root} : {}), + ...(Array.isArray(r.files) ? {files: r.files} : {}), }; }); fs.mkdirSync(path.dirname(file), {recursive: true}); diff --git a/src/pipeline/rnSpm.ts b/src/pipeline/rnSpm.ts index fbeccd3..ea5fb7c 100644 --- a/src/pipeline/rnSpm.ts +++ b/src/pipeline/rnSpm.ts @@ -149,6 +149,8 @@ const SCAFFOLDER_BANNER = "AUTO-SCAFFOLDED by react-native spm scaffold"; export interface ScaffoldOutcome { scaffolded: string[]; failed: { name: string; reason: string; warnings: string[] }[]; + /** The files each scaffolded library's result lists as written (relative to the library); absent: no usable list. */ + files: Map; } interface ScaffoldResultEntry { @@ -157,6 +159,16 @@ interface ScaffoldResultEntry { reason?: unknown; warnings?: unknown; root?: unknown; + files?: unknown; +} + +/** A result's `files`, when it is a list of relative paths inside the library; undefined otherwise. */ +function writtenFiles(files: unknown): string[] | undefined { + if (!Array.isArray(files)) return undefined; + const ok = files.every( + (f): f is string => typeof f === "string" && f !== "" && !f.startsWith("/") && !f.split("/").includes(".."), + ); + return ok ? (files as string[]) : undefined; } /** @@ -175,7 +187,7 @@ export function scaffoldOutcome(paths: ProjectPaths, names: readonly string[]): } catch { return undefined; } - const outcome: ScaffoldOutcome = { scaffolded: [], failed: [] }; + const outcome: ScaffoldOutcome = { scaffolded: [], failed: [], files: new Map() }; for (const name of names) { const entry = entries.find((e) => e.depName === name); const root = typeof entry?.root === "string" ? entry.root : path.join(paths.root, "node_modules", name); @@ -187,6 +199,8 @@ export function scaffoldOutcome(paths: ProjectPaths, names: readonly string[]): } if (entry?.status !== "error" && manifest.includes(SCAFFOLDER_BANNER)) { outcome.scaffolded.push(name); + const files = writtenFiles(entry?.files); + if (files !== undefined) outcome.files.set(name, files); continue; } const reason = @@ -295,13 +309,102 @@ export function parseMissingPackageSwift(output: string): string[] { * `swiftpmConfig.name` falls back to the podspec name, so the scaffolded manifest does not need it. */ export const PERSIST_EXCLUDE = "(^|/)\\.build/|^package\\.json$"; -export function persistScaffoldArgv(name: string): [string, string[]] { +/** `include`: patch-package's `--include`, the paths the patch may hold (persistInclude); absent: the whole package. */ +export function persistScaffoldArgv(name: string, include?: string): [string, string[]] { return [ process.execPath, - [patchPackageScript(), name, "--patch-dir", "patches", "--exclude", PERSIST_EXCLUDE], + [ + patchPackageScript(), + name, + "--patch-dir", + "patches", + "--exclude", + PERSIST_EXCLUDE, + ...(include !== undefined ? ["--include", include] : []), + ], ]; } +/** Directories the scaffolder writes and removes as a whole: past PERSIST_PATHS_MAX paths, one entry each. */ +const SCAFFOLDER_DIRS = ["rn-spm-pod-headers/", "rn-spm-react-headers/", "rn-spm-swift/"]; +const PERSIST_PATHS_MAX = 200; +/** Under Linux's 128 KiB limit on one argument; a longer `--include` would not spawn. */ +const PERSIST_INCLUDE_MAX = 100_000; + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** + * patch-package's `--include` for a scaffold: each path the scaffold wrote and each path the library's existing patch + * holds (a hand fix in it stays), relative to the library, anchored and escaped, in that order, once each. Past + * PERSIST_PATHS_MAX paths, those under a directory the scaffolder owns whole become that directory's prefix, so the + * argument stays short whatever the number of forwarders. Build outputs under the library (Gradle's `android/build`) + * match none of them. + */ +export function persistInclude(written: readonly string[], existing: readonly string[]): string { + const paths = [...new Set([...written, ...existing])]; + const collapse = paths.length > PERSIST_PATHS_MAX; + const entries = paths.map((p) => { + const dir = collapse ? SCAFFOLDER_DIRS.find((d) => p.startsWith(d)) : undefined; + return dir !== undefined ? `^${escapeRegExp(dir)}` : `^${escapeRegExp(p)}$`; + }); + return [...new Set(entries)].join("|"); +} + +/** + * The files `name`'s patch (patch-package's format, `diff --git a/node_modules// b/…`) touches, relative + * to the library, both sides of a rename included. Undefined when it has no such header, or a header it cannot read + * (a quoted path, a path outside the library). + */ +export function patchedPaths(text: string, name: string): string[] | undefined { + const headers = text.split("\n").filter((l) => l.startsWith("diff --git ")); + if (headers.length === 0) return undefined; + const prefix = `node_modules/${name}/`; + const paths: string[] = []; + for (const header of headers) { + const rest = header.slice("diff --git ".length); + if (!rest.startsWith(`a/${prefix}`)) return undefined; + // `a/

b/`: paths may hold spaces, so take the split whose sides are equal, else the only one. + const splits = [...rest.matchAll(/ b\//g)].map((m) => [rest.slice(2, m.index), rest.slice(m.index + 3)] as const); + const split = splits.find(([a, b]) => a === b) ?? (splits.length === 1 ? splits[0] : undefined); + if (split === undefined || !split.every((p) => p.startsWith(prefix) && p.length > prefix.length)) return undefined; + for (const p of split) { + const rel = p.slice(prefix.length); + if (!paths.includes(rel)) paths.push(rel); + } + } + return paths; +} + +/** + * What a persisted scaffold holds: `--include` for the scaffold's files and those of the library's patches in `patches` + * (`before`), or, when either list is missing, undefined with the `ℹ` line saying why (patch-package then diffs the + * whole package). + */ +function persistScope(name: string, files: string[] | undefined, before: Map): { include?: string; note?: string } { + const whole = "so its patch holds every file that differs from a clean copy"; + if (files === undefined) { + return { note: `ℹ The scaffold did not list the files it wrote in ${name}: persisting its whole package, ${whole}` }; + } + const existing: string[] = []; + const prefix = `${name.replace("/", "+")}+`; + for (const [file, bytes] of before) { + // `+….patch`; not a nested package's `+++.patch`. + if (!/^\d/.test(file.slice(prefix.length))) continue; + const paths = patchedPaths(bytes.toString("utf8"), name); + if (paths === undefined) { + return { note: `ℹ Could not tell which files patches/${file} changes: persisting ${name}'s whole package, ${whole}` }; + } + existing.push(...paths); + } + const include = persistInclude(files, existing); + if (include.length > PERSIST_INCLUDE_MAX) { + return { note: `ℹ ${name}'s scaffold wrote too many files to list for patch-package: persisting its whole package, ${whole}` }; + } + return { include }; +} + /** patch-package prints `✔ Created file patches/.patch`; prefer that over guessing the name. */ function createdPatchFile(output: string): string | undefined { return CREATED_RE.exec(output)?.[1]; @@ -438,9 +541,12 @@ export async function runRnSpm( // Only what was scaffolded is persisted; a failed library stops the build before React Native runs again. for (const name of outcome?.scaffolded ?? names) { - const [cmd, args] = persistScaffoldArgv(name); // The library's patch as it was: put back when the new one would carry a binary file. const before = libraryPatches(paths.root, name); + // The scaffold's files and the existing patch's, never the rest of the package (build outputs). + const scope = persistScope(name, outcome?.files.get(name), before); + if (scope.note !== undefined) log(scope.note); + const [cmd, args] = persistScaffoldArgv(name, scope.include); let failure: string | undefined; let persisted = ""; try { diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 613149c..c20d7a4 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -43,6 +43,23 @@ type Dep = { name: string; root: string; swiftName: string; platforms: object }; type ReadPodspec = { readPodspecCached(file: string): Model }; type Scaffold = { translatePodspecToSpmTarget(model: Model, dep: Dep): Spec }; +/** + * For each written library of a {@link scaffoldLibraries} run: the files its result lists, and the files the run created + * or changed in it, both relative to the library and sorted. + */ +function listedAndChanged(run: ReturnType): { lib: string; listed: string[]; changed: string[] }[] { + return run.results + .filter((r) => r.status === "written") + .map((r) => ({ + lib: r.depName, + listed: [...((r as { files?: unknown }).files as string[] | undefined ?? [])].sort(), + changed: Object.keys(run.files) + .filter((k) => k.startsWith(`${r.depName}/`)) + .map((k) => k.slice(r.depName.length + 1)) + .sort(), + })); +} + const tmp: string[] = []; function tempDir(): string { const d = mkdtempSync(path.join(tmpdir(), "xtool-rnspm-")); @@ -79,6 +96,14 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () return file; } + it("each written result lists the files its scaffold wrote", () => { + const run = scaffoldLibraries(SPM, { "react-native-screens": path.join(PODSPEC_FIXTURES, "RNScreens-4.30.1") }); + const listed = listedAndChanged(run); + expect(listed).toHaveLength(1); + expect(listed[0]!.listed).toContain("Package.swift"); + expect(listed[0]!.listed).toEqual(listed[0]!.changed); + }); + describe("the patched RN files carry the patch", () => { // Guards against testing an unpatched RN: each hunk must be present in what the tests load. const src = (f: string) => readFileSync(path.join(SPM, f), "utf8"); @@ -1516,6 +1541,16 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { expect(readdirSync(real).sort()).toEqual(before); }); + it("each written result lists the files its scaffold wrote, relative to the library", () => { + const listed = listedAndChanged(run()); + expect(listed.map((l) => l.lib).sort()).toEqual(Object.keys(run().roots).sort()); + for (const l of listed) expect(l.listed, l.lib).toEqual(l.changed); + // The mixed target's support files and the include stubs are among them. + const all = listed.flatMap((l) => l.listed.map((f) => `${l.lib}/${f}`)); + expect(all).toContain("react-native-screens/rn-spm-swift/umbrella.h"); + expect(all.some((f) => f.includes("/include/"))).toBe(true); + }); + it("gesture-handler 2.32.0 scaffolds", () => { expect(run().statuses["react-native-gesture-handler"]).toBe("written"); expect(run().results.filter((r) => r.status === "error")).toEqual([]); @@ -2171,6 +2206,17 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { expect(Object.keys(run.files).filter((k) => k.includes("rn-spm-pod-headers"))).toEqual(["foo/rn-spm-pod-headers/AppAuth/AppAuth.h"]); }); + it("13: the result lists the forwarder with the other files the scaffold wrote", () => { + const run = scaffold(APPAUTH_DEP, forwarding(FORWARD)); + const [foo] = listedAndChanged(run); + expect(foo!.listed).toEqual(foo!.changed); + expect(foo!.listed).toContain("rn-spm-pod-headers/AppAuth/AppAuth.h"); + expect(foo!.listed).toContain("Package.swift"); + // A scaffold again lists what it writes again, unchanged files included; package.json already has the name. + const again = withTable(forwarding(FORWARD), () => run.rerun({})); + expect((again[0] as { files?: string[] }).files).toEqual(foo!.listed.filter((f) => f !== "package.json")); + }); + it("13: the forwarder includes the pod's headers textually, without @import (Objective-C++ compiles without modules)", () => { const run = scaffold(APPAUTH_DEP, forwarding(FORWARD)); const text = run.files["foo/rn-spm-pod-headers/AppAuth/AppAuth.h"]!; diff --git a/tests/rn-spm-generate.test.ts b/tests/rn-spm-generate.test.ts index 8c5b49e..3c597b1 100644 --- a/tests/rn-spm-generate.test.ts +++ b/tests/rn-spm-generate.test.ts @@ -75,7 +75,7 @@ module.exports = { scaffoldAll(opts) { record('scaffoldAll', opts); return [ - {depName: 'lib-a', status: 'written', warnings: ['check the header paths']}, + {depName: 'lib-a', status: 'written', warnings: ['check the header paths'], files: ['Package.swift', 'include/Foo/Foo.h']}, {depName: 'lib-b', status: 'error', reason: 'no podspec readable'}, {depName: 'lib-c', status: 'already-set'}, ]; @@ -364,7 +364,7 @@ describe("rn-spm-generate.js", () => { expect(r.exitCode, r.all).toBe(0); expect(JSON.parse(readFileSync(results, "utf8"))).toEqual({ results: [ - { depName: "lib-a", status: "written", warnings: ["check the header paths"], root: "/nm/lib-a" }, + { depName: "lib-a", status: "written", warnings: ["check the header paths"], root: "/nm/lib-a", files: ["Package.swift", "include/Foo/Foo.h"] }, { depName: "lib-b", status: "error", reason: "no podspec readable", root: "/nm/lib-b" }, { depName: "lib-c", status: "already-set" }, ], diff --git a/tests/rnSpm.test.ts b/tests/rnSpm.test.ts index 0f41080..2924f67 100644 --- a/tests/rnSpm.test.ts +++ b/tests/rnSpm.test.ts @@ -7,6 +7,8 @@ import { binaryInPatch, configCommandFor, parseMissingPackageSwift, + patchedPaths, + persistInclude, persistScaffoldArgv, rnSpmArgs, rnSpmEnv, @@ -940,3 +942,172 @@ describe("the persist guard", () => { expect(r.logs.some((l) => l.includes("Did not persist"))).toBe(false); }); }); + +describe("persistInclude", () => { + it("anchors and escapes each path, the existing patch's included", () => { + const include = persistInclude(["Package.swift", "include/Foo+Bar/Foo+Bar.h"], ["ios/Foo.m"]); + expect(include).toBe("^Package\\.swift$|^include/Foo\\+Bar/Foo\\+Bar\\.h$|^ios/Foo\\.m$"); + const re = new RegExp(include, "i"); + for (const f of ["Package.swift", "include/Foo+Bar/Foo+Bar.h", "ios/Foo.m"]) expect(re.test(f), f).toBe(true); + for (const f of ["android/build/x.dex", "Package.swift.orig", "ios/Package.swift", "include/FooBar/Foo+Bar.h", "ios/FooXm"]) { + expect(re.test(f), f).toBe(false); + } + }); + + it("lists a path once, in order", () => { + expect(persistInclude(["Package.swift", "a.h"], ["a.h", "Package.swift", "b.m"])).toBe("^Package\\.swift$|^a\\.h$|^b\\.m$"); + }); + + it("collapses the directories the scaffolder owns past 200 paths", () => { + const forwarders = Array.from({ length: 250 }, (_, i) => `rn-spm-pod-headers/Pod/H${i}.h`); + const bare = Array.from({ length: 10 }, (_, i) => `rn-spm-react-headers/R${i}.h`); + const include = persistInclude(["Package.swift", ...forwarders, ...bare, "include/Foo/Foo.h"], ["ios/Foo.m"]); + expect(include).toBe("^Package\\.swift$|^rn-spm-pod-headers/|^rn-spm-react-headers/|^include/Foo/Foo\\.h$|^ios/Foo\\.m$"); + const re = new RegExp(include, "i"); + expect(re.test("rn-spm-pod-headers/Pod/H7.h")).toBe(true); + expect(re.test("android/build/rn-spm-pod-headers/x")).toBe(false); + }); +}); + +describe("patchedPaths", () => { + const header = (p: string, q = p) => `diff --git a/${p} b/${q}\nindex 1..2 100644\n--- a/${p}\n+++ b/${q}\n@@ -1 +1 @@\n-a\n+b\n`; + + it("lists the files a library's patch touches, relative to the library", () => { + const text = header("node_modules/lib-a/Package.swift") + header("node_modules/lib-a/ios/Foo.m"); + expect(patchedPaths(text, "lib-a")).toEqual(["Package.swift", "ios/Foo.m"]); + }); + + it("reads a scoped library, a path with spaces and both sides of a rename", () => { + const text = + header("node_modules/@scope/lib/ios/My File.m") + header("node_modules/@scope/lib/ios/Old.m", "node_modules/@scope/lib/ios/New.m"); + expect(patchedPaths(text, "@scope/lib")).toEqual(["ios/My File.m", "ios/Old.m", "ios/New.m"]); + }); + + it("cannot read a patch without diff headers, or with a path outside the library", () => { + expect(patchedPaths("the previous patch\n", "lib-a")).toBeUndefined(); + expect(patchedPaths("", "lib-a")).toBeUndefined(); + expect(patchedPaths(header("node_modules/lib-b/x.m"), "lib-a")).toBeUndefined(); + expect(patchedPaths('diff --git "a/node_modules/lib-a/\\303\\251.m" "b/node_modules/lib-a/\\303\\251.m"\n', "lib-a")).toBeUndefined(); + }); +}); + +describe("what a persisted patch holds", () => { + const tmp: string[] = []; + afterAll(() => { + for (const d of tmp) rmSync(d, { recursive: true, force: true }); + }); + const PATCH = "patches/lib-a+1.0.0.patch"; + const BANNER = "// AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit.\n"; + const section = (file: string, binary = false) => + binary + ? `diff --git a/node_modules/lib-a/${file} b/node_modules/lib-a/${file}\nnew file mode 100644\nGIT binary patch\nliteral 8\nPcmc~u&B@6x$;e;;0\n` + : `diff --git a/node_modules/lib-a/${file} b/node_modules/lib-a/${file}\nnew file mode 100644\n--- /dev/null\n+++ b/node_modules/lib-a/${file}\n@@ -0,0 +1 @@\n+// ${file}\n`; + + /** + * A project where lib-a differs from its clean copy in `changed` (a `.dex` as a binary file), the scaffold result lists + * `files` (absent: no list), and `previous` is lib-a's patch before. The fake patch-package keeps the paths its + * `--include` and `--exclude` select, as patch-package does (case-insensitive), and writes them as the patch. + */ + async function persisting(changed: string[], files: string[] | undefined, previous?: string) { + const root = mkdtempSync(path.join(tmpdir(), "rn-spm-include-")); + tmp.push(root); + const full = projectPaths(root); + if (previous !== undefined) { + mkdirSync(path.join(root, "patches"), { recursive: true }); + writeFileSync(path.join(root, PATCH), previous); + } + const logs: string[] = []; + const persists: string[][] = []; + let n = 0; + const runner: RnRunner = async (cmd, args) => { + n++; + if (n === 1) return { exitCode: 1, output: missing("lib-a") }; + if (args.includes("--scaffold")) { + const lib = path.join(root, "node_modules", "lib-a"); + mkdirSync(lib, { recursive: true }); + writeFileSync(path.join(lib, "Package.swift"), BANNER); + const result = { depName: "lib-a", status: "written", root: lib, ...(files !== undefined ? { files } : {}) }; + mkdirSync(path.dirname(full.scaffoldResults), { recursive: true }); + writeFileSync(full.scaffoldResults, JSON.stringify({ results: [result] })); + return { exitCode: 0, output: "" }; + } + if (cmd === process.execPath && args.includes("--patch-dir")) { + persists.push(args); + const flag = (f: string) => (args.includes(f) ? new RegExp(args[args.indexOf(f) + 1]!, "i") : undefined); + const include = flag("--include") ?? /.*/; + const exclude = flag("--exclude") ?? /^package\.json$/; + const kept = changed.filter((f) => include.test(f) && !exclude.test(f)); + mkdirSync(path.join(root, "patches"), { recursive: true }); + writeFileSync(path.join(root, PATCH), kept.map((f) => section(f, f.endsWith(".dex"))).join(""), "latin1"); + return { exitCode: 0, output: `✔ Created file ${PATCH}\n` }; + } + return { exitCode: 0, output: "" }; + }; + await runRnSpm(full, { kind: "bare", rnScripts: "vendored", expoPlugin: "installed" }, { + runner, + log: (l) => logs.push(l), + rnDir, + writePodTable: () => POD_TABLE, + }); + const file = path.join(root, PATCH); + return { logs, persists, patch: existsSync(file) ? readFileSync(file, "utf8") : undefined }; + } + const DEX = "android/build/.transforms/0a1b/transformed/bundleLibRuntimeToDirDebug/bundleLibRuntimeToDirDebug_dex/com/BV/LinearGradient/BuildConfig.dex"; + const GRADLE = ["android/.cxx/Debug/x/build.ninja", DEX]; + + it("persists a library Gradle built in place: the patch holds the scaffold's files, no build output", async () => { + const r = await persisting(["Package.swift", "rn-spm-pod-headers/A/A.h", ...GRADLE], ["Package.swift", "rn-spm-pod-headers/A/A.h"]); + expect(r.logs).toContain(`✔ scaffold — persisted ${PATCH}`); + expect(r.logs.some((l) => l.includes("Did not persist"))).toBe(false); + expect(r.patch).toContain("node_modules/lib-a/Package.swift"); + expect(r.patch).toContain("node_modules/lib-a/rn-spm-pod-headers/A/A.h"); + expect(r.patch).not.toContain("android"); + const args = r.persists[0]!; + expect(args[args.indexOf("--include") + 1]).toBe("^Package\\.swift$|^rn-spm-pod-headers/A/A\\.h$"); + expect(args[args.indexOf("--exclude") + 1]).toBe("(^|/)\\.build/|^package\\.json$"); + expect(r.logs.some((l) => l.startsWith("ℹ"))).toBe(false); + }); + + it("keeps the files the library's existing patch holds, a hand fix included", async () => { + const previous = section("Package.swift") + section("ios/Foo.m"); + const r = await persisting(["Package.swift", "ios/Foo.m", "ios/Bar.m", ...GRADLE], ["Package.swift"], previous); + expect(r.logs).toContain(`✔ scaffold — persisted ${PATCH}`); + expect(r.patch).toContain("node_modules/lib-a/ios/Foo.m"); + expect(r.patch).not.toContain("ios/Bar.m"); + expect(r.patch).not.toContain("android"); + const args = r.persists[0]!; + expect(args[args.indexOf("--include") + 1]).toBe("^Package\\.swift$|^ios/Foo\\.m$"); + }); + + it("diffs the whole package when it cannot read the existing patch, and says so", async () => { + const r = await persisting(["Package.swift", "ios/Foo.m"], ["Package.swift"], "the previous patch\n"); + expect(r.persists[0]).not.toContain("--include"); + expect(r.patch).toContain("node_modules/lib-a/ios/Foo.m"); + expect(r.logs).toContain( + `ℹ Could not tell which files ${PATCH} changes: persisting lib-a's whole package, so its patch holds every file that differs from a clean copy`, + ); + expect(r.logs.filter((l) => l.startsWith("ℹ"))).toHaveLength(1); + }); + + it("diffs the whole package when the scaffold result lists no files, and says so", async () => { + const r = await persisting(["Package.swift"], undefined); + expect(r.persists[0]).not.toContain("--include"); + expect(r.logs).toContain( + "ℹ The scaffold did not list the files it wrote in lib-a: persisting its whole package, so its patch holds every file that differs from a clean copy", + ); + }); + + it("diffs the whole package when the list would not fit in one argument, and says so", async () => { + const files = Array.from({ length: 2000 }, (_, i) => `include/Foo/Header${i}WithALongEnoughNameToFillTheArgument.h`); + const r = await persisting(["Package.swift"], ["Package.swift", ...files]); + expect(r.persists[0]).not.toContain("--include"); + expect(r.logs).toContain( + "ℹ lib-a's scaffold wrote too many files to list for patch-package: persisting its whole package, so its patch holds every file that differs from a clean copy", + ); + }); + + it("still refuses a binary file the existing patch's paths bring in", async () => { + const r = await persisting(["Package.swift", "ios/libX.dex"], ["Package.swift"], section("ios/libX.dex")); + expect(r.logs).toContain("⚠ Did not persist lib-a's scaffold: the patch would contain a binary file (node_modules/lib-a/ios/libX.dex)"); + }); +}); diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index b41cd3e..a8076ae 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -2044,10 +2044,12 @@ function reactIncludeRoots(appRoot /*: string */) /*: Array */ { * the Swift umbrella (unless the podspec brings its own bridging header) and * the `-Swift.h` spellings CocoaPods sources use. The shims import the * real header with angle brackets so the lookup skips their own directory. + * Each file goes through `write`, which records it. */ function writeMixedLanguageSupport( depRoot /*: string */, mixed /*: {swiftHeader: string, podModule: string, bridgingHeader: string, umbrellaHeaders: ?Array} */, + write /*: (file: string, text: string) => void */, ) /*: void */ { const dir = path.join(depRoot, MIXED_SUPPORT_DIR); fs.rmSync(dir, {recursive: true, force: true}); @@ -2055,7 +2057,7 @@ function writeMixedLanguageSupport( const banner = '// AUTO-SCAFFOLDED by react-native spm scaffold (mixed Swift + Objective-C target).\n'; if (mixed.umbrellaHeaders != null) { - fs.writeFileSync( + write( path.join(dir, MIXED_UMBRELLA_HEADER), banner + '// Swift bridging header: what the CocoaPods umbrella gives Swift — Foundation,\n' + @@ -2063,21 +2065,15 @@ function writeMixedLanguageSupport( '#import \n' + '#if __has_include()\n#import \n#endif\n' + mixed.umbrellaHeaders.map(h => `#import "../${h}"\n`).join(''), - 'utf8', ); } const forward = `#import <${mixed.swiftHeader}>\n`; - fs.writeFileSync( + write( path.join(dir, mixed.podModule, `${mixed.podModule}-Swift.h`), banner + forward, - 'utf8', ); if (`${mixed.podModule}-Swift.h` !== mixed.swiftHeader) { - fs.writeFileSync( - path.join(dir, `${mixed.podModule}-Swift.h`), - banner + forward, - 'utf8', - ); + write(path.join(dir, `${mixed.podModule}-Swift.h`), banner + forward); } } @@ -2340,14 +2336,23 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); + // Every file this scaffold writes under the library, relative to its root + // (posix), for the result: a patch that persists the scaffold can then hold + // these files and no other. What it removes is its own earlier output, which + // a clean copy of the library does not hold. + const written /*: Set */ = new Set(); + const write = (file /*: string */, text /*: string */) => { + fs.writeFileSync(file, text, 'utf8'); + written.add(path.relative(dep.root, file).split(path.sep).join('/')); + }; + if (!ctx.dryRun) { - fs.writeFileSync(pkgSwiftPath, content, 'utf8'); + write(pkgSwiftPath, content); const manifest65Path = path.join(dep.root, MIXED_MANIFEST_6_5); if (spec.mixedLanguage != null) { - fs.writeFileSync( + write( manifest65Path, content.replace(MIXED_TOOLS_VERSION_LINE, MIXED_TOOLS_VERSION_LINE_6_5), - 'utf8', ); } else if ( fs.existsSync(manifest65Path) && @@ -2358,10 +2363,9 @@ function scaffoldPackageSwiftForDep( // Emit the ambient-import prefix header next to the manifest when the // target has ObjC(++) sources (the manifest `-include`s it by bare name). if (spec.needsObjCPrefix) { - fs.writeFileSync( + write( path.join(dep.root, SCAFFOLD_PREFIX_HEADER), SCAFFOLD_PREFIX_HEADER_CONTENTS, - 'utf8', ); } // Mirror root-level headers into the generated include// shim @@ -2374,13 +2378,12 @@ function scaffoldPackageSwiftForDep( // Entries may be nested relative paths (e.g. apple/Handlers/X.h): the // stub is named by basename and #imports the real header by path. const name = path.posix.basename(header); - fs.writeFileSync( + write( path.join(shimDir, name), `// AUTO-SCAFFOLDED by react-native spm scaffold — the namespaced\n` + `// spelling (<${spec.swiftName}/${name}>) of the header,\n` + `// matching how CocoaPods header maps expose it.\n` + `#import "../../${header}"\n`, - 'utf8', ); } } @@ -2391,19 +2394,18 @@ function scaffoldPackageSwiftForDep( const name = names?.[i] ?? path.posix.basename(header); const stub = path.join(nsDir, name); fs.mkdirSync(path.dirname(stub), {recursive: true}); - fs.writeFileSync( + write( stub, `// AUTO-SCAFFOLDED by react-native spm scaffold — the <${dir}/${name}>\n` + `// spelling CocoaPods' header_dir gives the header.\n` + `#import "${'../'.repeat(dir.split('/').length + name.split('/').length)}${header}"\n`, - 'utf8', ); }); } } if (!ctx.dryRun && spec.mixedLanguage != null) { - writeMixedLanguageSupport(dep.root, spec.mixedLanguage); + writeMixedLanguageSupport(dep.root, spec.mixedLanguage, write); } if (!ctx.dryRun && spec.publicHeadersPath != null) { const mapPath = path.join( @@ -2413,7 +2415,7 @@ function scaffoldPackageSwiftForDep( ); const map = spec.clangModuleMap; if (map != null) { - fs.writeFileSync( + write( mapPath, `${SCAFFOLDER_MARKER}\n` + '// The module SwiftPM would make of publicHeadersPath, minus the headers the podspec leaves\n' + @@ -2423,7 +2425,6 @@ function scaffoldPackageSwiftForDep( map.excludes.map(h => ` exclude header "${h}"\n`).join('') + ' export *\n' + '}\n', - 'utf8', ); } else if ( fs.existsSync(mapPath) && @@ -2438,12 +2439,11 @@ function scaffoldPackageSwiftForDep( if (spec.reactBareHeaders.length > 0) { fs.mkdirSync(bareDir, {recursive: true}); for (const name of spec.reactBareHeaders) { - fs.writeFileSync( + write( path.join(bareDir, name), `// AUTO-SCAFFOLDED by react-native spm scaffold — the bare "${name}"\n` + `// spelling CocoaPods' header map resolves to React's public header.\n` + `#import \n`, - 'utf8', ); } } @@ -2457,11 +2457,10 @@ function scaffoldPackageSwiftForDep( for (const {pod, header, headers} of spec.podForwarders ?? []) { const file = path.join(podHeadersDir, ...header.split('/')); fs.mkdirSync(path.dirname(file), {recursive: true}); - fs.writeFileSync( + write( file, `// ${SCAFFOLDER_BANNER} — forwards <${header}> to the public headers of the pod ${pod}.\n` + headers.map(h => `#import <${h}>\n`).join(''), - 'utf8', ); } } @@ -2475,6 +2474,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; + if ( + !ctx.dryRun && + (swiftpmName === 'created' || swiftpmName === 'inserted') + ) { + written.add('package.json'); + } return { depName, @@ -2483,6 +2488,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, + files: [...written].sort(), }; } diff --git a/vendor/rn-spm/spm/spm-types.js b/vendor/rn-spm/spm/spm-types.js index 51e146e..73dc6c8 100644 --- a/vendor/rn-spm/spm/spm-types.js +++ b/vendor/rn-spm/spm/spm-types.js @@ -542,6 +542,9 @@ export type ScaffoldResult = // What became of `swiftpmConfig.name` in the library's package.json. // Absent when the name was not podspec-derived, so nothing was attempted. swiftpmName?: SwiftpmNameOutcome, + // Every file the scaffold wrote under the library, relative to its root + // (posix separators), sorted. + files: Array, } | { depName: string, From 1d3fddfa1f79e87fb8d6e8e918ff3fa6dc4fdeab Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 20:30:46 -0600 Subject: [PATCH 09/16] docs: describe what a persisted scaffold holds --- CHANGELOG.md | 3 +++ docs/how-it-works.md | 7 ++++++- docs/troubleshooting.md | 9 ++++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e04f728..d1415c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea - An Objective-C++ file that imports a pod table forward (a bare app's `AppDelegate.mm` with `#import `) compiles, instead of stopping with "use of '@import' when modules are disabled": the scaffold's forwarder `#import`s the pod's public headers instead of `@import`ing its modules. +- A library that was also built for Android gets its scaffold persisted, instead of "⚠ Did not persist 's + scaffold: the patch would contain a binary file (node_modules//android/build/…/BuildConfig.dex)" and a new + scaffold at every build: the patch holds the files the scaffold wrote and those its existing patch held. ## [0.1.0-alpha.6] - 2026-11-05 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index a6e4b4b..d9dd19e 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -358,7 +358,12 @@ patch above is what makes that scaffolder work for real-world podspecs. `rn-spm`, `build` prints one `ℹ Not copied into the app: …` line naming what still does not arrive: plain `resources`, and bundles whose name or files are Ruby code. -- rn-xtool persists the generated file in your project's `patches/` with patch-package: commit those files. +- rn-xtool persists the generated file in your project's `patches/` with patch-package: commit those files. A + persisted patch holds the files the scaffold wrote (the scaffold step lists them) and the files the library's + existing patch already held, so a fix of your own in that patch stays, and build outputs under the package (Gradle's + `android/build` and `.cxx`) never enter it. When rn-xtool cannot read which files the existing patch holds (or the + list would not fit in one argument), it diffs the whole package, as patch-package does by itself, and says so in an + `ℹ` line. - On every build the `patches` step applies rn-xtool's own patches and then your project's `patches/` (when present), so a fresh `node_modules` gets those Package.swift files back. A patch whose package is not installed is left out with a `⚠` line, and the others apply diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 456365f..ac3d397 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -704,7 +704,14 @@ shapes below end `Leave the library out with "exclude" in rn-xtool.config.json.` - **The persist guard.** The `pods` and `pod-binaries` steps write nothing under `node_modules`, so a persisted scaffold never holds the vendor's files. As a guard, rn-xtool does not persist a scaffold patch that would hold a binary file: `⚠ Did not persist 's scaffold: the patch would contain a binary file ()`, or `⚠ Did not persist - 's scaffold: rn-xtool could not read to check it for binary files`. The build goes on. + 's scaffold: rn-xtool could not read to check it for binary files`. The build goes on. A + persisted patch holds only the files the scaffold wrote and those the library's existing patch held, so the Android + build outputs under the package (`android/build/…/*.dex`) stay out of it. The binary line can still appear when the library's existing patch holds a binary file, or when rn-xtool + diffs the whole package and a build left binaries under it: an `ℹ … persisting 's whole package, …` line + before it says why (most often `ℹ Could not tell which files patches/ changes`, a patch whose + `diff --git a/node_modules//…` headers it cannot read). For the first, remove the binary file's section from + the patch; for the second, fix or delete the patch the `ℹ` line names, or remove the library's build outputs + (`android/build`, `android/.cxx`), then build. ### knownLimits.allow and binary pods From 983d079e520e7b675bf34af5a54cc2c06d7f3fb7 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 21:04:45 -0600 Subject: [PATCH 10/16] fix: evaluate Ruby locals in podspec globs --- patches/react-native+0.88.0.patch | 1114 ++++++++++++++--- patches/react-native+0.88.1.patch | 1114 ++++++++++++++--- .../podspecs/RNScreens-4.24.0/LICENSE | 21 + .../RNScreens-4.24.0/RNScreens.podspec | 77 ++ .../rnscreens/RNSScreenShadowNode.cpp | 0 .../rnscreens/RNSScreenShadowNode.h | 0 .../cpp/RNScreensTurboModule.cpp | 0 .../cpp/RNScreensTurboModule.h | 0 .../podspecs/RNScreens-4.24.0/ios/RNSScreen.h | 0 .../RNScreens-4.24.0/ios/RNSScreen.mm | 0 .../RNScreens-4.24.0/ios/RNSScreenStack.h | 0 .../RNScreens-4.24.0/ios/RNSScreenStack.mm | 0 .../ios/bridging/RNSReactBaseView.h | 0 .../ios/bridging/RNSReactBaseView.mm | 0 .../ios/bridging/Swift-Bridging.h | 7 + .../ReactMountingTransactionObserving.swift | 0 .../stack/host/RNSStackHostComponentView.h | 0 .../stack/host/RNSStackHostComponentView.mm | 0 .../ios/stubs/RNSGammaStubs.h | 0 .../ios/stubs/RNSGammaStubs.mm | 0 .../podspecs/RNScreens-4.24.0/package.json | 78 ++ .../react-native-svg/Package.swift | 1 + .../react-native-svg/apple/module.modulemap | 8 - tests/rn-scaffolder.test.ts | 152 ++- tests/tarballs.test.ts | 4 +- vendor/rn-spm/rn-xtool-edits.patch | 2 +- vendor/rn-spm/spm/read-podspec.js | 932 ++++++++++++-- vendor/rn-spm/spm/scaffold-package-swift.js | 12 +- vendor/rn-spm/spm/spm-types.js | 4 + 29 files changed, 3132 insertions(+), 394 deletions(-) create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/LICENSE create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/RNScreens.podspec create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.cpp create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.cpp create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.mm create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.mm create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.mm create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/Swift-Bridging.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/ReactMountingTransactionObserving.swift create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.mm create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.h create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.mm create mode 100644 tests/fixtures/podspecs/RNScreens-4.24.0/package.json delete mode 100644 tests/fixtures/scaffold-golden/react-native-svg/apple/module.modulemap diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index 700e77b..1d117a6 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1,5 +1,5 @@ diff --git a/node_modules/react-native/scripts/spm/read-podspec.js b/node_modules/react-native/scripts/spm/read-podspec.js -index 8fcf04b..b3e3a53 100644 +index 8fcf04b..6ed3f14 100644 --- a/node_modules/react-native/scripts/spm/read-podspec.js +++ b/node_modules/react-native/scripts/spm/read-podspec.js @@ -102,13 +102,12 @@ function runPodIpcSpec(podspecPath /*: string */) /*: RawSpec | null */ { @@ -22,106 +22,836 @@ index 8fcf04b..b3e3a53 100644 }); } catch { cleanupPatchedPodspec(patchedPath); -@@ -170,58 +169,337 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { +@@ -170,58 +169,1072 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { // Regex fallback // --------------------------------------------------------------------------- -+// Ruby constants. Podspecs commonly hoist a glob or extension list into a local -+// and reuse it (react-native-screens: `source_files_exts = '{h,m,mm,cpp}'`, -+// `source_files = ["ios/**/*.#{source_files_exts}"]`, `s.source_files = -+// source_files`). The field regexes below only understand literals, so such a -+// field read as missing and the library scaffolded with no sources. ++// Ruby locals and conditions. Podspecs hoist globs, extension lists and flags ++// into locals and set them under conditions; react-native-screens 4.24.0: +// -+// This pre-pass resolves the simple cases textually, so the regexes stay -+// untouched: single-line `ident = 'str' | "str" | ["a", "b"]` assignments are -+// collected (first assignment wins; `if`/`ENV[...]` conditions are NOT -+// evaluated, except the one kind below), then `#{ident}` inside the text is replaced by a known string -+// constant, and a field assigned a bare known identifier (`s.x = ident`) is -+// rewritten to the literal value (`s.x = ident`, `s.ios.x = ident`, and a -+// subspec's `ss.x = ident`). `#{}` is only interpolated inside double-quoted -+// strings, as in Ruby. Unknown interpolations/identifiers are left as they are. ++// new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1' ++// source_files_exts = ++// new_arch_enabled ? '{h,m,mm,cpp,swift}' : '{h,m,mm,swift}' ++// source_files = ["ios/**/*.#{source_files_exts}"] ++// if !new_arch_enabled ++// source_files.push("cpp/RNScreensTurboModule.cpp", ...) ++// end ++// ... ++// s.source_files = source_files ++// if !gamma_project_enabled ++// s.exclude_files = "ios/gamma/**/*.#{source_files_exts}" ++// else ... +// -+// One kind of condition is evaluated: a string ternary on an environment -+// variable React Native's CocoaPods setup itself sets for every pod -+// (`ident = ENV['VAR'] == 'v' ? 'a' : 'b'`, also `!=`), with the value that -+// setup gives it: `1` for both. The environment is not read. React Native -+// 0.87+ sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, -+// so a `0` left in the shell could only break the build (and a persisted -+// scaffold). react-native-worklets puts -+// `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == '1' ? '-DHERMES_V1_ENABLED' -+// : ''` in OTHER_CFLAGS; without the define it includes the legacy Hermes -+// inspector headers, which the prebuilt artifacts do not ship. ++// The field regexes below only understand literals, so this pre-pass runs the ++// podspec's statements in order over a small, side-effect-free subset of Ruby ++// and leaves the regexes a flat text: ++// ++// - values: string literals (single quotes verbatim, double quotes with ++// `#{expr}` interpolation), `%w[...]`, array literals, numbers, `true`, ++// `false`, `nil`, and locals (`name = expr`, also `+=` and `||=`; the last ++// assignment that runs wins, as in Ruby); ++// - `ENV['X']` and `ENV.fetch('X', default)`: `RCT_NEW_ARCH_ENABLED` and ++// `RCT_HERMES_V1_ENABLED` are `1` (below), every other variable is unset. ++// The environment is never read, so a scaffold does not depend on the shell; ++// - `==`, `!=`, `!`/`not`, `&&`/`and`, `||`/`or`, `+` on strings and arrays, ++// `a ? b : c`, `array.join(sep)`, `.to_s`, `.freeze`; ++// - `if`/`elsif`/`else`/`unless`/`end` blocks and `stmt if cond` / `stmt ++// unless cond` modifiers, at the top level and inside the spec and subspec ++// blocks: a branch that does not run is blanked, the control lines of a ++// condition that was evaluated are dropped; ++// - `local.push(...)`, `local.append(...)`, `local.concat(...)`, `local << x`; ++// - `recv. = expr` on the spec or a subspec (`s.`, `s.ios.`, `ss.`): ++// a value that is not already a literal is rewritten to the literal it ++// evaluates to. Inside a hash (`pod_target_xcconfig`, `resource_bundles`), ++// `=> local` is replaced by the local's value. ++// ++// Anything else (method calls, hashes, symbols, `$config[...]`, blocks other ++// than the spec's, conditions on any of these) is not evaluated: the text ++// stays as written, and a local assigned from it, or under such a condition, is ++// unknown from there on. Both branches of such a condition stay visible, as ++// before (react-native-vision-camera's `if enableFrameProcessors` subspec). A ++// `source_files` or `exclude_files` value that uses something unknown is ++// returned in `unresolved`, and the scaffolder refuses the library ++// (unresolvedSourcesReason): a glob read in part gives a target that builds ++// and lacks the library's classes, so the app crashes at start ++// (react-native-screens 4.24.0 lost all of ios/). ++// ++// `RCT_NEW_ARCH_ENABLED` and `RCT_HERMES_V1_ENABLED` get the value React ++// Native's CocoaPods setup gives every pod, `1` for both. React Native 0.87+ ++// sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, so a ++// `0` left in the shell could only break the build (and a persisted scaffold). ++// react-native-worklets puts `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == ++// '1' ? '-DHERMES_V1_ENABLED' : ''` in OTHER_CFLAGS; without the define it ++// includes the legacy Hermes inspector headers, which the prebuilt artifacts ++// do not ship. +const RN_POD_ENV /*: {[string]: string} */ = { + RCT_NEW_ARCH_ENABLED: '1', + RCT_HERMES_V1_ENABLED: '1', +}; -+function rnPodEnvTernary(rhs /*: string */) /*: ?string */ { -+ const m = rhs.match( -+ /^ENV\[\s*(["'])([A-Z0-9_]+)\1\s*\]\s*(==|!=)\s*(["'])([^"']*)\4\s*\?\s*(?:"([^"]*)"|'([^']*)')\s*:\s*(?:"([^"]*)"|'([^']*)')$/, ++ ++// A value the evaluator could not compute, and why. ++class RubyUnresolved { ++ /*:: why: string; */ ++ constructor(why /*: string */) { ++ this.why = why; ++ } ++} ++const isUnresolved = (v /*: mixed */) /*: boolean */ => ++ v instanceof RubyUnresolved; ++ ++// The source-glob fields an unevaluated expression must not reach silently. ++const STRICT_FIELDS /*: Set */ = new Set([ ++ 'source_files', ++ 'exclude_files', ++]); ++const PLATFORM_SCOPES /*: Set */ = new Set([ ++ 'ios', ++ 'osx', ++ 'macos', ++ 'tvos', ++ 'visionos', ++ 'watchos', ++]); ++ ++// Tokens of one Ruby expression. A double-quoted string keeps its parts: ++// literal text and the source of each `#{...}`. ++function tokenizeRubyExpr(src /*: string */) /*: Array */ { ++ const tokens = []; ++ let i = 0; ++ // The end of a `#{...}` starting at `from` (just past `#{`), or -1. ++ const interpEnd = (from /*: number */) => { ++ let depth = 1; ++ let quote = ''; ++ for (let j = from; j < src.length; j++) { ++ const c = src[j]; ++ if (quote !== '') { ++ if (c === '\\') j++; ++ else if (c === quote) quote = ''; ++ } else if (c === '"' || c === "'") quote = c; ++ else if (c === '{') depth++; ++ else if (c === '}' && --depth === 0) return j; ++ } ++ return -1; ++ }; ++ const CLOSE = {'[': ']', '(': ')', '{': '}', '<': '>'}; ++ while (i < src.length) { ++ const c = src[i]; ++ if (/\s/.test(c)) { ++ i++; ++ } else if (c === "'") { ++ let v = ''; ++ let j = i + 1; ++ for (; j < src.length && src[j] !== "'"; j++) { ++ if (src[j] === '\\' && (src[j + 1] === "'" || src[j + 1] === '\\')) { ++ v += src[++j]; ++ } else v += src[j]; ++ } ++ if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; ++ tokens.push({t: 'str', parts: [v]}); ++ i = j + 1; ++ } else if (c === '"') { ++ const parts = []; ++ let v = ''; ++ let j = i + 1; ++ for (; j < src.length && src[j] !== '"'; j++) { ++ if (src[j] === '\\') { ++ const e = src[++j]; ++ v += e === 'n' ? '\n' : e === 't' ? '\t' : e; ++ } else if (src[j] === '#' && src[j + 1] === '{') { ++ const end = interpEnd(j + 2); ++ if (end < 0) return [{t: 'bad', v: src.slice(i)}]; ++ parts.push(v, {expr: src.slice(j + 2, end)}); ++ v = ''; ++ j = end; ++ } else v += src[j]; ++ } ++ if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; ++ parts.push(v); ++ tokens.push({t: 'str', parts}); ++ i = j + 1; ++ } else if (c === '%' && /^%w[[({<]/.test(src.slice(i, i + 3))) { ++ const close = CLOSE[src[i + 2]]; ++ const end = src.indexOf(close, i + 3); ++ if (end < 0) return [{t: 'bad', v: src.slice(i)}]; ++ tokens.push({ ++ t: 'words', ++ v: src ++ .slice(i + 3, end) ++ .split(/\s+/) ++ .filter(Boolean), ++ }); ++ i = end + 1; ++ } else if (/[0-9]/.test(c)) { ++ const m = src.slice(i).match(/^[0-9][0-9_.]*/); ++ const text = m != null ? m[0] : c; ++ tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); ++ i += text.length; ++ } else if (/[A-Za-z_]/.test(c)) { ++ const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); ++ const text = m != null ? m[0] : c; ++ tokens.push({t: 'id', v: text}); ++ i += text.length; ++ } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { ++ tokens.push({t: 'bad', v: src.slice(i)}); // a symbol ++ i = src.length; ++ } else { ++ const two = src.slice(i, i + 2); ++ if (['==', '!=', '&&', '||', '=>', '::', '<<', '=~'].includes(two)) { ++ tokens.push({t: 'op', v: two}); ++ i += 2; ++ } else { ++ tokens.push({t: 'op', v: c}); ++ i++; ++ } ++ } ++ } ++ return tokens; ++} ++ ++const rubyTruthy = (v /*: mixed */) /*: boolean */ => v !== false && v != null; ++ ++function rubyEqual(a /*: mixed */, b /*: mixed */) /*: boolean */ { ++ if (Array.isArray(a) && Array.isArray(b)) { ++ return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); ++ } ++ return a === b; ++} ++ ++// `#{v}`: Ruby's to_s for the values the evaluator knows. ++function rubyToS(v /*: mixed */) /*: string | RubyUnresolved */ { ++ if (typeof v === 'string') return v; ++ if (v == null) return ''; ++ if (typeof v === 'boolean' || typeof v === 'number') return String(v); ++ return new RubyUnresolved('an array or hash inside `#{...}`'); ++} ++ ++/** ++ * Evaluates one Ruby expression with the locals in `env`. Returns the value, ++ * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list ++ * (`s.x = "a", "b"`) as an array. Never runs anything. ++ */ ++function evalRubyExpr( ++ src /*: string */, ++ env /*: Map */, ++ list /*:: ?: boolean */, ++) /*: mixed */ { ++ const tokens = tokenizeRubyExpr(src); ++ let pos = 0; ++ const peek = (v /*: string */) => ++ tokens[pos] != null && ++ (tokens[pos].t === 'op' || tokens[pos].t === 'id') && ++ tokens[pos].v === v; ++ const take = (v /*: string */) => { ++ if (!peek(v)) return false; ++ pos++; ++ return true; ++ }; ++ const fail = (why /*: string */) => new RubyUnresolved(why); ++ // Skips a balanced (...) / [...] / {...} group starting at `pos`. ++ const skipGroup = () => { ++ let depth = 0; ++ do { ++ const tk = tokens[pos++]; ++ if (tk == null) return; ++ if (tk.t === 'op' && '([{'.includes(tk.v)) depth++; ++ if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; ++ } while (depth > 0); ++ }; ++ // Comma-separated expressions up to `close` (already past the opener). ++ const parseItems = (close /*: string */) => { ++ const items = []; ++ while (!peek(close)) { ++ if (tokens[pos] == null) return fail(`a missing \`${close}\``); ++ items.push(parseTernary()); ++ if (!take(',')) break; ++ } ++ if (!take(close)) return fail(`a missing \`${close}\``); ++ return items.find(isUnresolved) ?? items; ++ }; ++ function parsePrimary() /*: mixed */ { ++ const tk = tokens[pos++]; ++ if (tk == null) return fail('an incomplete expression'); ++ if (tk.t === 'str') { ++ let out = ''; ++ for (const part of tk.parts) { ++ if (typeof part === 'string') { ++ out += part; ++ continue; ++ } ++ const inner = evalRubyExpr(part.expr, env); ++ if (isUnresolved(inner)) return inner; ++ const s = rubyToS(inner); ++ if (isUnresolved(s)) return s; ++ out += (s /*: any */); ++ } ++ return out; ++ } ++ if (tk.t === 'words') return tk.v; ++ if (tk.t === 'num') return tk.v; ++ if (tk.t === 'bad') return fail(`\`${tk.v}\``); ++ if (tk.t === 'op') { ++ if (tk.v === '(') { ++ const v = parseTernary(); ++ return take(')') ? v : fail('a missing `)`'); ++ } ++ if (tk.v === '[') return parseItems(']'); ++ if (tk.v === '{') return fail('a hash'); ++ return fail(`\`${tk.v}\``); ++ } ++ // An identifier. ++ const name = tk.v; ++ if (name === 'true') return true; ++ if (name === 'false') return false; ++ if (name === 'nil') return null; ++ if (name === 'ENV') { ++ if (take('[')) { ++ const key = parseTernary(); ++ if (!take(']')) return fail('a missing `]`'); ++ if (isUnresolved(key)) return key; ++ return typeof key === 'string' && Object.hasOwn(RN_POD_ENV, key) ++ ? RN_POD_ENV[key] ++ : null; ++ } ++ if (take('.') && take('fetch') && take('(')) { ++ const args = parseItems(')'); ++ if (isUnresolved(args)) return args; ++ const [key, fallback] = (args /*: any */); ++ if (typeof key !== 'string') return fail('`ENV.fetch` of a non-string'); ++ return Object.hasOwn(RN_POD_ENV, key) ? RN_POD_ENV[key] : fallback; ++ } ++ return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); ++ } ++ if (peek('(')) { ++ skipGroup(); ++ return fail(`the method call \`${name}(...)\``); ++ } ++ if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); ++ const v = env.get(name); ++ if (isUnresolved(v)) { ++ return fail(`\`${name}\`, which ${(v /*: any */).why}`); ++ } ++ return v; ++ } ++ function parsePostfix() /*: mixed */ { ++ let v = parsePrimary(); ++ while (peek('.') || peek('[')) { ++ if (take('[')) { ++ pos--; ++ skipGroup(); ++ v = isUnresolved(v) ? v : fail('an index `[...]`'); ++ continue; ++ } ++ take('.'); ++ const m = tokens[pos++]; ++ const method = m != null && m.t === 'id' ? m.v : '?'; ++ let args = []; ++ if (peek('(')) { ++ pos++; ++ const got = parseItems(')'); ++ if (isUnresolved(got)) { ++ v = isUnresolved(v) ? v : got; ++ continue; ++ } ++ args = (got /*: any */); ++ } ++ if (isUnresolved(v)) continue; ++ if ((method === 'freeze' || method === 'to_s') && typeof v === 'string') { ++ continue; ++ } ++ if (method === 'join' && Array.isArray(v)) { ++ const sep = args.length > 0 ? args[0] : ''; ++ const parts = v.flat(Infinity).map(rubyToS); ++ const bad = parts.find(isUnresolved); ++ v = ++ bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); ++ continue; ++ } ++ v = fail(`the method call \`.${method}\``); ++ } ++ return v; ++ } ++ function parseUnary() /*: mixed */ { ++ if (take('!')) { ++ const v = parseUnary(); ++ return isUnresolved(v) ? v : !rubyTruthy(v); ++ } ++ return parsePostfix(); ++ } ++ function parseAdd() /*: mixed */ { ++ let l = parseUnary(); ++ while (take('+')) { ++ const r = parseUnary(); ++ if (isUnresolved(l)) continue; ++ if (isUnresolved(r)) l = r; ++ else if (typeof l === 'string' && typeof r === 'string') l = l + r; ++ else if (Array.isArray(l) && Array.isArray(r)) l = [...l, ...r]; ++ else l = fail('`+` on values other than two strings or two arrays'); ++ } ++ return l; ++ } ++ function parseEq() /*: mixed */ { ++ const l = parseAdd(); ++ if (peek('==') || peek('!=')) { ++ const op = tokens[pos++].v; ++ const r = parseAdd(); ++ if (isUnresolved(l)) return l; ++ if (isUnresolved(r)) return r; ++ return op === '==' ? rubyEqual(l, r) : !rubyEqual(l, r); ++ } ++ if (peek('=~') || peek('<') || peek('>')) { ++ return fail(`the operator \`${tokens[pos].v}\``); ++ } ++ return l; ++ } ++ function parseNot() /*: mixed */ { ++ if (take('not')) { ++ const v = parseNot(); ++ return isUnresolved(v) ? v : !rubyTruthy(v); ++ } ++ return parseEq(); ++ } ++ function parseAnd() /*: mixed */ { ++ let l = parseNot(); ++ while (take('&&') || take('and')) { ++ const r = parseNot(); ++ if (!isUnresolved(l) && rubyTruthy(l)) l = r; ++ } ++ return l; ++ } ++ function parseOr() /*: mixed */ { ++ let l = parseAnd(); ++ while (take('||') || take('or')) { ++ const r = parseAnd(); ++ if (!isUnresolved(l) && !rubyTruthy(l)) l = r; ++ } ++ return l; ++ } ++ function parseTernary() /*: mixed */ { ++ const c = parseOr(); ++ if (!take('?')) return c; ++ const a = parseTernary(); ++ if (!take(':')) return fail('a ternary without `:`'); ++ const b = parseTernary(); ++ if (isUnresolved(c)) return c; ++ return rubyTruthy(c) ? a : b; ++ } ++ let value = parseTernary(); ++ if (list === true && peek(',')) { ++ const items = [value]; ++ while (take(',')) items.push(parseTernary()); ++ value = items.find(isUnresolved) ?? items; ++ } ++ if (pos < tokens.length && !isUnresolved(value)) { ++ const rest = tokens[pos]; ++ return fail( ++ rest.t === 'op' || rest.t === 'id' ++ ? `\`${rest.v}\` where it ends` ++ : 'more than one expression', ++ ); ++ } ++ return value; ++} ++ ++// A literal the field regexes read as written: quoted strings without ++// `#{...}`, as one value, an array or a bare list. ++function isPlainLiteral(rhs /*: string */) /*: boolean */ { ++ const str = `(?:"[^"\\\\#]*"|'[^'\\\\]*')`; ++ const list = `${str}(?:\\s*,\\s*${str})*`; ++ return new RegExp( ++ `^(?:${list}|\\[\\s*(?:${list}\\s*,?)?\\s*\\]|true|false)$`, ++ ).test(rhs.trim()); ++} ++ ++// The literal a field is rewritten to, or null when the value has none. ++function rubyLiteral(v /*: mixed */) /*: ?string */ { ++ if (typeof v === 'string') return JSON.stringify(v); ++ if (typeof v === 'boolean') return String(v); ++ if (Array.isArray(v)) { ++ const flat = v.flat(Infinity); ++ if (!flat.every(x => typeof x === 'string')) return null; ++ return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; ++ } ++ return null; ++} ++ ++// The podspec's logical statements: lines joined while a bracket or string is ++// open or the line ends in `,`, `\`, an operator or `=`. A heredoc's body ++// belongs to the statement that opens it. `code` is the statement without ++// trailing comments. ++function rubyStatements( ++ lines /*: Array */, ++) /*: Array<{start: number, end: number, code: string}> */ { ++ const out = []; ++ const scan = ( ++ line /*: string */, ++ state /*: {depth: number, quote: string} */, ++ ) => { ++ let code = ''; ++ for (let i = 0; i < line.length; i++) { ++ const c = line[i]; ++ if (state.quote !== '') { ++ code += c; ++ if (c === '\\') code += line[++i] ?? ''; ++ else if (c === state.quote) state.quote = ''; ++ continue; ++ } ++ if (c === '#') break; ++ code += c; ++ if (c === '"' || c === "'") state.quote = c; ++ else if ('([{'.includes(c)) state.depth++; ++ else if (')]}'.includes(c)) state.depth--; ++ } ++ return code; ++ }; ++ let i = 0; ++ while (i < lines.length) { ++ const start = i; ++ const state = {depth: 0, quote: ''}; ++ const codes = []; ++ let heredoc = null; ++ while (i < lines.length) { ++ const code = scan(lines[i], state); ++ codes.push(code); ++ i++; ++ const h = code.match(/<<([-~]?)(["']?)([A-Za-z_]\w*)\2\s*$/); ++ if (h != null && state.quote === '') { ++ heredoc = {indented: h[1] !== '', id: h[3]}; ++ break; ++ } ++ const open = ++ state.depth > 0 || ++ state.quote !== '' || ++ /(?:,|\\|&&|\|\||[^=!<>]=|\+|\s\?|\s:)\s*$/.test(code); ++ if (!open) break; ++ } ++ if (i >= lines.length && (state.depth > 0 || state.quote !== '')) { ++ // Never closed: read the first line alone and go on from the next. ++ const code = scan(lines[start], {depth: 0, quote: ''}); ++ out.push({start, end: start, code}); ++ i = start + 1; ++ continue; ++ } ++ if (heredoc != null) { ++ const {indented, id} = heredoc; ++ while (i < lines.length) { ++ const l = lines[i++]; ++ if ((indented ? l.trim() : l) === id) break; ++ } ++ } ++ out.push({start, end: i - 1, code: codes.join('\n')}); ++ } ++ return out; ++} ++ ++// The index of a trailing `if`/`unless` modifier outside strings and brackets. ++function modifierIndex(code /*: string */) /*: ?{at: number, kw: string} */ { ++ let quote = ''; ++ let depth = 0; ++ for (let i = 1; i < code.length; i++) { ++ const c = code[i]; ++ if (quote !== '') { ++ if (c === '\\') i++; ++ else if (c === quote) quote = ''; ++ continue; ++ } ++ if (c === '"' || c === "'") quote = c; ++ else if ('([{'.includes(c)) depth++; ++ else if (')]}'.includes(c)) depth--; ++ else if (depth === 0 && /\s/.test(code[i - 1])) { ++ const m = code.slice(i).match(/^(if|unless)\s/); ++ if (m != null) return {at: i, kw: m[1]}; ++ } ++ } ++ return null; ++} ++ ++/*:: ++type Unresolved = {field: string, expr: string, why: string}; ++type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; ++*/ ++ ++// Why a local set under `act` is unknown from there on. ++function unknownUnder(act /*: Activity */) /*: RubyUnresolved */ { ++ return new RubyUnresolved( ++ act.state === 'maybe' ++ ? `is set under \`${act.why}\`, a condition the reader cannot evaluate` ++ : `is set inside \`${act.why}\`, a block the reader does not run`, + ); -+ if (m == null || !Object.hasOwn(RN_POD_ENV, m[2])) return null; -+ const value = RN_POD_ENV[m[2]]; -+ const holds = m[3] === '==' ? value === m[5] : value !== m[5]; -+ return holds ? m[6] ?? m[7] : m[8] ?? m[9]; +} -+function resolveRubyConstants(content /*: string */) /*: string */ { -+ const strings /*: Map */ = new Map(); -+ const arrays /*: Map> */ = -+ new Map(); -+ const assignRe = /^[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*(.+?)[ \t]*$/gm; -+ for (const m of content.matchAll(assignRe)) { -+ const name = m[1]; -+ if (strings.has(name) || arrays.has(name)) continue; -+ const rhs = m[2]; -+ const str = rhs.match(/^(?:"([^"]*)"|'([^']*)')$/); -+ if (str != null) { -+ strings.set(name, str[1] ?? str[2]); ++ ++// The branch an `elsif` opens, and what is known of the branches before it. ++function elsifBranch( ++ prior /*: string */, ++ cond /*: string */, ++) /*: {branch: string, prior: string} */ { ++ if (prior === 'yes') return {branch: 'no', prior: 'yes'}; ++ if (prior === 'no') return {branch: cond, prior: cond}; ++ // An earlier branch may have run. ++ return { ++ branch: cond === 'no' ? 'no' : 'maybe', ++ prior: cond === 'yes' ? 'yes' : 'maybe', ++ }; ++} ++ ++/** ++ * Runs the podspec's statements over the subset above. Returns the rewritten ++ * text (same line count) and each `source_files`/`exclude_files` assignment ++ * whose value could not be evaluated. ++ */ ++function evaluateRubyLocals( ++ content /*: string */, ++) /*: {text: string, unresolved: Array} */ { ++ const lines = content.split('\n'); ++ const out = lines.slice(); ++ const env /*: Map */ = new Map(); ++ const recvs /*: Set */ = new Set(); ++ const unresolved /*: Array */ = []; ++ // `if` blocks (which branch is being read) and other blocks. ++ const frames /*: Array */ = []; ++ const blank = (st /*: {start: number, end: number} */) => { ++ for (let k = st.start; k <= st.end; k++) out[k] = ''; ++ }; ++ // Whether the statement being read runs: 'yes', 'no', 'maybe' (under a ++ // condition it cannot evaluate) or 'opaque' (in a block it does not run), ++ // with the condition or block that decides. ++ const activity = () /*: Activity */ => { ++ let act /*: Activity */ = {state: 'yes', why: ''}; ++ for (const f of frames) { ++ const s = f.kind === 'if' ? f.branch : f.opaque ? 'opaque' : 'yes'; ++ if (s === 'no') return {state: 'no', why: ''}; ++ if (s !== 'yes' && act.state === 'yes') { ++ act = {state: s, why: f.kind === 'if' ? f.cond : f.code}; ++ } ++ } ++ return act; ++ }; ++ const condOf = (src /*: string */, negate /*: boolean */) => { ++ const v = evalRubyExpr(src, env); ++ if (isUnresolved(v)) return 'maybe'; ++ return rubyTruthy(v) !== negate ? 'yes' : 'no'; ++ }; ++ // Lines that stay as written: `#{local}` (a known string) in their ++ // double-quoted literals, and `=> local` inside a hash, get the value. ++ const interpolate = ( ++ st /*: {start: number, end: number} */, ++ hash /*: boolean */, ++ ) => { ++ const known = (id /*: string */) => { ++ const v = env.get(id); ++ return typeof v === 'string' ? v : null; ++ }; ++ for (let k = st.start; k <= st.end; k++) { ++ out[k] = out[k].replace( ++ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, ++ lit => ++ lit[0] === '"' ++ ? lit.replace( ++ /#\{\s*([A-Za-z_]\w*)\s*\}/g, ++ (whole, id) => known(id) ?? whole, ++ ) ++ : lit, ++ ); ++ if (hash) { ++ out[k] = out[k].replace( ++ /(=>\s*)([A-Za-z_]\w*)(?=\s*(?:,|\}|$))/g, ++ (whole, arrow, id) => { ++ const lit = env.has(id) ? rubyLiteral(env.get(id)) : null; ++ return lit != null ? arrow + lit : whole; ++ }, ++ ); ++ } ++ } ++ }; ++ const setLocal = ( ++ name /*: string */, ++ value /*: mixed */, ++ act /*: Activity */, ++ ) => { ++ env.set(name, act.state === 'yes' ? value : unknownUnder(act)); ++ }; ++ ++ for (const st of rubyStatements(lines)) { ++ const code = st.code.trim(); ++ if (code === '') continue; ++ const act = activity(); ++ const oneLine = /[\s;]end\s*;?$/.test(code); ++ const top = frames[frames.length - 1]; ++ let m; ++ m = oneLine ? null : code.match(/^(if|unless)\s+([\s\S]+?)(?:\s+then)?$/); ++ if (m != null) { ++ // Under a branch that does not run, every branch is dead. ++ const branch = ++ act.state === 'no' || act.state === 'opaque' ++ ? act.state ++ : condOf(m[2], m[1] === 'unless'); ++ frames.push({ ++ kind: 'if', ++ branch, ++ prior: act.state === 'no' ? 'yes' : branch, ++ cond: m[2], ++ evaluated: branch !== 'maybe' && branch !== 'opaque', ++ ctrl: [st], ++ }); + continue; + } -+ const fromEnv = rnPodEnvTernary(rhs); -+ if (fromEnv != null) { -+ strings.set(name, fromEnv); ++ if (top?.kind === 'if') { ++ if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { ++ top.ctrl.push(st); ++ if (top.branch === 'opaque') continue; ++ const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); ++ if (cond === 'maybe') top.evaluated = false; ++ Object.assign(top, elsifBranch(top.prior, cond), {cond: m[1]}); ++ continue; ++ } ++ if (code === 'else') { ++ top.ctrl.push(st); ++ if (top.branch !== 'opaque') { ++ top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; ++ } ++ continue; ++ } ++ } ++ if (/^end\b/.test(code) && top != null) { ++ frames.pop(); ++ // An evaluated condition leaves no control lines behind. ++ if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { ++ for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); ++ blank(st); ++ } + continue; + } -+ const arr = rhs.match(/^\[([^\]]*)\]$/); -+ if (arr != null) { -+ const items = []; -+ for (const it of arr[1].matchAll(/"([^"]*)"|'([^']*)'/g)) { -+ items.push({value: it[1] ?? it[2], dq: it[1] != null}); ++ const opensBlock = ++ !oneLine && ++ (/^(?:case|begin|while|until|for|def|class|module)\b/.test(code) || ++ /\bdo(?:\s*\|[^|]*\|)?\s*$/.test(code) || ++ /=\s*(?:if|unless|case|begin)\b/.test(code)); ++ if (opensBlock) { ++ // The spec's and its subspecs' blocks run; any other is opaque. ++ const spec = code.match(/Pod::Spec\.new\s+do\s*\|\s*(\w+)\s*\|\s*$/); ++ const sub = code.match( ++ /^(\w+)\.subspec\s[\s\S]*\bdo\s*\|\s*(\w+)\s*\|\s*$/, ++ ); ++ const recv = ++ spec?.[1] ?? (sub != null && recvs.has(sub[1]) ? sub[2] : null); ++ if (recv != null) recvs.add(recv); ++ const assigned = code.match(/^([A-Za-z_]\w*)\s*=/); ++ if (assigned != null) { ++ setLocal(assigned[1], null, {state: 'opaque', why: code}); + } -+ arrays.set(name, items); ++ frames.push({kind: 'block', opaque: recv == null, code}); ++ if (act.state === 'no') blank(st); ++ continue; + } -+ } -+ if (strings.size === 0 && arrays.size === 0) return content; -+ const interpolate = (text /*: string */) => -+ text.replace(/#\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g, (whole, id) => -+ strings.has(id) ? (strings.get(id) /*: any */) : whole, ++ if (act.state === 'no') { ++ blank(st); ++ continue; ++ } ++ // A trailing `if`/`unless` modifier. ++ let core = code; ++ let stAct = act; ++ const mod = modifierIndex(code); ++ if (mod != null) { ++ core = code.slice(0, mod.at).trim(); ++ const cond = code.slice(mod.at + mod.kw.length).trim(); ++ const c = ++ act.state === 'yes' ? condOf(cond, mod.kw === 'unless') : act.state; ++ if (c === 'no') { ++ blank(st); ++ continue; ++ } ++ if (c === 'maybe' && act.state === 'yes') { ++ stAct = {state: 'maybe', why: cond}; ++ } ++ } ++ // `recv.field = expr` on the spec or a subspec. Under a condition it ++ // cannot evaluate, or in a block it does not run, it is read as if it ran, ++ // as the field regexes always did: a literal stays as written, an ++ // expression is evaluated or, in a source glob, refused. ++ const field = core.match( ++ /^([A-Za-z_]\w*)(?:\.([a-z]+))?\.([a-z_]+)\s*=(?![=~>])\s*([\s\S]+)$/, + ); -+ // Constants may be built from earlier ones: resolve the arrays' items too -+ // (double-quoted items only). -+ const arrayValues /*: Map> */ = new Map(); -+ for (const [k, v] of arrays) { -+ arrayValues.set(k, v.map(i => (i.dq ? interpolate(i.value) : i.value))); -+ } -+ // Only double-quoted string literals interpolate; scan literal by literal -+ // (a line never spans a string here) so `'ios/*.#{x}'` stays as written. -+ const interpolated = content.replace( -+ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, -+ lit => (lit[0] === '"' ? interpolate(lit) : lit), -+ ); -+ const quote = (v /*: string */) => JSON.stringify(v); -+ return interpolated.replace( -+ /^(\s*[A-Za-z_]\w*(?:\.(?:ios|osx|tvos|visionos|watchos))?\.[A-Za-z_]+\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)[ \t]*$/gm, -+ (whole, lhs, id) => { -+ if (strings.has(id)) return lhs + quote((strings.get(id) /*: any */)); -+ if (arrayValues.has(id)) { -+ return ( -+ lhs + '[' + (arrayValues.get(id) /*: any */).map(quote).join(', ') + ']' ++ if ( ++ field != null && ++ recvs.has(field[1]) && ++ (field[2] == null || PLATFORM_SCOPES.has(field[2])) ++ ) { ++ const [, recv, scope, name, rhs] = field; ++ // Only the spec's own and its `ios` scope count. ++ if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; ++ const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; ++ const v = evalRubyExpr(rhs, env, true); ++ const lit = isUnresolved(v) ? null : rubyLiteral(v); ++ if (lit != null) { ++ blank(st); ++ const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; ++ out[st.start] = `${indent}${lhs} = ${lit}`; ++ } else if (STRICT_FIELDS.has(name)) { ++ unresolved.push({ ++ field: lhs, ++ expr: rhs.trim(), ++ why: isUnresolved(v) ++ ? `it uses ${(v /*: any */).why}` ++ : 'its value is not a string or an array of strings', ++ }); ++ } else { ++ interpolate(st, /^\{/.test(rhs.trim())); ++ } ++ continue; ++ } ++ // `name = expr`, `name += expr`, `name ||= expr`. ++ const assign = core.match( ++ /^([A-Za-z_]\w*)\s*(\+=|\|\|=|=)(?![=~>])\s*([\s\S]+)$/, ++ ); ++ if (assign != null && !recvs.has(assign[1])) { ++ const [, name, op, rhs] = assign; ++ let v = evalRubyExpr(rhs, env); ++ if (op !== '=' && !isUnresolved(v)) { ++ const vars = new Map([ ++ ['old', env.has(name) ? env.get(name) : null], ++ ['new', v], ++ ]); ++ v = evalRubyExpr(op === '+=' ? 'old + new' : 'old || new', vars); ++ } ++ if (isUnresolved(v)) { ++ v = new RubyUnresolved( ++ `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + ++ `(${(v /*: any */).why})`, + ); + } -+ return whole; -+ }, -+ ); ++ setLocal(name, v, stAct); ++ interpolate(st, false); ++ continue; ++ } ++ // `name.push(...)`, `name << x`; any other change to a local makes it ++ // unknown. ++ const change = core.match(/^([A-Za-z_]\w*)\s*(?:\.|\[|<<)/); ++ if (change != null && env.has(change[1]) && !recvs.has(change[1])) { ++ const name = change[1]; ++ const old = env.get(name); ++ const add = ++ core.match(/^\w+\s*\.(push|append|concat)\s*\(([\s\S]*)\)$/) ?? ++ core.match(/^\w+\s*\.(push|append|concat)\s+([\s\S]+)$/) ?? ++ core.match(/^\w+\s*(<<)\s*([\s\S]+)$/); ++ let v /*: mixed */ = new RubyUnresolved( ++ `is changed by \`${core}\`, which the reader cannot evaluate`, ++ ); ++ if (add != null && Array.isArray(old)) { ++ // `<<` adds one value; push/append/concat take a list. ++ const args = evalRubyExpr( ++ add[1] === '<<' ? `[(${add[2]})]` : `[${add[2]}]`, ++ env, ++ ); ++ if (Array.isArray(args)) { ++ if (add[1] !== 'concat') v = [...old, ...args]; ++ else if (args.every(Array.isArray)) v = [...old, ...args.flat()]; ++ } ++ } ++ setLocal(name, v, stAct); ++ continue; ++ } ++ interpolate(st, false); ++ } ++ return {text: out.join('\n'), unresolved}; +} + +// The library's own version. Podspecs load the package.json next to them @@ -164,13 +894,10 @@ index 8fcf04b..b3e3a53 100644 // Comment-only lines are dropped so a commented-out `# s.header_dir` cannot win // over the live one. A trailing `#` and a `#` inside a string survive: only the // first non-whitespace character counts. - function readPodspecSource(podspecPath /*: string */) /*: string */ { -- return fs -- .readFileSync(podspecPath, 'utf8') -- .split('\n') -- .filter(line => !/^\s*#/.test(line)) -- .join('\n'); -+ return resolveRubyConstants( ++function readPodspecEvaluated( ++ podspecPath /*: string */, ++) /*: {text: string, unresolved: Array} */ { ++ return evaluateRubyLocals( + resolvePackageVersion( + fs + .readFileSync(podspecPath, 'utf8') @@ -180,6 +907,14 @@ index 8fcf04b..b3e3a53 100644 + path.dirname(podspecPath), + ), + ); ++} + function readPodspecSource(podspecPath /*: string */) /*: string */ { +- return fs +- .readFileSync(podspecPath, 'utf8') +- .split('\n') +- .filter(line => !/^\s*#/.test(line)) +- .join('\n'); ++ return readPodspecEvaluated(podspecPath).text; +} + +// The main spec's block variable: `Pod::Spec.new do |podspec|` -> `podspec`. @@ -313,11 +1048,12 @@ index 8fcf04b..b3e3a53 100644 + * `opts.dropSubspecs` are left out, as if the podspec did not declare them. */ -function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +- const content = readPodspecSource(podspecPath); +function regexPodspec( + podspecPath /*: string */, + opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, +) /*: RawSpec */ { - const content = readPodspecSource(podspecPath); ++ const {text: content, unresolved} = readPodspecEvaluated(podspecPath); + const dropped = new Set(opts?.dropSubspecs ?? []); + const mainName = mainReceiverName(content); + const MAIN_RECV = mainRecvPattern(mainName); @@ -386,7 +1122,7 @@ index 8fcf04b..b3e3a53 100644 } // The fields that identify the spec, and only when the receiver spelling -@@ -235,9 +513,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -235,9 +1248,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: // s. = ["a", "b"] (array) // s. = "single" (single value treated as 1-element array) @@ -417,7 +1153,7 @@ index 8fcf04b..b3e3a53 100644 if (mArr != null) { const inner = mArr[1]; const out /*: Array */ = []; -@@ -249,16 +545,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -249,16 +1280,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { } return out; } @@ -460,7 +1196,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; out.push(m[1]); } -@@ -269,21 +586,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -269,21 +1321,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // s.framework "X" → ["X"] // s.framework = "X" → ["X"] // s.frameworks = ["X","Y"] → ["X","Y"] @@ -491,7 +1227,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; const itemRe = /["']([^"']+)["']/g; while (true) { -@@ -298,12 +619,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -298,12 +1354,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: 'HEADER_SEARCH_PATHS' => '...' or => ["...","..."] // Returns the raw token strings (still containing $(PODS_TARGET_SRCROOT) // etc.); substitution happens at translation time. @@ -508,7 +1244,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; const itemRe = /["']((?:[^"'\\]|\\.)+)["']/g; while (true) { -@@ -321,7 +644,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -321,7 +1379,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { const strRe = /["']HEADER_SEARCH_PATHS["']\s*=>\s*["']((?:[^"'\\]|\\.)+)["']/g; while (true) { @@ -517,7 +1253,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; for (const token of m[1].split(/\s+/)) { if (token.length > 0) { -@@ -332,15 +655,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -332,15 +1390,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { return Array.from(new Set(out)); } @@ -573,7 +1309,7 @@ index 8fcf04b..b3e3a53 100644 ); } if (/install_modules_dependencies/.test(content)) { -@@ -354,24 +715,100 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -354,26 +1450,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { ); } @@ -686,8 +1422,11 @@ index 8fcf04b..b3e3a53 100644 + ), __regex_partial__: true, __warnings__: warnings, ++ __unresolved__: unresolved, }; -@@ -423,6 +860,58 @@ function shellTokenize(value /*: string */) /*: Array */ { + } + +@@ -423,6 +1596,58 @@ function shellTokenize(value /*: string */) /*: Array */ { return tokens; } @@ -746,7 +1485,7 @@ index 8fcf04b..b3e3a53 100644 // --------------------------------------------------------------------------- // Subspec flattening // --------------------------------------------------------------------------- -@@ -438,8 +927,16 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -438,8 +1663,16 @@ function shellTokenize(value /*: string */) /*: Array */ { * - String fields → top-level wins; if absent, take the first subspec's value * - pod_target_xcconfig HEADER_SEARCH_PATHS → array-union across all selected subspecs * - dependencies → array-union of name strings (version constraints dropped) @@ -764,7 +1503,7 @@ index 8fcf04b..b3e3a53 100644 const warnings /*: Array */ = []; // $FlowFixMe[prop-missing] dynamic shape const partial /*: boolean */ = rawSpec.__regex_partial__ === true; -@@ -456,7 +953,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -456,7 +1689,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // - `default_subspecs`: array of names (or undefined → use all subspecs) const subspecs = Array.isArray(rawSpec.subspecs) ? rawSpec.subspecs : []; let selected = subspecs; @@ -778,7 +1517,7 @@ index 8fcf04b..b3e3a53 100644 const wanted = new Set(rawSpec.default_subspecs); selected = subspecs.filter(s => { // $FlowFixMe[prop-missing] dynamic shape -@@ -464,6 +966,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -464,6 +1702,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return name != null && wanted.has(name); }); } @@ -789,7 +1528,7 @@ index 8fcf04b..b3e3a53 100644 const layers = [rawSpec, ...selected]; function mergeArrayField(key /*: string */) /*: Array */ { -@@ -482,6 +988,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -482,6 +1724,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return Array.from(new Set(out)); } @@ -807,7 +1546,7 @@ index 8fcf04b..b3e3a53 100644 // Only the spec's own value: a subspec's `header_dir` names that subspec's // headers, and several subspecs can disagree. function specStringField(key /*: string */) /*: string | null */ { -@@ -544,6 +1061,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -544,6 +1797,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // `-D`s are safe to forward; arbitrary flags may be machine- or // example-app-specific. $(inherited), unresolved $(...) tokens, and invalid // C identifiers are skipped. @@ -828,7 +1567,7 @@ index 8fcf04b..b3e3a53 100644 function mergePreprocessorDefines() /*: Array */ { const out /*: Array */ = []; const seen /*: Set */ = new Set(); -@@ -554,7 +1085,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -554,7 +1821,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { config /*: ?('debug' | 'release') */, ) => { if (!validName.test(name)) return; @@ -853,7 +1592,7 @@ index 8fcf04b..b3e3a53 100644 return; // unresolved Xcode/Ruby token — don't emit a broken define } const key = `${name}|${config ?? ''}`; -@@ -571,6 +1118,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -571,6 +1854,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { 'xcconfig', 'user_target_xcconfig', ]; @@ -874,7 +1613,7 @@ index 8fcf04b..b3e3a53 100644 for (const layer of layers) { if (layer == null || typeof layer !== 'object') continue; for (const xcKey of XCCONFIG_KEYS) { -@@ -627,44 +1188,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -627,44 +1924,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return out; } @@ -1019,7 +1758,7 @@ index 8fcf04b..b3e3a53 100644 } } return out; -@@ -677,6 +1313,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -677,6 +2049,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { ? false : true; // RN ecosystem default @@ -1040,7 +1779,7 @@ index 8fcf04b..b3e3a53 100644 return { name: specStringField('name') ?? '', version: specStringField('version') ?? '', -@@ -693,15 +1343,42 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -693,23 +2079,81 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // header_mappings_dir copy step, which SPM has no equivalent for. headerMappingsDirs: mergeArrayField('header_mappings_dir'), headerDir: specStringField('header_dir'), @@ -1085,7 +1824,46 @@ index 8fcf04b..b3e3a53 100644 requiresArc, warnings, partial, -@@ -722,15 +1399,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { + // Default: overridden in readPodspec, which can see the podspec source. + usesInstallModulesDependencies: false, ++ // $FlowFixMe[incompatible-type] runtime-validated dynamic shape ++ unresolvedSources: Array.isArray(rawSpec.__unresolved__) ++ ? rawSpec.__unresolved__ ++ : [], + }; + } + ++/** ++ * Why the podspec's source globs cannot be scaffolded, or null: each ++ * `source_files`/`exclude_files` value the regex path could not evaluate. A ++ * glob read in part gives a target that builds without some of the library's ++ * files (react-native-screens 4.24.0 lost all of ios/, and the app crashed at ++ * start), so the scaffolder refuses the library instead. Other callers (name ++ * resolution, header search paths) keep reading the model as before. ++ */ ++function unresolvedSourcesReason( ++ podspecPath /*: string */, ++ model /*: PodspecModel */, ++) /*: ?string */ { ++ const list /*: Array */ = model.unresolvedSources ?? []; ++ if (list.length === 0) return null; ++ return ( ++ `${podspecPath}: ` + ++ list ++ .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) ++ .join('; ') + ++ '. The podspec reader evaluates locals, string interpolation, arrays, ' + ++ "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + ++ 'the globs it could read would leave some of the library\'s files out of ' + ++ 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + ++ 'reads the podspec, or give the library a Package.swift of its own.' ++ ); ++} ++ + // --------------------------------------------------------------------------- + // Top-level entry + // --------------------------------------------------------------------------- +@@ -722,15 +2166,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { * Throws when the file doesn't exist. Otherwise always returns a * PodspecModel — warnings on the model surface partial parses to the * caller, who can decide whether to proceed or abort scaffolding for that @@ -1108,7 +1886,7 @@ index 8fcf04b..b3e3a53 100644 // Record whether the podspec calls `install_modules_dependencies(s)`. We // strip that helper before `pod ipc` and the regex parser can't expand it, // so the React-Core family it injects never lands in `model.dependencies`. -@@ -746,21 +1426,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { +@@ -746,21 +2193,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { return model; } @@ -1159,7 +1937,7 @@ index 8fcf04b..b3e3a53 100644 podspecModels.set(key, model); return model; } -@@ -794,12 +1499,13 @@ function readPodspecNames( +@@ -794,12 +2266,13 @@ function readPodspecNames( if (hasShadowingSubspec(source)) { return null; } @@ -1174,11 +1952,30 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); +@@ -840,4 +2313,5 @@ module.exports = { + runPodIpcSpec, + regexPodspec, + flattenSubspecs, ++ unresolvedSourcesReason, + }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..a8076ae 100644 +index cf7e587..341c374 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -@@ -54,6 +54,7 @@ const { +@@ -45,7 +45,11 @@ const { + } = require('./expand-spm-dependencies'); + const {expandSpmSourceGlobs} = require('./generate-spm-autolinking'); + const {MIN_IOS_VERSION_SUPPORTED} = require('./ios-deployment-target'); +-const {findPodspecs, readPodspecCached} = require('./read-podspec'); ++const { ++ findPodspecs, ++ readPodspecCached, ++ unresolvedSourcesReason, ++} = require('./read-podspec'); + const { + REACT_CODEGEN_PACKAGE_NAME, + REACT_CODEGEN_PRODUCTS, +@@ -54,6 +58,7 @@ const { SCAFFOLDER_MARKER, makeLogger, remotePackageConfig, @@ -1186,7 +1983,7 @@ index cf7e587..a8076ae 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +114,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -1463,7 +2260,7 @@ index cf7e587..a8076ae 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +416,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +420,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1837,7 +2634,7 @@ index cf7e587..a8076ae 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +805,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +809,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1866,7 +2663,7 @@ index cf7e587..a8076ae 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +903,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +907,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1879,7 +2676,7 @@ index cf7e587..a8076ae 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +983,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +987,92 @@ function translatePodspecToSpmTarget( } } @@ -2000,7 +2797,7 @@ index cf7e587..a8076ae 100644 } } -@@ -427,15 +1134,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1138,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2058,7 +2855,7 @@ index cf7e587..a8076ae 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1244,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1248,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2110,7 +2907,7 @@ index cf7e587..a8076ae 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1310,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1314,101 @@ function translatePodspecToSpmTarget( ); } @@ -2212,7 +3009,7 @@ index cf7e587..a8076ae 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1413,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1417,201 @@ function translatePodspecToSpmTarget( } } @@ -2416,7 +3213,7 @@ index cf7e587..a8076ae 100644 warnings, }; } -@@ -565,6 +1632,9 @@ type EmitContext = { +@@ -565,6 +1636,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2426,7 +3223,7 @@ index cf7e587..a8076ae 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1699,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1703,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2453,7 +3250,7 @@ index cf7e587..a8076ae 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1808,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1812,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2486,7 +3283,7 @@ index cf7e587..a8076ae 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1851,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1855,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2498,7 +3295,7 @@ index cf7e587..a8076ae 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1871,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1875,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2572,7 +3369,7 @@ index cf7e587..a8076ae 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1946,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1950,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2581,7 +3378,7 @@ index cf7e587..a8076ae 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1956,13 @@ let package = Package( +@@ -778,13 +1960,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2598,7 +3395,7 @@ index cf7e587..a8076ae 100644 ) `; } -@@ -844,6 +2022,61 @@ function reportSwiftName( +@@ -844,6 +2026,61 @@ function reportSwiftName( } } @@ -2660,7 +3457,7 @@ index cf7e587..a8076ae 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2186,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2673,7 +3470,7 @@ index cf7e587..a8076ae 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2207,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2682,7 +3479,7 @@ index cf7e587..a8076ae 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2235,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2727,7 +3524,17 @@ index cf7e587..a8076ae 100644 } catch (e) { return { depName, -@@ -1012,35 +2284,17 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2284,27 @@ function scaffoldPackageSwiftForDep( + reason: `Podspec read failed: ${e.message}`, + }; + } ++ // A source glob the podspec reader could not evaluate: a target built from ++ // the rest would lack some of the library's files. ++ const unresolved = unresolvedSourcesReason(podspecPath, model); ++ if (unresolved != null) { ++ return {depName, status: 'error', reason: unresolved}; ++ } + const spec = translatePodspecToSpmTarget( model, dep, @@ -2772,7 +3579,7 @@ index cf7e587..a8076ae 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2326,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2336,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2780,7 +3587,7 @@ index cf7e587..a8076ae 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2336,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2346,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -2820,7 +3627,7 @@ index cf7e587..a8076ae 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2375,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2385,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2921,7 +3728,7 @@ index cf7e587..a8076ae 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2474,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2484,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -2934,7 +3741,7 @@ index cf7e587..a8076ae 100644 return { depName, -@@ -1128,6 +2488,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2498,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -2942,7 +3749,7 @@ index cf7e587..a8076ae 100644 }; } -@@ -1141,7 +2502,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2512,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2951,7 +3758,7 @@ index cf7e587..a8076ae 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2523,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2533,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2960,7 +3767,7 @@ index cf7e587..a8076ae 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2655,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2665,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2972,7 +3779,7 @@ index cf7e587..a8076ae 100644 }; */ -@@ -1323,6 +2689,17 @@ function scaffoldAll( +@@ -1323,6 +2699,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2990,7 +3797,7 @@ index cf7e587..a8076ae 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2707,23 @@ function scaffoldAll( +@@ -1330,24 +2717,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -3026,7 +3833,7 @@ index cf7e587..a8076ae 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2762,9 @@ function scaffoldAll( +@@ -1386,6 +2772,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3036,7 +3843,7 @@ index cf7e587..a8076ae 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2783,9 @@ function scaffoldAll( +@@ -1404,6 +2793,9 @@ function scaffoldAll( } module.exports = { @@ -3047,10 +3854,21 @@ index cf7e587..a8076ae 100644 scaffoldAll, scaffoldPackageSwiftForDep, diff --git a/node_modules/react-native/scripts/spm/spm-types.js b/node_modules/react-native/scripts/spm/spm-types.js -index a89142f..73dc6c8 100644 +index a89142f..6ce647d 100644 --- a/node_modules/react-native/scripts/spm/spm-types.js +++ b/node_modules/react-native/scripts/spm/spm-types.js -@@ -502,6 +502,9 @@ export type SpmScaffoldSpec = { +@@ -471,6 +471,10 @@ export type PodspecModel = { + // flag as an implicit React-core dependency (a plain ObjC module using the + // helper has no `codegenConfig` to key off). + usesInstallModulesDependencies: boolean, ++ // The `source_files`/`exclude_files` values the regex fallback could not ++ // evaluate (a method call, an unknown local): the scaffolder refuses the ++ // library rather than build it from a partial source list. ++ unresolvedSources?: Array<{field: string, expr: string, why: string}>, + }; + + // Intermediate translation result — concrete data the Swift emitter consumes. +@@ -502,6 +506,9 @@ export type SpmScaffoldSpec = { coreReactNative: boolean, siblingNames: Array, siblingSwiftNames?: {[npmName: string]: string}, @@ -3060,7 +3878,7 @@ index a89142f..73dc6c8 100644 // Extra frameworks beyond the autolinker's default UIKit/Foundation/CoreGraphics // set. Merged with the defaults at emit time. extraFrameworks: Array, -@@ -539,6 +542,9 @@ export type ScaffoldResult = +@@ -539,6 +546,9 @@ export type ScaffoldResult = // What became of `swiftpmConfig.name` in the library's package.json. // Absent when the name was not podspec-derived, so nothing was attempted. swiftpmName?: SwiftpmNameOutcome, diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index 700e77b..1d117a6 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1,5 +1,5 @@ diff --git a/node_modules/react-native/scripts/spm/read-podspec.js b/node_modules/react-native/scripts/spm/read-podspec.js -index 8fcf04b..b3e3a53 100644 +index 8fcf04b..6ed3f14 100644 --- a/node_modules/react-native/scripts/spm/read-podspec.js +++ b/node_modules/react-native/scripts/spm/read-podspec.js @@ -102,13 +102,12 @@ function runPodIpcSpec(podspecPath /*: string */) /*: RawSpec | null */ { @@ -22,106 +22,836 @@ index 8fcf04b..b3e3a53 100644 }); } catch { cleanupPatchedPodspec(patchedPath); -@@ -170,58 +169,337 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { +@@ -170,58 +169,1072 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { // Regex fallback // --------------------------------------------------------------------------- -+// Ruby constants. Podspecs commonly hoist a glob or extension list into a local -+// and reuse it (react-native-screens: `source_files_exts = '{h,m,mm,cpp}'`, -+// `source_files = ["ios/**/*.#{source_files_exts}"]`, `s.source_files = -+// source_files`). The field regexes below only understand literals, so such a -+// field read as missing and the library scaffolded with no sources. ++// Ruby locals and conditions. Podspecs hoist globs, extension lists and flags ++// into locals and set them under conditions; react-native-screens 4.24.0: +// -+// This pre-pass resolves the simple cases textually, so the regexes stay -+// untouched: single-line `ident = 'str' | "str" | ["a", "b"]` assignments are -+// collected (first assignment wins; `if`/`ENV[...]` conditions are NOT -+// evaluated, except the one kind below), then `#{ident}` inside the text is replaced by a known string -+// constant, and a field assigned a bare known identifier (`s.x = ident`) is -+// rewritten to the literal value (`s.x = ident`, `s.ios.x = ident`, and a -+// subspec's `ss.x = ident`). `#{}` is only interpolated inside double-quoted -+// strings, as in Ruby. Unknown interpolations/identifiers are left as they are. ++// new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1' ++// source_files_exts = ++// new_arch_enabled ? '{h,m,mm,cpp,swift}' : '{h,m,mm,swift}' ++// source_files = ["ios/**/*.#{source_files_exts}"] ++// if !new_arch_enabled ++// source_files.push("cpp/RNScreensTurboModule.cpp", ...) ++// end ++// ... ++// s.source_files = source_files ++// if !gamma_project_enabled ++// s.exclude_files = "ios/gamma/**/*.#{source_files_exts}" ++// else ... +// -+// One kind of condition is evaluated: a string ternary on an environment -+// variable React Native's CocoaPods setup itself sets for every pod -+// (`ident = ENV['VAR'] == 'v' ? 'a' : 'b'`, also `!=`), with the value that -+// setup gives it: `1` for both. The environment is not read. React Native -+// 0.87+ sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, -+// so a `0` left in the shell could only break the build (and a persisted -+// scaffold). react-native-worklets puts -+// `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == '1' ? '-DHERMES_V1_ENABLED' -+// : ''` in OTHER_CFLAGS; without the define it includes the legacy Hermes -+// inspector headers, which the prebuilt artifacts do not ship. ++// The field regexes below only understand literals, so this pre-pass runs the ++// podspec's statements in order over a small, side-effect-free subset of Ruby ++// and leaves the regexes a flat text: ++// ++// - values: string literals (single quotes verbatim, double quotes with ++// `#{expr}` interpolation), `%w[...]`, array literals, numbers, `true`, ++// `false`, `nil`, and locals (`name = expr`, also `+=` and `||=`; the last ++// assignment that runs wins, as in Ruby); ++// - `ENV['X']` and `ENV.fetch('X', default)`: `RCT_NEW_ARCH_ENABLED` and ++// `RCT_HERMES_V1_ENABLED` are `1` (below), every other variable is unset. ++// The environment is never read, so a scaffold does not depend on the shell; ++// - `==`, `!=`, `!`/`not`, `&&`/`and`, `||`/`or`, `+` on strings and arrays, ++// `a ? b : c`, `array.join(sep)`, `.to_s`, `.freeze`; ++// - `if`/`elsif`/`else`/`unless`/`end` blocks and `stmt if cond` / `stmt ++// unless cond` modifiers, at the top level and inside the spec and subspec ++// blocks: a branch that does not run is blanked, the control lines of a ++// condition that was evaluated are dropped; ++// - `local.push(...)`, `local.append(...)`, `local.concat(...)`, `local << x`; ++// - `recv. = expr` on the spec or a subspec (`s.`, `s.ios.`, `ss.`): ++// a value that is not already a literal is rewritten to the literal it ++// evaluates to. Inside a hash (`pod_target_xcconfig`, `resource_bundles`), ++// `=> local` is replaced by the local's value. ++// ++// Anything else (method calls, hashes, symbols, `$config[...]`, blocks other ++// than the spec's, conditions on any of these) is not evaluated: the text ++// stays as written, and a local assigned from it, or under such a condition, is ++// unknown from there on. Both branches of such a condition stay visible, as ++// before (react-native-vision-camera's `if enableFrameProcessors` subspec). A ++// `source_files` or `exclude_files` value that uses something unknown is ++// returned in `unresolved`, and the scaffolder refuses the library ++// (unresolvedSourcesReason): a glob read in part gives a target that builds ++// and lacks the library's classes, so the app crashes at start ++// (react-native-screens 4.24.0 lost all of ios/). ++// ++// `RCT_NEW_ARCH_ENABLED` and `RCT_HERMES_V1_ENABLED` get the value React ++// Native's CocoaPods setup gives every pod, `1` for both. React Native 0.87+ ++// sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, so a ++// `0` left in the shell could only break the build (and a persisted scaffold). ++// react-native-worklets puts `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == ++// '1' ? '-DHERMES_V1_ENABLED' : ''` in OTHER_CFLAGS; without the define it ++// includes the legacy Hermes inspector headers, which the prebuilt artifacts ++// do not ship. +const RN_POD_ENV /*: {[string]: string} */ = { + RCT_NEW_ARCH_ENABLED: '1', + RCT_HERMES_V1_ENABLED: '1', +}; -+function rnPodEnvTernary(rhs /*: string */) /*: ?string */ { -+ const m = rhs.match( -+ /^ENV\[\s*(["'])([A-Z0-9_]+)\1\s*\]\s*(==|!=)\s*(["'])([^"']*)\4\s*\?\s*(?:"([^"]*)"|'([^']*)')\s*:\s*(?:"([^"]*)"|'([^']*)')$/, ++ ++// A value the evaluator could not compute, and why. ++class RubyUnresolved { ++ /*:: why: string; */ ++ constructor(why /*: string */) { ++ this.why = why; ++ } ++} ++const isUnresolved = (v /*: mixed */) /*: boolean */ => ++ v instanceof RubyUnresolved; ++ ++// The source-glob fields an unevaluated expression must not reach silently. ++const STRICT_FIELDS /*: Set */ = new Set([ ++ 'source_files', ++ 'exclude_files', ++]); ++const PLATFORM_SCOPES /*: Set */ = new Set([ ++ 'ios', ++ 'osx', ++ 'macos', ++ 'tvos', ++ 'visionos', ++ 'watchos', ++]); ++ ++// Tokens of one Ruby expression. A double-quoted string keeps its parts: ++// literal text and the source of each `#{...}`. ++function tokenizeRubyExpr(src /*: string */) /*: Array */ { ++ const tokens = []; ++ let i = 0; ++ // The end of a `#{...}` starting at `from` (just past `#{`), or -1. ++ const interpEnd = (from /*: number */) => { ++ let depth = 1; ++ let quote = ''; ++ for (let j = from; j < src.length; j++) { ++ const c = src[j]; ++ if (quote !== '') { ++ if (c === '\\') j++; ++ else if (c === quote) quote = ''; ++ } else if (c === '"' || c === "'") quote = c; ++ else if (c === '{') depth++; ++ else if (c === '}' && --depth === 0) return j; ++ } ++ return -1; ++ }; ++ const CLOSE = {'[': ']', '(': ')', '{': '}', '<': '>'}; ++ while (i < src.length) { ++ const c = src[i]; ++ if (/\s/.test(c)) { ++ i++; ++ } else if (c === "'") { ++ let v = ''; ++ let j = i + 1; ++ for (; j < src.length && src[j] !== "'"; j++) { ++ if (src[j] === '\\' && (src[j + 1] === "'" || src[j + 1] === '\\')) { ++ v += src[++j]; ++ } else v += src[j]; ++ } ++ if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; ++ tokens.push({t: 'str', parts: [v]}); ++ i = j + 1; ++ } else if (c === '"') { ++ const parts = []; ++ let v = ''; ++ let j = i + 1; ++ for (; j < src.length && src[j] !== '"'; j++) { ++ if (src[j] === '\\') { ++ const e = src[++j]; ++ v += e === 'n' ? '\n' : e === 't' ? '\t' : e; ++ } else if (src[j] === '#' && src[j + 1] === '{') { ++ const end = interpEnd(j + 2); ++ if (end < 0) return [{t: 'bad', v: src.slice(i)}]; ++ parts.push(v, {expr: src.slice(j + 2, end)}); ++ v = ''; ++ j = end; ++ } else v += src[j]; ++ } ++ if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; ++ parts.push(v); ++ tokens.push({t: 'str', parts}); ++ i = j + 1; ++ } else if (c === '%' && /^%w[[({<]/.test(src.slice(i, i + 3))) { ++ const close = CLOSE[src[i + 2]]; ++ const end = src.indexOf(close, i + 3); ++ if (end < 0) return [{t: 'bad', v: src.slice(i)}]; ++ tokens.push({ ++ t: 'words', ++ v: src ++ .slice(i + 3, end) ++ .split(/\s+/) ++ .filter(Boolean), ++ }); ++ i = end + 1; ++ } else if (/[0-9]/.test(c)) { ++ const m = src.slice(i).match(/^[0-9][0-9_.]*/); ++ const text = m != null ? m[0] : c; ++ tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); ++ i += text.length; ++ } else if (/[A-Za-z_]/.test(c)) { ++ const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); ++ const text = m != null ? m[0] : c; ++ tokens.push({t: 'id', v: text}); ++ i += text.length; ++ } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { ++ tokens.push({t: 'bad', v: src.slice(i)}); // a symbol ++ i = src.length; ++ } else { ++ const two = src.slice(i, i + 2); ++ if (['==', '!=', '&&', '||', '=>', '::', '<<', '=~'].includes(two)) { ++ tokens.push({t: 'op', v: two}); ++ i += 2; ++ } else { ++ tokens.push({t: 'op', v: c}); ++ i++; ++ } ++ } ++ } ++ return tokens; ++} ++ ++const rubyTruthy = (v /*: mixed */) /*: boolean */ => v !== false && v != null; ++ ++function rubyEqual(a /*: mixed */, b /*: mixed */) /*: boolean */ { ++ if (Array.isArray(a) && Array.isArray(b)) { ++ return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); ++ } ++ return a === b; ++} ++ ++// `#{v}`: Ruby's to_s for the values the evaluator knows. ++function rubyToS(v /*: mixed */) /*: string | RubyUnresolved */ { ++ if (typeof v === 'string') return v; ++ if (v == null) return ''; ++ if (typeof v === 'boolean' || typeof v === 'number') return String(v); ++ return new RubyUnresolved('an array or hash inside `#{...}`'); ++} ++ ++/** ++ * Evaluates one Ruby expression with the locals in `env`. Returns the value, ++ * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list ++ * (`s.x = "a", "b"`) as an array. Never runs anything. ++ */ ++function evalRubyExpr( ++ src /*: string */, ++ env /*: Map */, ++ list /*:: ?: boolean */, ++) /*: mixed */ { ++ const tokens = tokenizeRubyExpr(src); ++ let pos = 0; ++ const peek = (v /*: string */) => ++ tokens[pos] != null && ++ (tokens[pos].t === 'op' || tokens[pos].t === 'id') && ++ tokens[pos].v === v; ++ const take = (v /*: string */) => { ++ if (!peek(v)) return false; ++ pos++; ++ return true; ++ }; ++ const fail = (why /*: string */) => new RubyUnresolved(why); ++ // Skips a balanced (...) / [...] / {...} group starting at `pos`. ++ const skipGroup = () => { ++ let depth = 0; ++ do { ++ const tk = tokens[pos++]; ++ if (tk == null) return; ++ if (tk.t === 'op' && '([{'.includes(tk.v)) depth++; ++ if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; ++ } while (depth > 0); ++ }; ++ // Comma-separated expressions up to `close` (already past the opener). ++ const parseItems = (close /*: string */) => { ++ const items = []; ++ while (!peek(close)) { ++ if (tokens[pos] == null) return fail(`a missing \`${close}\``); ++ items.push(parseTernary()); ++ if (!take(',')) break; ++ } ++ if (!take(close)) return fail(`a missing \`${close}\``); ++ return items.find(isUnresolved) ?? items; ++ }; ++ function parsePrimary() /*: mixed */ { ++ const tk = tokens[pos++]; ++ if (tk == null) return fail('an incomplete expression'); ++ if (tk.t === 'str') { ++ let out = ''; ++ for (const part of tk.parts) { ++ if (typeof part === 'string') { ++ out += part; ++ continue; ++ } ++ const inner = evalRubyExpr(part.expr, env); ++ if (isUnresolved(inner)) return inner; ++ const s = rubyToS(inner); ++ if (isUnresolved(s)) return s; ++ out += (s /*: any */); ++ } ++ return out; ++ } ++ if (tk.t === 'words') return tk.v; ++ if (tk.t === 'num') return tk.v; ++ if (tk.t === 'bad') return fail(`\`${tk.v}\``); ++ if (tk.t === 'op') { ++ if (tk.v === '(') { ++ const v = parseTernary(); ++ return take(')') ? v : fail('a missing `)`'); ++ } ++ if (tk.v === '[') return parseItems(']'); ++ if (tk.v === '{') return fail('a hash'); ++ return fail(`\`${tk.v}\``); ++ } ++ // An identifier. ++ const name = tk.v; ++ if (name === 'true') return true; ++ if (name === 'false') return false; ++ if (name === 'nil') return null; ++ if (name === 'ENV') { ++ if (take('[')) { ++ const key = parseTernary(); ++ if (!take(']')) return fail('a missing `]`'); ++ if (isUnresolved(key)) return key; ++ return typeof key === 'string' && Object.hasOwn(RN_POD_ENV, key) ++ ? RN_POD_ENV[key] ++ : null; ++ } ++ if (take('.') && take('fetch') && take('(')) { ++ const args = parseItems(')'); ++ if (isUnresolved(args)) return args; ++ const [key, fallback] = (args /*: any */); ++ if (typeof key !== 'string') return fail('`ENV.fetch` of a non-string'); ++ return Object.hasOwn(RN_POD_ENV, key) ? RN_POD_ENV[key] : fallback; ++ } ++ return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); ++ } ++ if (peek('(')) { ++ skipGroup(); ++ return fail(`the method call \`${name}(...)\``); ++ } ++ if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); ++ const v = env.get(name); ++ if (isUnresolved(v)) { ++ return fail(`\`${name}\`, which ${(v /*: any */).why}`); ++ } ++ return v; ++ } ++ function parsePostfix() /*: mixed */ { ++ let v = parsePrimary(); ++ while (peek('.') || peek('[')) { ++ if (take('[')) { ++ pos--; ++ skipGroup(); ++ v = isUnresolved(v) ? v : fail('an index `[...]`'); ++ continue; ++ } ++ take('.'); ++ const m = tokens[pos++]; ++ const method = m != null && m.t === 'id' ? m.v : '?'; ++ let args = []; ++ if (peek('(')) { ++ pos++; ++ const got = parseItems(')'); ++ if (isUnresolved(got)) { ++ v = isUnresolved(v) ? v : got; ++ continue; ++ } ++ args = (got /*: any */); ++ } ++ if (isUnresolved(v)) continue; ++ if ((method === 'freeze' || method === 'to_s') && typeof v === 'string') { ++ continue; ++ } ++ if (method === 'join' && Array.isArray(v)) { ++ const sep = args.length > 0 ? args[0] : ''; ++ const parts = v.flat(Infinity).map(rubyToS); ++ const bad = parts.find(isUnresolved); ++ v = ++ bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); ++ continue; ++ } ++ v = fail(`the method call \`.${method}\``); ++ } ++ return v; ++ } ++ function parseUnary() /*: mixed */ { ++ if (take('!')) { ++ const v = parseUnary(); ++ return isUnresolved(v) ? v : !rubyTruthy(v); ++ } ++ return parsePostfix(); ++ } ++ function parseAdd() /*: mixed */ { ++ let l = parseUnary(); ++ while (take('+')) { ++ const r = parseUnary(); ++ if (isUnresolved(l)) continue; ++ if (isUnresolved(r)) l = r; ++ else if (typeof l === 'string' && typeof r === 'string') l = l + r; ++ else if (Array.isArray(l) && Array.isArray(r)) l = [...l, ...r]; ++ else l = fail('`+` on values other than two strings or two arrays'); ++ } ++ return l; ++ } ++ function parseEq() /*: mixed */ { ++ const l = parseAdd(); ++ if (peek('==') || peek('!=')) { ++ const op = tokens[pos++].v; ++ const r = parseAdd(); ++ if (isUnresolved(l)) return l; ++ if (isUnresolved(r)) return r; ++ return op === '==' ? rubyEqual(l, r) : !rubyEqual(l, r); ++ } ++ if (peek('=~') || peek('<') || peek('>')) { ++ return fail(`the operator \`${tokens[pos].v}\``); ++ } ++ return l; ++ } ++ function parseNot() /*: mixed */ { ++ if (take('not')) { ++ const v = parseNot(); ++ return isUnresolved(v) ? v : !rubyTruthy(v); ++ } ++ return parseEq(); ++ } ++ function parseAnd() /*: mixed */ { ++ let l = parseNot(); ++ while (take('&&') || take('and')) { ++ const r = parseNot(); ++ if (!isUnresolved(l) && rubyTruthy(l)) l = r; ++ } ++ return l; ++ } ++ function parseOr() /*: mixed */ { ++ let l = parseAnd(); ++ while (take('||') || take('or')) { ++ const r = parseAnd(); ++ if (!isUnresolved(l) && !rubyTruthy(l)) l = r; ++ } ++ return l; ++ } ++ function parseTernary() /*: mixed */ { ++ const c = parseOr(); ++ if (!take('?')) return c; ++ const a = parseTernary(); ++ if (!take(':')) return fail('a ternary without `:`'); ++ const b = parseTernary(); ++ if (isUnresolved(c)) return c; ++ return rubyTruthy(c) ? a : b; ++ } ++ let value = parseTernary(); ++ if (list === true && peek(',')) { ++ const items = [value]; ++ while (take(',')) items.push(parseTernary()); ++ value = items.find(isUnresolved) ?? items; ++ } ++ if (pos < tokens.length && !isUnresolved(value)) { ++ const rest = tokens[pos]; ++ return fail( ++ rest.t === 'op' || rest.t === 'id' ++ ? `\`${rest.v}\` where it ends` ++ : 'more than one expression', ++ ); ++ } ++ return value; ++} ++ ++// A literal the field regexes read as written: quoted strings without ++// `#{...}`, as one value, an array or a bare list. ++function isPlainLiteral(rhs /*: string */) /*: boolean */ { ++ const str = `(?:"[^"\\\\#]*"|'[^'\\\\]*')`; ++ const list = `${str}(?:\\s*,\\s*${str})*`; ++ return new RegExp( ++ `^(?:${list}|\\[\\s*(?:${list}\\s*,?)?\\s*\\]|true|false)$`, ++ ).test(rhs.trim()); ++} ++ ++// The literal a field is rewritten to, or null when the value has none. ++function rubyLiteral(v /*: mixed */) /*: ?string */ { ++ if (typeof v === 'string') return JSON.stringify(v); ++ if (typeof v === 'boolean') return String(v); ++ if (Array.isArray(v)) { ++ const flat = v.flat(Infinity); ++ if (!flat.every(x => typeof x === 'string')) return null; ++ return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; ++ } ++ return null; ++} ++ ++// The podspec's logical statements: lines joined while a bracket or string is ++// open or the line ends in `,`, `\`, an operator or `=`. A heredoc's body ++// belongs to the statement that opens it. `code` is the statement without ++// trailing comments. ++function rubyStatements( ++ lines /*: Array */, ++) /*: Array<{start: number, end: number, code: string}> */ { ++ const out = []; ++ const scan = ( ++ line /*: string */, ++ state /*: {depth: number, quote: string} */, ++ ) => { ++ let code = ''; ++ for (let i = 0; i < line.length; i++) { ++ const c = line[i]; ++ if (state.quote !== '') { ++ code += c; ++ if (c === '\\') code += line[++i] ?? ''; ++ else if (c === state.quote) state.quote = ''; ++ continue; ++ } ++ if (c === '#') break; ++ code += c; ++ if (c === '"' || c === "'") state.quote = c; ++ else if ('([{'.includes(c)) state.depth++; ++ else if (')]}'.includes(c)) state.depth--; ++ } ++ return code; ++ }; ++ let i = 0; ++ while (i < lines.length) { ++ const start = i; ++ const state = {depth: 0, quote: ''}; ++ const codes = []; ++ let heredoc = null; ++ while (i < lines.length) { ++ const code = scan(lines[i], state); ++ codes.push(code); ++ i++; ++ const h = code.match(/<<([-~]?)(["']?)([A-Za-z_]\w*)\2\s*$/); ++ if (h != null && state.quote === '') { ++ heredoc = {indented: h[1] !== '', id: h[3]}; ++ break; ++ } ++ const open = ++ state.depth > 0 || ++ state.quote !== '' || ++ /(?:,|\\|&&|\|\||[^=!<>]=|\+|\s\?|\s:)\s*$/.test(code); ++ if (!open) break; ++ } ++ if (i >= lines.length && (state.depth > 0 || state.quote !== '')) { ++ // Never closed: read the first line alone and go on from the next. ++ const code = scan(lines[start], {depth: 0, quote: ''}); ++ out.push({start, end: start, code}); ++ i = start + 1; ++ continue; ++ } ++ if (heredoc != null) { ++ const {indented, id} = heredoc; ++ while (i < lines.length) { ++ const l = lines[i++]; ++ if ((indented ? l.trim() : l) === id) break; ++ } ++ } ++ out.push({start, end: i - 1, code: codes.join('\n')}); ++ } ++ return out; ++} ++ ++// The index of a trailing `if`/`unless` modifier outside strings and brackets. ++function modifierIndex(code /*: string */) /*: ?{at: number, kw: string} */ { ++ let quote = ''; ++ let depth = 0; ++ for (let i = 1; i < code.length; i++) { ++ const c = code[i]; ++ if (quote !== '') { ++ if (c === '\\') i++; ++ else if (c === quote) quote = ''; ++ continue; ++ } ++ if (c === '"' || c === "'") quote = c; ++ else if ('([{'.includes(c)) depth++; ++ else if (')]}'.includes(c)) depth--; ++ else if (depth === 0 && /\s/.test(code[i - 1])) { ++ const m = code.slice(i).match(/^(if|unless)\s/); ++ if (m != null) return {at: i, kw: m[1]}; ++ } ++ } ++ return null; ++} ++ ++/*:: ++type Unresolved = {field: string, expr: string, why: string}; ++type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; ++*/ ++ ++// Why a local set under `act` is unknown from there on. ++function unknownUnder(act /*: Activity */) /*: RubyUnresolved */ { ++ return new RubyUnresolved( ++ act.state === 'maybe' ++ ? `is set under \`${act.why}\`, a condition the reader cannot evaluate` ++ : `is set inside \`${act.why}\`, a block the reader does not run`, + ); -+ if (m == null || !Object.hasOwn(RN_POD_ENV, m[2])) return null; -+ const value = RN_POD_ENV[m[2]]; -+ const holds = m[3] === '==' ? value === m[5] : value !== m[5]; -+ return holds ? m[6] ?? m[7] : m[8] ?? m[9]; +} -+function resolveRubyConstants(content /*: string */) /*: string */ { -+ const strings /*: Map */ = new Map(); -+ const arrays /*: Map> */ = -+ new Map(); -+ const assignRe = /^[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*(.+?)[ \t]*$/gm; -+ for (const m of content.matchAll(assignRe)) { -+ const name = m[1]; -+ if (strings.has(name) || arrays.has(name)) continue; -+ const rhs = m[2]; -+ const str = rhs.match(/^(?:"([^"]*)"|'([^']*)')$/); -+ if (str != null) { -+ strings.set(name, str[1] ?? str[2]); ++ ++// The branch an `elsif` opens, and what is known of the branches before it. ++function elsifBranch( ++ prior /*: string */, ++ cond /*: string */, ++) /*: {branch: string, prior: string} */ { ++ if (prior === 'yes') return {branch: 'no', prior: 'yes'}; ++ if (prior === 'no') return {branch: cond, prior: cond}; ++ // An earlier branch may have run. ++ return { ++ branch: cond === 'no' ? 'no' : 'maybe', ++ prior: cond === 'yes' ? 'yes' : 'maybe', ++ }; ++} ++ ++/** ++ * Runs the podspec's statements over the subset above. Returns the rewritten ++ * text (same line count) and each `source_files`/`exclude_files` assignment ++ * whose value could not be evaluated. ++ */ ++function evaluateRubyLocals( ++ content /*: string */, ++) /*: {text: string, unresolved: Array} */ { ++ const lines = content.split('\n'); ++ const out = lines.slice(); ++ const env /*: Map */ = new Map(); ++ const recvs /*: Set */ = new Set(); ++ const unresolved /*: Array */ = []; ++ // `if` blocks (which branch is being read) and other blocks. ++ const frames /*: Array */ = []; ++ const blank = (st /*: {start: number, end: number} */) => { ++ for (let k = st.start; k <= st.end; k++) out[k] = ''; ++ }; ++ // Whether the statement being read runs: 'yes', 'no', 'maybe' (under a ++ // condition it cannot evaluate) or 'opaque' (in a block it does not run), ++ // with the condition or block that decides. ++ const activity = () /*: Activity */ => { ++ let act /*: Activity */ = {state: 'yes', why: ''}; ++ for (const f of frames) { ++ const s = f.kind === 'if' ? f.branch : f.opaque ? 'opaque' : 'yes'; ++ if (s === 'no') return {state: 'no', why: ''}; ++ if (s !== 'yes' && act.state === 'yes') { ++ act = {state: s, why: f.kind === 'if' ? f.cond : f.code}; ++ } ++ } ++ return act; ++ }; ++ const condOf = (src /*: string */, negate /*: boolean */) => { ++ const v = evalRubyExpr(src, env); ++ if (isUnresolved(v)) return 'maybe'; ++ return rubyTruthy(v) !== negate ? 'yes' : 'no'; ++ }; ++ // Lines that stay as written: `#{local}` (a known string) in their ++ // double-quoted literals, and `=> local` inside a hash, get the value. ++ const interpolate = ( ++ st /*: {start: number, end: number} */, ++ hash /*: boolean */, ++ ) => { ++ const known = (id /*: string */) => { ++ const v = env.get(id); ++ return typeof v === 'string' ? v : null; ++ }; ++ for (let k = st.start; k <= st.end; k++) { ++ out[k] = out[k].replace( ++ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, ++ lit => ++ lit[0] === '"' ++ ? lit.replace( ++ /#\{\s*([A-Za-z_]\w*)\s*\}/g, ++ (whole, id) => known(id) ?? whole, ++ ) ++ : lit, ++ ); ++ if (hash) { ++ out[k] = out[k].replace( ++ /(=>\s*)([A-Za-z_]\w*)(?=\s*(?:,|\}|$))/g, ++ (whole, arrow, id) => { ++ const lit = env.has(id) ? rubyLiteral(env.get(id)) : null; ++ return lit != null ? arrow + lit : whole; ++ }, ++ ); ++ } ++ } ++ }; ++ const setLocal = ( ++ name /*: string */, ++ value /*: mixed */, ++ act /*: Activity */, ++ ) => { ++ env.set(name, act.state === 'yes' ? value : unknownUnder(act)); ++ }; ++ ++ for (const st of rubyStatements(lines)) { ++ const code = st.code.trim(); ++ if (code === '') continue; ++ const act = activity(); ++ const oneLine = /[\s;]end\s*;?$/.test(code); ++ const top = frames[frames.length - 1]; ++ let m; ++ m = oneLine ? null : code.match(/^(if|unless)\s+([\s\S]+?)(?:\s+then)?$/); ++ if (m != null) { ++ // Under a branch that does not run, every branch is dead. ++ const branch = ++ act.state === 'no' || act.state === 'opaque' ++ ? act.state ++ : condOf(m[2], m[1] === 'unless'); ++ frames.push({ ++ kind: 'if', ++ branch, ++ prior: act.state === 'no' ? 'yes' : branch, ++ cond: m[2], ++ evaluated: branch !== 'maybe' && branch !== 'opaque', ++ ctrl: [st], ++ }); + continue; + } -+ const fromEnv = rnPodEnvTernary(rhs); -+ if (fromEnv != null) { -+ strings.set(name, fromEnv); ++ if (top?.kind === 'if') { ++ if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { ++ top.ctrl.push(st); ++ if (top.branch === 'opaque') continue; ++ const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); ++ if (cond === 'maybe') top.evaluated = false; ++ Object.assign(top, elsifBranch(top.prior, cond), {cond: m[1]}); ++ continue; ++ } ++ if (code === 'else') { ++ top.ctrl.push(st); ++ if (top.branch !== 'opaque') { ++ top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; ++ } ++ continue; ++ } ++ } ++ if (/^end\b/.test(code) && top != null) { ++ frames.pop(); ++ // An evaluated condition leaves no control lines behind. ++ if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { ++ for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); ++ blank(st); ++ } + continue; + } -+ const arr = rhs.match(/^\[([^\]]*)\]$/); -+ if (arr != null) { -+ const items = []; -+ for (const it of arr[1].matchAll(/"([^"]*)"|'([^']*)'/g)) { -+ items.push({value: it[1] ?? it[2], dq: it[1] != null}); ++ const opensBlock = ++ !oneLine && ++ (/^(?:case|begin|while|until|for|def|class|module)\b/.test(code) || ++ /\bdo(?:\s*\|[^|]*\|)?\s*$/.test(code) || ++ /=\s*(?:if|unless|case|begin)\b/.test(code)); ++ if (opensBlock) { ++ // The spec's and its subspecs' blocks run; any other is opaque. ++ const spec = code.match(/Pod::Spec\.new\s+do\s*\|\s*(\w+)\s*\|\s*$/); ++ const sub = code.match( ++ /^(\w+)\.subspec\s[\s\S]*\bdo\s*\|\s*(\w+)\s*\|\s*$/, ++ ); ++ const recv = ++ spec?.[1] ?? (sub != null && recvs.has(sub[1]) ? sub[2] : null); ++ if (recv != null) recvs.add(recv); ++ const assigned = code.match(/^([A-Za-z_]\w*)\s*=/); ++ if (assigned != null) { ++ setLocal(assigned[1], null, {state: 'opaque', why: code}); + } -+ arrays.set(name, items); ++ frames.push({kind: 'block', opaque: recv == null, code}); ++ if (act.state === 'no') blank(st); ++ continue; + } -+ } -+ if (strings.size === 0 && arrays.size === 0) return content; -+ const interpolate = (text /*: string */) => -+ text.replace(/#\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g, (whole, id) => -+ strings.has(id) ? (strings.get(id) /*: any */) : whole, ++ if (act.state === 'no') { ++ blank(st); ++ continue; ++ } ++ // A trailing `if`/`unless` modifier. ++ let core = code; ++ let stAct = act; ++ const mod = modifierIndex(code); ++ if (mod != null) { ++ core = code.slice(0, mod.at).trim(); ++ const cond = code.slice(mod.at + mod.kw.length).trim(); ++ const c = ++ act.state === 'yes' ? condOf(cond, mod.kw === 'unless') : act.state; ++ if (c === 'no') { ++ blank(st); ++ continue; ++ } ++ if (c === 'maybe' && act.state === 'yes') { ++ stAct = {state: 'maybe', why: cond}; ++ } ++ } ++ // `recv.field = expr` on the spec or a subspec. Under a condition it ++ // cannot evaluate, or in a block it does not run, it is read as if it ran, ++ // as the field regexes always did: a literal stays as written, an ++ // expression is evaluated or, in a source glob, refused. ++ const field = core.match( ++ /^([A-Za-z_]\w*)(?:\.([a-z]+))?\.([a-z_]+)\s*=(?![=~>])\s*([\s\S]+)$/, + ); -+ // Constants may be built from earlier ones: resolve the arrays' items too -+ // (double-quoted items only). -+ const arrayValues /*: Map> */ = new Map(); -+ for (const [k, v] of arrays) { -+ arrayValues.set(k, v.map(i => (i.dq ? interpolate(i.value) : i.value))); -+ } -+ // Only double-quoted string literals interpolate; scan literal by literal -+ // (a line never spans a string here) so `'ios/*.#{x}'` stays as written. -+ const interpolated = content.replace( -+ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, -+ lit => (lit[0] === '"' ? interpolate(lit) : lit), -+ ); -+ const quote = (v /*: string */) => JSON.stringify(v); -+ return interpolated.replace( -+ /^(\s*[A-Za-z_]\w*(?:\.(?:ios|osx|tvos|visionos|watchos))?\.[A-Za-z_]+\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)[ \t]*$/gm, -+ (whole, lhs, id) => { -+ if (strings.has(id)) return lhs + quote((strings.get(id) /*: any */)); -+ if (arrayValues.has(id)) { -+ return ( -+ lhs + '[' + (arrayValues.get(id) /*: any */).map(quote).join(', ') + ']' ++ if ( ++ field != null && ++ recvs.has(field[1]) && ++ (field[2] == null || PLATFORM_SCOPES.has(field[2])) ++ ) { ++ const [, recv, scope, name, rhs] = field; ++ // Only the spec's own and its `ios` scope count. ++ if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; ++ const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; ++ const v = evalRubyExpr(rhs, env, true); ++ const lit = isUnresolved(v) ? null : rubyLiteral(v); ++ if (lit != null) { ++ blank(st); ++ const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; ++ out[st.start] = `${indent}${lhs} = ${lit}`; ++ } else if (STRICT_FIELDS.has(name)) { ++ unresolved.push({ ++ field: lhs, ++ expr: rhs.trim(), ++ why: isUnresolved(v) ++ ? `it uses ${(v /*: any */).why}` ++ : 'its value is not a string or an array of strings', ++ }); ++ } else { ++ interpolate(st, /^\{/.test(rhs.trim())); ++ } ++ continue; ++ } ++ // `name = expr`, `name += expr`, `name ||= expr`. ++ const assign = core.match( ++ /^([A-Za-z_]\w*)\s*(\+=|\|\|=|=)(?![=~>])\s*([\s\S]+)$/, ++ ); ++ if (assign != null && !recvs.has(assign[1])) { ++ const [, name, op, rhs] = assign; ++ let v = evalRubyExpr(rhs, env); ++ if (op !== '=' && !isUnresolved(v)) { ++ const vars = new Map([ ++ ['old', env.has(name) ? env.get(name) : null], ++ ['new', v], ++ ]); ++ v = evalRubyExpr(op === '+=' ? 'old + new' : 'old || new', vars); ++ } ++ if (isUnresolved(v)) { ++ v = new RubyUnresolved( ++ `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + ++ `(${(v /*: any */).why})`, + ); + } -+ return whole; -+ }, -+ ); ++ setLocal(name, v, stAct); ++ interpolate(st, false); ++ continue; ++ } ++ // `name.push(...)`, `name << x`; any other change to a local makes it ++ // unknown. ++ const change = core.match(/^([A-Za-z_]\w*)\s*(?:\.|\[|<<)/); ++ if (change != null && env.has(change[1]) && !recvs.has(change[1])) { ++ const name = change[1]; ++ const old = env.get(name); ++ const add = ++ core.match(/^\w+\s*\.(push|append|concat)\s*\(([\s\S]*)\)$/) ?? ++ core.match(/^\w+\s*\.(push|append|concat)\s+([\s\S]+)$/) ?? ++ core.match(/^\w+\s*(<<)\s*([\s\S]+)$/); ++ let v /*: mixed */ = new RubyUnresolved( ++ `is changed by \`${core}\`, which the reader cannot evaluate`, ++ ); ++ if (add != null && Array.isArray(old)) { ++ // `<<` adds one value; push/append/concat take a list. ++ const args = evalRubyExpr( ++ add[1] === '<<' ? `[(${add[2]})]` : `[${add[2]}]`, ++ env, ++ ); ++ if (Array.isArray(args)) { ++ if (add[1] !== 'concat') v = [...old, ...args]; ++ else if (args.every(Array.isArray)) v = [...old, ...args.flat()]; ++ } ++ } ++ setLocal(name, v, stAct); ++ continue; ++ } ++ interpolate(st, false); ++ } ++ return {text: out.join('\n'), unresolved}; +} + +// The library's own version. Podspecs load the package.json next to them @@ -164,13 +894,10 @@ index 8fcf04b..b3e3a53 100644 // Comment-only lines are dropped so a commented-out `# s.header_dir` cannot win // over the live one. A trailing `#` and a `#` inside a string survive: only the // first non-whitespace character counts. - function readPodspecSource(podspecPath /*: string */) /*: string */ { -- return fs -- .readFileSync(podspecPath, 'utf8') -- .split('\n') -- .filter(line => !/^\s*#/.test(line)) -- .join('\n'); -+ return resolveRubyConstants( ++function readPodspecEvaluated( ++ podspecPath /*: string */, ++) /*: {text: string, unresolved: Array} */ { ++ return evaluateRubyLocals( + resolvePackageVersion( + fs + .readFileSync(podspecPath, 'utf8') @@ -180,6 +907,14 @@ index 8fcf04b..b3e3a53 100644 + path.dirname(podspecPath), + ), + ); ++} + function readPodspecSource(podspecPath /*: string */) /*: string */ { +- return fs +- .readFileSync(podspecPath, 'utf8') +- .split('\n') +- .filter(line => !/^\s*#/.test(line)) +- .join('\n'); ++ return readPodspecEvaluated(podspecPath).text; +} + +// The main spec's block variable: `Pod::Spec.new do |podspec|` -> `podspec`. @@ -313,11 +1048,12 @@ index 8fcf04b..b3e3a53 100644 + * `opts.dropSubspecs` are left out, as if the podspec did not declare them. */ -function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +- const content = readPodspecSource(podspecPath); +function regexPodspec( + podspecPath /*: string */, + opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, +) /*: RawSpec */ { - const content = readPodspecSource(podspecPath); ++ const {text: content, unresolved} = readPodspecEvaluated(podspecPath); + const dropped = new Set(opts?.dropSubspecs ?? []); + const mainName = mainReceiverName(content); + const MAIN_RECV = mainRecvPattern(mainName); @@ -386,7 +1122,7 @@ index 8fcf04b..b3e3a53 100644 } // The fields that identify the spec, and only when the receiver spelling -@@ -235,9 +513,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -235,9 +1248,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: // s. = ["a", "b"] (array) // s. = "single" (single value treated as 1-element array) @@ -417,7 +1153,7 @@ index 8fcf04b..b3e3a53 100644 if (mArr != null) { const inner = mArr[1]; const out /*: Array */ = []; -@@ -249,16 +545,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -249,16 +1280,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { } return out; } @@ -460,7 +1196,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; out.push(m[1]); } -@@ -269,21 +586,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -269,21 +1321,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // s.framework "X" → ["X"] // s.framework = "X" → ["X"] // s.frameworks = ["X","Y"] → ["X","Y"] @@ -491,7 +1227,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; const itemRe = /["']([^"']+)["']/g; while (true) { -@@ -298,12 +619,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -298,12 +1354,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: 'HEADER_SEARCH_PATHS' => '...' or => ["...","..."] // Returns the raw token strings (still containing $(PODS_TARGET_SRCROOT) // etc.); substitution happens at translation time. @@ -508,7 +1244,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; const itemRe = /["']((?:[^"'\\]|\\.)+)["']/g; while (true) { -@@ -321,7 +644,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -321,7 +1379,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { const strRe = /["']HEADER_SEARCH_PATHS["']\s*=>\s*["']((?:[^"'\\]|\\.)+)["']/g; while (true) { @@ -517,7 +1253,7 @@ index 8fcf04b..b3e3a53 100644 if (m == null) break; for (const token of m[1].split(/\s+/)) { if (token.length > 0) { -@@ -332,15 +655,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -332,15 +1390,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { return Array.from(new Set(out)); } @@ -573,7 +1309,7 @@ index 8fcf04b..b3e3a53 100644 ); } if (/install_modules_dependencies/.test(content)) { -@@ -354,24 +715,100 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -354,26 +1450,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { ); } @@ -686,8 +1422,11 @@ index 8fcf04b..b3e3a53 100644 + ), __regex_partial__: true, __warnings__: warnings, ++ __unresolved__: unresolved, }; -@@ -423,6 +860,58 @@ function shellTokenize(value /*: string */) /*: Array */ { + } + +@@ -423,6 +1596,58 @@ function shellTokenize(value /*: string */) /*: Array */ { return tokens; } @@ -746,7 +1485,7 @@ index 8fcf04b..b3e3a53 100644 // --------------------------------------------------------------------------- // Subspec flattening // --------------------------------------------------------------------------- -@@ -438,8 +927,16 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -438,8 +1663,16 @@ function shellTokenize(value /*: string */) /*: Array */ { * - String fields → top-level wins; if absent, take the first subspec's value * - pod_target_xcconfig HEADER_SEARCH_PATHS → array-union across all selected subspecs * - dependencies → array-union of name strings (version constraints dropped) @@ -764,7 +1503,7 @@ index 8fcf04b..b3e3a53 100644 const warnings /*: Array */ = []; // $FlowFixMe[prop-missing] dynamic shape const partial /*: boolean */ = rawSpec.__regex_partial__ === true; -@@ -456,7 +953,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -456,7 +1689,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // - `default_subspecs`: array of names (or undefined → use all subspecs) const subspecs = Array.isArray(rawSpec.subspecs) ? rawSpec.subspecs : []; let selected = subspecs; @@ -778,7 +1517,7 @@ index 8fcf04b..b3e3a53 100644 const wanted = new Set(rawSpec.default_subspecs); selected = subspecs.filter(s => { // $FlowFixMe[prop-missing] dynamic shape -@@ -464,6 +966,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -464,6 +1702,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return name != null && wanted.has(name); }); } @@ -789,7 +1528,7 @@ index 8fcf04b..b3e3a53 100644 const layers = [rawSpec, ...selected]; function mergeArrayField(key /*: string */) /*: Array */ { -@@ -482,6 +988,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -482,6 +1724,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return Array.from(new Set(out)); } @@ -807,7 +1546,7 @@ index 8fcf04b..b3e3a53 100644 // Only the spec's own value: a subspec's `header_dir` names that subspec's // headers, and several subspecs can disagree. function specStringField(key /*: string */) /*: string | null */ { -@@ -544,6 +1061,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -544,6 +1797,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // `-D`s are safe to forward; arbitrary flags may be machine- or // example-app-specific. $(inherited), unresolved $(...) tokens, and invalid // C identifiers are skipped. @@ -828,7 +1567,7 @@ index 8fcf04b..b3e3a53 100644 function mergePreprocessorDefines() /*: Array */ { const out /*: Array */ = []; const seen /*: Set */ = new Set(); -@@ -554,7 +1085,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -554,7 +1821,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { config /*: ?('debug' | 'release') */, ) => { if (!validName.test(name)) return; @@ -853,7 +1592,7 @@ index 8fcf04b..b3e3a53 100644 return; // unresolved Xcode/Ruby token — don't emit a broken define } const key = `${name}|${config ?? ''}`; -@@ -571,6 +1118,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -571,6 +1854,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { 'xcconfig', 'user_target_xcconfig', ]; @@ -874,7 +1613,7 @@ index 8fcf04b..b3e3a53 100644 for (const layer of layers) { if (layer == null || typeof layer !== 'object') continue; for (const xcKey of XCCONFIG_KEYS) { -@@ -627,44 +1188,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -627,44 +1924,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return out; } @@ -1019,7 +1758,7 @@ index 8fcf04b..b3e3a53 100644 } } return out; -@@ -677,6 +1313,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -677,6 +2049,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { ? false : true; // RN ecosystem default @@ -1040,7 +1779,7 @@ index 8fcf04b..b3e3a53 100644 return { name: specStringField('name') ?? '', version: specStringField('version') ?? '', -@@ -693,15 +1343,42 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -693,23 +2079,81 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // header_mappings_dir copy step, which SPM has no equivalent for. headerMappingsDirs: mergeArrayField('header_mappings_dir'), headerDir: specStringField('header_dir'), @@ -1085,7 +1824,46 @@ index 8fcf04b..b3e3a53 100644 requiresArc, warnings, partial, -@@ -722,15 +1399,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { + // Default: overridden in readPodspec, which can see the podspec source. + usesInstallModulesDependencies: false, ++ // $FlowFixMe[incompatible-type] runtime-validated dynamic shape ++ unresolvedSources: Array.isArray(rawSpec.__unresolved__) ++ ? rawSpec.__unresolved__ ++ : [], + }; + } + ++/** ++ * Why the podspec's source globs cannot be scaffolded, or null: each ++ * `source_files`/`exclude_files` value the regex path could not evaluate. A ++ * glob read in part gives a target that builds without some of the library's ++ * files (react-native-screens 4.24.0 lost all of ios/, and the app crashed at ++ * start), so the scaffolder refuses the library instead. Other callers (name ++ * resolution, header search paths) keep reading the model as before. ++ */ ++function unresolvedSourcesReason( ++ podspecPath /*: string */, ++ model /*: PodspecModel */, ++) /*: ?string */ { ++ const list /*: Array */ = model.unresolvedSources ?? []; ++ if (list.length === 0) return null; ++ return ( ++ `${podspecPath}: ` + ++ list ++ .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) ++ .join('; ') + ++ '. The podspec reader evaluates locals, string interpolation, arrays, ' + ++ "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + ++ 'the globs it could read would leave some of the library\'s files out of ' + ++ 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + ++ 'reads the podspec, or give the library a Package.swift of its own.' ++ ); ++} ++ + // --------------------------------------------------------------------------- + // Top-level entry + // --------------------------------------------------------------------------- +@@ -722,15 +2166,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { * Throws when the file doesn't exist. Otherwise always returns a * PodspecModel — warnings on the model surface partial parses to the * caller, who can decide whether to proceed or abort scaffolding for that @@ -1108,7 +1886,7 @@ index 8fcf04b..b3e3a53 100644 // Record whether the podspec calls `install_modules_dependencies(s)`. We // strip that helper before `pod ipc` and the regex parser can't expand it, // so the React-Core family it injects never lands in `model.dependencies`. -@@ -746,21 +1426,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { +@@ -746,21 +2193,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { return model; } @@ -1159,7 +1937,7 @@ index 8fcf04b..b3e3a53 100644 podspecModels.set(key, model); return model; } -@@ -794,12 +1499,13 @@ function readPodspecNames( +@@ -794,12 +2266,13 @@ function readPodspecNames( if (hasShadowingSubspec(source)) { return null; } @@ -1174,11 +1952,30 @@ index 8fcf04b..b3e3a53 100644 const name = field('name'); const moduleName = field('module_name'); +@@ -840,4 +2313,5 @@ module.exports = { + runPodIpcSpec, + regexPodspec, + flattenSubspecs, ++ unresolvedSourcesReason, + }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..a8076ae 100644 +index cf7e587..341c374 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -@@ -54,6 +54,7 @@ const { +@@ -45,7 +45,11 @@ const { + } = require('./expand-spm-dependencies'); + const {expandSpmSourceGlobs} = require('./generate-spm-autolinking'); + const {MIN_IOS_VERSION_SUPPORTED} = require('./ios-deployment-target'); +-const {findPodspecs, readPodspecCached} = require('./read-podspec'); ++const { ++ findPodspecs, ++ readPodspecCached, ++ unresolvedSourcesReason, ++} = require('./read-podspec'); + const { + REACT_CODEGEN_PACKAGE_NAME, + REACT_CODEGEN_PRODUCTS, +@@ -54,6 +58,7 @@ const { SCAFFOLDER_MARKER, makeLogger, remotePackageConfig, @@ -1186,7 +1983,7 @@ index cf7e587..a8076ae 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +114,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -1463,7 +2260,7 @@ index cf7e587..a8076ae 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +416,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +420,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -1837,7 +2634,7 @@ index cf7e587..a8076ae 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +805,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +809,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -1866,7 +2663,7 @@ index cf7e587..a8076ae 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +903,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +907,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -1879,7 +2676,7 @@ index cf7e587..a8076ae 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +983,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +987,92 @@ function translatePodspecToSpmTarget( } } @@ -2000,7 +2797,7 @@ index cf7e587..a8076ae 100644 } } -@@ -427,15 +1134,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1138,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2058,7 +2855,7 @@ index cf7e587..a8076ae 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1244,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1248,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2110,7 +2907,7 @@ index cf7e587..a8076ae 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1310,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1314,101 @@ function translatePodspecToSpmTarget( ); } @@ -2212,7 +3009,7 @@ index cf7e587..a8076ae 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1413,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1417,201 @@ function translatePodspecToSpmTarget( } } @@ -2416,7 +3213,7 @@ index cf7e587..a8076ae 100644 warnings, }; } -@@ -565,6 +1632,9 @@ type EmitContext = { +@@ -565,6 +1636,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -2426,7 +3223,7 @@ index cf7e587..a8076ae 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1699,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1703,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -2453,7 +3250,7 @@ index cf7e587..a8076ae 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1808,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1812,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -2486,7 +3283,7 @@ index cf7e587..a8076ae 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1851,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1855,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -2498,7 +3295,7 @@ index cf7e587..a8076ae 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1871,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1875,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -2572,7 +3369,7 @@ index cf7e587..a8076ae 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1946,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1950,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -2581,7 +3378,7 @@ index cf7e587..a8076ae 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1956,13 @@ let package = Package( +@@ -778,13 +1960,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -2598,7 +3395,7 @@ index cf7e587..a8076ae 100644 ) `; } -@@ -844,6 +2022,61 @@ function reportSwiftName( +@@ -844,6 +2026,61 @@ function reportSwiftName( } } @@ -2660,7 +3457,7 @@ index cf7e587..a8076ae 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2186,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -2673,7 +3470,7 @@ index cf7e587..a8076ae 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2207,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -2682,7 +3479,7 @@ index cf7e587..a8076ae 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2235,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -2727,7 +3524,17 @@ index cf7e587..a8076ae 100644 } catch (e) { return { depName, -@@ -1012,35 +2284,17 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2284,27 @@ function scaffoldPackageSwiftForDep( + reason: `Podspec read failed: ${e.message}`, + }; + } ++ // A source glob the podspec reader could not evaluate: a target built from ++ // the rest would lack some of the library's files. ++ const unresolved = unresolvedSourcesReason(podspecPath, model); ++ if (unresolved != null) { ++ return {depName, status: 'error', reason: unresolved}; ++ } + const spec = translatePodspecToSpmTarget( model, dep, @@ -2772,7 +3579,7 @@ index cf7e587..a8076ae 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2326,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2336,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -2780,7 +3587,7 @@ index cf7e587..a8076ae 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2336,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2346,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -2820,7 +3627,7 @@ index cf7e587..a8076ae 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2375,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2385,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -2921,7 +3728,7 @@ index cf7e587..a8076ae 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2474,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2484,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -2934,7 +3741,7 @@ index cf7e587..a8076ae 100644 return { depName, -@@ -1128,6 +2488,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2498,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -2942,7 +3749,7 @@ index cf7e587..a8076ae 100644 }; } -@@ -1141,7 +2502,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2512,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -2951,7 +3758,7 @@ index cf7e587..a8076ae 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2523,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2533,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -2960,7 +3767,7 @@ index cf7e587..a8076ae 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2655,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2665,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -2972,7 +3779,7 @@ index cf7e587..a8076ae 100644 }; */ -@@ -1323,6 +2689,17 @@ function scaffoldAll( +@@ -1323,6 +2699,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -2990,7 +3797,7 @@ index cf7e587..a8076ae 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2707,23 @@ function scaffoldAll( +@@ -1330,24 +2717,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -3026,7 +3833,7 @@ index cf7e587..a8076ae 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2762,9 @@ function scaffoldAll( +@@ -1386,6 +2772,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3036,7 +3843,7 @@ index cf7e587..a8076ae 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2783,9 @@ function scaffoldAll( +@@ -1404,6 +2793,9 @@ function scaffoldAll( } module.exports = { @@ -3047,10 +3854,21 @@ index cf7e587..a8076ae 100644 scaffoldAll, scaffoldPackageSwiftForDep, diff --git a/node_modules/react-native/scripts/spm/spm-types.js b/node_modules/react-native/scripts/spm/spm-types.js -index a89142f..73dc6c8 100644 +index a89142f..6ce647d 100644 --- a/node_modules/react-native/scripts/spm/spm-types.js +++ b/node_modules/react-native/scripts/spm/spm-types.js -@@ -502,6 +502,9 @@ export type SpmScaffoldSpec = { +@@ -471,6 +471,10 @@ export type PodspecModel = { + // flag as an implicit React-core dependency (a plain ObjC module using the + // helper has no `codegenConfig` to key off). + usesInstallModulesDependencies: boolean, ++ // The `source_files`/`exclude_files` values the regex fallback could not ++ // evaluate (a method call, an unknown local): the scaffolder refuses the ++ // library rather than build it from a partial source list. ++ unresolvedSources?: Array<{field: string, expr: string, why: string}>, + }; + + // Intermediate translation result — concrete data the Swift emitter consumes. +@@ -502,6 +506,9 @@ export type SpmScaffoldSpec = { coreReactNative: boolean, siblingNames: Array, siblingSwiftNames?: {[npmName: string]: string}, @@ -3060,7 +3878,7 @@ index a89142f..73dc6c8 100644 // Extra frameworks beyond the autolinker's default UIKit/Foundation/CoreGraphics // set. Merged with the defaults at emit time. extraFrameworks: Array, -@@ -539,6 +542,9 @@ export type ScaffoldResult = +@@ -539,6 +546,9 @@ export type ScaffoldResult = // What became of `swiftpmConfig.name` in the library's package.json. // Absent when the name was not podspec-derived, so nothing was attempted. swiftpmName?: SwiftpmNameOutcome, diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/LICENSE b/tests/fixtures/podspecs/RNScreens-4.24.0/LICENSE new file mode 100644 index 0000000..1a19308 --- /dev/null +++ b/tests/fixtures/podspecs/RNScreens-4.24.0/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Software Mansion + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/RNScreens.podspec b/tests/fixtures/podspecs/RNScreens-4.24.0/RNScreens.podspec new file mode 100644 index 0000000..0cbe163 --- /dev/null +++ b/tests/fixtures/podspecs/RNScreens-4.24.0/RNScreens.podspec @@ -0,0 +1,77 @@ +# Fixture for tests/rn-scaffolder.test.ts: RNScreens.podspec from react-native-screens 4.24.0 (npm), unchanged below this header. +# MIT License, Copyright (c) 2018 Software Mansion . See LICENSE in this directory. +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "package.json"))) + +gamma_project_enabled = ENV['RNS_GAMMA_ENABLED'] == '1' +new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1' +debug_logging = ENV['RNS_DEBUG_LOGGING'] == '1' + +source_files_exts = new_arch_enabled ? '{h,m,mm,cpp,swift}' : '{h,m,mm,swift}' +source_files = ["ios/**/*.#{source_files_exts}"] + +if !new_arch_enabled + source_files.push("cpp/RNScreensTurboModule.cpp", "cpp/RNScreensTurboModule.h") +end + +min_supported_ios_version = new_arch_enabled ? "15.1" : "15.1" +min_supported_tvos_version = "15.1" +min_supported_visionos_version = "1.0" + +rnscreens_cpp_flags = [] + +rnscreens_cpp_flags << "-DRNS_DEBUG_LOGGING=1" if debug_logging +rnscreens_cpp_flags << "-DRNS_GAMMA_ENABLED=1" if gamma_project_enabled + +rnscreens_config = { + 'OTHER_CPLUSPLUSFLAGS' => rnscreens_cpp_flags.join(" ") +} + +if gamma_project_enabled + # This setting is required to make Swift code build. However we have + # dependency on `React-RCTImage` pod, which does not set `DEFINES_MODULE` + # and therefore it fails to build. Currently we do patch react-native source + # code to make it work & the fix is already merged, however it'll be most likely released + # with 0.81. We can not expect users to patch the react-native sources, thus + # we can not have Swift code in stable package. + rnscreens_config['DEFINES_MODULE'] = 'YES' +end + +Pod::Spec.new do |s| + s.name = "RNScreens" + s.version = package["version"] + s.summary = package["description"] + s.description = <<-DESC + RNScreens - first incomplete navigation solution for your React Native app + DESC + s.homepage = "https://github.com/software-mansion/react-native-screens" + s.license = "MIT" + s.author = { "author" => "author@domain.cn" } + s.platforms = { :ios => min_supported_ios_version, :tvos => min_supported_tvos_version, :visionos => min_supported_visionos_version } + s.source = { :git => "https://github.com/software-mansion/react-native-screens.git", :tag => "#{s.version}" } + s.source_files = source_files + s.project_header_files = "ios/bridging/Swift-Bridging.h" + s.requires_arc = true + + if !gamma_project_enabled + s.exclude_files = "ios/gamma/**/*.#{source_files_exts}" + else + s.exclude_files = "ios/stubs/**/*.#{source_files_exts}" + Pod::UI.puts "[RNScreens] Gamma project enabled. Including source files." + end + + s.pod_target_xcconfig = rnscreens_config + + install_modules_dependencies(s) + if new_arch_enabled + s.subspec "common" do |ss| + ss.source_files = ["common/cpp/**/*.{cpp,h}", "cpp/**/*.{cpp,h}"] + ss.project_header_files = "common/cpp/**/*.h", "cpp/**/*.h" # Don't expose C++ headers publicly to allow importing framework into Swift files + ss.header_dir = "rnscreens" + ss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/common/cpp\"" } + end + end + + s.dependency "React-RCTImage" +end diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.cpp b/tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.cpp new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.h b/tests/fixtures/podspecs/RNScreens-4.24.0/common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.cpp b/tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.cpp new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.h b/tests/fixtures/podspecs/RNScreens-4.24.0/cpp/RNScreensTurboModule.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.mm b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreen.mm new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.mm b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/RNSScreenStack.mm new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.mm b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/RNSReactBaseView.mm new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/Swift-Bridging.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/Swift-Bridging.h new file mode 100644 index 0000000..464acea --- /dev/null +++ b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/bridging/Swift-Bridging.h @@ -0,0 +1,7 @@ +#pragma once + +#if __has_include() +#import +#else +#import "RNScreens-Swift.h" +#endif diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/ReactMountingTransactionObserving.swift b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/ReactMountingTransactionObserving.swift new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.mm b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/gamma/stack/host/RNSStackHostComponentView.mm new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.h b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.h new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.mm b/tests/fixtures/podspecs/RNScreens-4.24.0/ios/stubs/RNSGammaStubs.mm new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNScreens-4.24.0/package.json b/tests/fixtures/podspecs/RNScreens-4.24.0/package.json new file mode 100644 index 0000000..08bd209 --- /dev/null +++ b/tests/fixtures/podspecs/RNScreens-4.24.0/package.json @@ -0,0 +1,78 @@ +{ + "name": "react-native-screens", + "version": "4.24.0", + "description": "Native navigation primitives for your React Native app.", + "license": "MIT", + "codegenConfig": { + "name": "rnscreens", + "type": "all", + "jsSrcsDir": "./src/fabric", + "android": { + "javaPackageName": "com.swmansion.rnscreens" + }, + "ios": { + "components": { + "RNSFullWindowOverlay": { + "className": "RNSFullWindowOverlay" + }, + "RNSModalScreen": { + "className": "RNSModalScreen" + }, + "RNSScreenContainer": { + "className": "RNSScreenContainerView" + }, + "RNSScreenContentWrapper": { + "className": "RNSScreenContentWrapper" + }, + "RNSScreenFooter": { + "className": "RNSScreenFooter" + }, + "RNSScreen": { + "className": "RNSScreenView" + }, + "RNSScreenNavigationContainer": { + "className": "RNSScreenNavigationContainerView" + }, + "RNSScreenStackHeaderConfig": { + "className": "RNSScreenStackHeaderConfig" + }, + "RNSScreenStackHeaderSubview": { + "className": "RNSScreenStackHeaderSubview" + }, + "RNSScreenStack": { + "className": "RNSScreenStackView" + }, + "RNSSearchBar": { + "className": "RNSSearchBar" + }, + "RNSStackScreen": { + "className": "RNSStackScreenComponentView" + }, + "RNSStackHost": { + "className": "RNSStackHostComponentView" + }, + "RNSTabsScreen": { + "className": "RNSTabsScreenComponentView" + }, + "RNSTabsHost": { + "className": "RNSTabsHostComponentView" + }, + "RNSTabsBottomAccessory": { + "className": "RNSTabsBottomAccessoryComponentView" + }, + "RNSTabsBottomAccessoryContent": { + "className": "RNSTabsBottomAccessoryContentComponentView" + }, + "RNSSplitViewHost": { + "className": "RNSSplitViewHostComponentView" + }, + "RNSSplitViewScreen": { + "className": "RNSSplitViewScreenComponentView" + }, + "RNSSafeAreaView": { + "className": "RNSSafeAreaViewComponentView" + } + } + } + } +} diff --git a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift index 36f04fe..d7c72b8 100644 --- a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift @@ -142,6 +142,7 @@ let package = Package( "apple/Utils/RNSVGCGFCRule.h", "apple/Utils/RNSVGConvert.h", "apple/Utils/RNSVGConvert.mm", + "apple/Utils/RNSVGFabricConversions.h", "apple/Utils/RNSVGLength.h", "apple/Utils/RNSVGLength.mm", "apple/Utils/RNSVGMarkerPosition.h", diff --git a/tests/fixtures/scaffold-golden/react-native-svg/apple/module.modulemap b/tests/fixtures/scaffold-golden/react-native-svg/apple/module.modulemap deleted file mode 100644 index 6f78e7f..0000000 --- a/tests/fixtures/scaffold-golden/react-native-svg/apple/module.modulemap +++ /dev/null @@ -1,8 +0,0 @@ -// AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. -// The module SwiftPM would make of publicHeadersPath, minus the headers the podspec leaves -// out of the target, which an importer could not build. -module RNSVG { - umbrella "." - exclude header "Utils/RNSVGFabricConversions.h" - export * -} diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index c20d7a4..81de46e 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -111,7 +111,8 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(src("read-podspec.js")).toContain("Ruby bare list without brackets"); }); it("read-podspec.js has the Ruby constants hunk", () => { - expect(src("read-podspec.js")).toContain("function resolveRubyConstants"); + // Fix 3's constants pass, which fix 28 grew into an evaluator. + expect(src("read-podspec.js")).toContain("function evaluateRubyLocals"); }); it("read-podspec.js has the subspec merge hunk", () => { const f = src("read-podspec.js"); @@ -152,7 +153,8 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () }); it("the scaffolder has the fixes 14–19 hunks", () => { expect(src("read-podspec.js")).toContain("function resolvePackageVersion"); - expect(src("read-podspec.js")).toContain("function rnPodEnvTernary"); + // Fix 19's RN_POD_ENV ternary, which fix 28 grew into ENV lookups in the evaluator. + expect(src("read-podspec.js")).toContain("const RN_POD_ENV"); expect(src("read-podspec.js")).toContain("env: {...process.env, ...RN_POD_ENV}"); const f = src("scaffold-package-swift.js"); expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 5"); @@ -209,6 +211,12 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(f).toContain("function loadPodTable"); expect(f).toContain("// rn-xtool-pods: "); }); + it("the scaffolder has the fix 28 hunks", () => { + const reader = src("read-podspec.js"); + expect(reader).toContain("function evalRubyExpr"); + expect(reader).toContain("function unresolvedSourcesReason"); + expect(src("scaffold-package-swift.js")).toContain("unresolvedSourcesReason(podspecPath, model)"); + }); }); it("gives the per-app header farm a header-less module map, so Objective-C imports it textually", () => { @@ -1482,7 +1490,8 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { ["0", "0"], ["empty", ""], ["true", "true"], - ])("19: evaluates both ternaries with React Native's value 1 (environment %s), and no other ENV condition", (_, value) => { + ])("19: evaluates both ternaries with React Native's value 1 (environment %s), and any other variable as unset", (_, value) => { + // Fix 28: every other `ENV[...]` reads as unset whatever the shell says, so a scaffold never depends on it. const body = " hermes = ENV['RCT_HERMES_V1_ENABLED'] == '1' ? '-DHERMES_V1_ON' : '-DHERMES_V1_OFF'\n" + ' arch = ENV["RCT_NEW_ARCH_ENABLED"] != "0" ? "-DARCH_ON" : "-DARCH_OFF"\n' + @@ -1497,7 +1506,8 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { const got = defines(scaffoldOne(lib({ "ios/Foo.h": "", "ios/Foo.m": "" }, body)).pkg); expect(got).toContain("HERMES_V1_ON"); expect(got).toContain("ARCH_ON"); - for (const d of ["HERMES_V1_OFF", "ARCH_OFF", "FOO_ON", "FOO_OFF"]) expect(got).not.toContain(d); + expect(got).toContain("FOO_OFF"); + for (const d of ["HERMES_V1_OFF", "ARCH_OFF", "FOO_ON"]) expect(got).not.toContain(d); } finally { vi.unstubAllEnvs(); } @@ -2387,6 +2397,140 @@ describe("scaffolder fix 27: binary pods (vendor/rn-spm)", () => { }); }); +// Fix 28 (React Native 0.88.0 patch), on the vendored copy. react-native-screens 4.24.0 builds its globs from locals +// assigned under conditions (`exts = new_arch_enabled ? '…' : '…'`, `source_files = ["ios/**/*.#{exts}"]`, a +// conditional `.push`, `if !gamma … else … end` around `exclude_files`): the reader left `#{exts}` unresolved, the +// target got only the `common` subspec's C++ and no Objective-C class, and the app crashed at start. +describe("scaffolder fix 28: podspec locals and conditions (vendor/rn-spm)", () => { + const fixture = (dir: string) => path.join(PODSPEC_FIXTURES, dir); + /** The `sources:` entries of a manifest's first target. */ + const sourcesOf = (pkg: string) => [...pkg.match(/sources: \[([^\]]*)\]/)![1]!.matchAll(/"([^"]+)"/g)].map((m) => m[1]!); + /** A library with the given files and podspec text (the whole file), as a temp dir. */ + function podLib(files: Record, podspec: string, name = "Foo"): string { + const root = tempDir(); + for (const [f, text] of Object.entries({ "package.json": JSON.stringify({ name: "foo", version: "1.0.0" }), ...files })) { + mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); + writeFileSync(path.join(root, f), text); + } + writeFileSync(path.join(root, `${name}.podspec`), podspec); + return root; + } + const scaffoldPod = (root: string) => scaffoldLibraries(VENDORED_RN_SPM, { "react-native-foo": root }); + const FILES = { "ios/A.h": "", "ios/A.mm": "", "ios/B.m": "", "ios/off/C.mm": "", "cpp/D.cpp": "", "cpp/D.h": "" }; + + it("28: scaffolds screens 4.24.0 with its ios/ sources, gamma excluded, stubs and the common subspec kept", () => { + const run = scaffoldLibraries(VENDORED_RN_SPM, { "react-native-screens": fixture("RNScreens-4.24.0") }); + expect(run.results[0]?.status, run.results[0]?.reason).toBe("written"); + const pkg = run.files["react-native-screens/Package.swift"]!; + const sources = sourcesOf(pkg); + for (const f of [ + "ios/RNSScreen.mm", + "ios/RNSScreenStack.mm", + "ios/bridging/RNSReactBaseView.mm", + "ios/stubs/RNSGammaStubs.mm", + "cpp/RNScreensTurboModule.cpp", + "common/cpp/react/renderer/components/rnscreens/RNSScreenShadowNode.cpp", + ]) { + expect(sources, f).toContain(f); + } + expect(sources.filter((f) => f.startsWith("ios/gamma/"))).toEqual([]); + // With RNS_GAMMA_ENABLED unset every Swift file is under ios/gamma, so CocoaPods builds one Objective-C++ target: + // clang-only here too, and the module map leaves out the gamma headers and Swift-Bridging.h (it imports the + // module's own -Swift.h, which a clang-only target never has). + expect(pkg.split("\n")[0]).toBe("// swift-tools-version: 6.0"); + expect(run.files["react-native-screens/Package@swift-6.5.swift"]).toBeUndefined(); + expect(pkg).toContain('publicHeadersPath: "ios",'); + const map = run.files["react-native-screens/ios/module.modulemap"]!; + expect(map).toContain(' exclude header "gamma/stack/host/RNSStackHostComponentView.h"\n'); + expect(map).toContain(' exclude header "bridging/Swift-Bridging.h"\n'); + expect(map).not.toContain("stubs/"); + }); + + it("28: evaluates locals, interpolation, ternaries, ENV, if/elsif/else/unless and push/<< in order", () => { + const podspec = + "new_arch = ENV['RCT_NEW_ARCH_ENABLED'] == '1'\n" + + "legacy = !new_arch\n" + + "gamma = ENV['FOO_GAMMA'] == '1'\n" + + "exts = new_arch ? '{h,m,mm,cpp}' : '{h,m}'\n" + + 'srcs = ["ios/*.#{exts}"]\n' + + 'srcs.push("never/*.m") if legacy\n' + + "unless gamma\n" + + ' srcs << "cpp/*.{cpp,h}"\n' + + "end\n" + + "if gamma\n" + + ' off = "ios/never/**"\n' + + "elsif ENV['RCT_HERMES_V1_ENABLED'] != '1'\n" + + ' off = "ios/also-never/**"\n' + + "else\n" + + " off = 'ios/off/**'\n" + + "end\n" + + "Pod::Spec.new do |s|\n" + + ' s.name = "Foo"\n' + + " s.source_files = srcs\n" + + " if !gamma\n" + + " s.exclude_files = off\n" + + " else\n" + + ' s.exclude_files = "ios/A.h"\n' + + " end\n" + + "end\n"; + const run = scaffoldPod(podLib(FILES, podspec)); + expect(run.results[0]?.status, run.results[0]?.reason).toBe("written"); + expect(sourcesOf(run.files["react-native-foo/Package.swift"]!).sort()).toEqual(["cpp/D.cpp", "cpp/D.h", "ios/A.h", "ios/A.mm", "ios/B.m"]); + }); + + it("28: single-quoted strings do not interpolate, and a later assignment wins", () => { + const root = podLib( + FILES, + "exts = '{h}'\n" + + "exts = '{h,mm}'\n" + + "Pod::Spec.new do |s|\n" + + ' s.name = "Foo"\n' + + ' s.source_files = "ios/*.#{exts}", \'ios/#{exts}.m\'\n' + + "end\n", + ); + const { readPodspec } = createRequire(import.meta.url)(path.join(VENDORED_RN_SPM, "read-podspec.js")) as { + readPodspec(f: string): { sourceFiles: string[] }; + }; + expect(withRnRoot("0.86.3", () => readPodspec(path.join(root, "Foo.podspec"))).sourceFiles).toEqual(["ios/*.{h,mm}", "ios/#{exts}.m"]); + }); + + it.each([ + ["an unknown identifier", " s.source_files = mystery", "source_files", "mystery"], + ["a method call", ' s.source_files = Dir.glob("ios/*.m")', "source_files", 'Dir.glob("ios/*.m")'], + ["an interpolated call", ' s.exclude_files = "ios/#{helper(1)}/**"', "exclude_files", '"ios/#{helper(1)}/**"'], + ["a local built from a call", ' srcs = ["ios/*.m"] + extra_sources\n s.source_files = srcs', "source_files", "srcs"], + ["a local set under a condition it cannot evaluate", " if respond_to?(:foo)\n exts = '{h,m}'\n end\n s.source_files = \"ios/*.#{exts}\"", "source_files", "respond_to?(:foo)"], + ])("28: refuses %s in a source glob, naming the podspec, the field and the expression", (_, body, field, expr) => { + const run = scaffoldPod(podLib(FILES, `Pod::Spec.new do |s|\n s.name = "Foo"\n${body}\nend\n`)); + const res = run.results[0]!; + expect(res.status).toBe("error"); + expect(res.reason).toContain("Foo.podspec"); + expect(res.reason).toContain(field); + expect(res.reason).toContain(expr); + expect(run.files["react-native-foo/Package.swift"]).toBeUndefined(); + }); + + it("28: reads both branches of a condition it cannot evaluate, as before", () => { + // The `respond_to?(:install_modules_dependencies, true)` idiom, and a literal glob under such a condition + // (react-native-vision-camera's `if enableFrameProcessors` subspec, fix 20): both branches stay visible. + const podspec = + "Pod::Spec.new do |s|\n" + + ' s.name = "Foo"\n' + + " if respond_to?(:foo)\n" + + ' s.source_files = "ios/*.{h,mm}"\n' + + " end\n" + + " if respond_to?(:install_modules_dependencies, true)\n" + + " install_modules_dependencies(s)\n" + + " else\n" + + ' s.dependency "React-Core"\n' + + " end\n" + + "end\n"; + const run = scaffoldPod(podLib(FILES, podspec)); + expect(run.results[0]?.status, run.results[0]?.reason).toBe("written"); + expect(sourcesOf(run.files["react-native-foo/Package.swift"]!).sort()).toEqual(["ios/A.h", "ios/A.mm"]); + }); +}); + describe("React Native's own pods are core (vendor/rn-spm)", () => { type Classify = (depName: string, ctx: object) => { kind: string }; const classify = (name: string): string => diff --git a/tests/tarballs.test.ts b/tests/tarballs.test.ts index 89a4430..311a8f1 100644 --- a/tests/tarballs.test.ts +++ b/tests/tarballs.test.ts @@ -143,9 +143,9 @@ describe("tests/support/tarballs", () => { expect(patchedSpm(rn)).toBe(spm); expect(packageFromTarball(rn)).toBe(pristine); expect(path.dirname(path.dirname(spm))).not.toBe(pristine); - expect(readFileSync(path.join(spm, "read-podspec.js"), "utf8")).toContain("function resolveRubyConstants"); + expect(readFileSync(path.join(spm, "read-podspec.js"), "utf8")).toContain("function evaluateRubyLocals"); expect(readFileSync(path.join(pristine, "scripts", "spm", "read-podspec.js"), "utf8")).not.toContain( - "function resolveRubyConstants", + "function evaluateRubyLocals", ); // Its scripts load yargs and micromatch, which an app would have installed; here they come from rn-xtool. expect(existsSync(path.join(spm, "..", "..", "node_modules", "yargs"))).toBe(true); diff --git a/vendor/rn-spm/rn-xtool-edits.patch b/vendor/rn-spm/rn-xtool-edits.patch index 292713b..3309c15 100644 --- a/vendor/rn-spm/rn-xtool-edits.patch +++ b/vendor/rn-spm/rn-xtool-edits.patch @@ -161,7 +161,7 @@ resolveLocalHermesCompilerVersion, --- a/spm/read-podspec.js +++ b/spm/read-podspec.js -@@ -1428,9 +1428,15 @@ +@@ -2195,9 +2195,15 @@ // The installed React Native's version as the macros libraries derive from it. function readRnVersionMacros() /*: {[string]: number} */ { diff --git a/vendor/rn-spm/spm/read-podspec.js b/vendor/rn-spm/spm/read-podspec.js index d11e3ba..5dfc1a5 100644 --- a/vendor/rn-spm/spm/read-podspec.js +++ b/vendor/rn-spm/spm/read-podspec.js @@ -169,102 +169,832 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { // Regex fallback // --------------------------------------------------------------------------- -// Ruby constants. Podspecs commonly hoist a glob or extension list into a local -// and reuse it (react-native-screens: `source_files_exts = '{h,m,mm,cpp}'`, -// `source_files = ["ios/**/*.#{source_files_exts}"]`, `s.source_files = -// source_files`). The field regexes below only understand literals, so such a -// field read as missing and the library scaffolded with no sources. +// Ruby locals and conditions. Podspecs hoist globs, extension lists and flags +// into locals and set them under conditions; react-native-screens 4.24.0: // -// This pre-pass resolves the simple cases textually, so the regexes stay -// untouched: single-line `ident = 'str' | "str" | ["a", "b"]` assignments are -// collected (first assignment wins; `if`/`ENV[...]` conditions are NOT -// evaluated, except the one kind below), then `#{ident}` inside the text is replaced by a known string -// constant, and a field assigned a bare known identifier (`s.x = ident`) is -// rewritten to the literal value (`s.x = ident`, `s.ios.x = ident`, and a -// subspec's `ss.x = ident`). `#{}` is only interpolated inside double-quoted -// strings, as in Ruby. Unknown interpolations/identifiers are left as they are. +// new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1' +// source_files_exts = +// new_arch_enabled ? '{h,m,mm,cpp,swift}' : '{h,m,mm,swift}' +// source_files = ["ios/**/*.#{source_files_exts}"] +// if !new_arch_enabled +// source_files.push("cpp/RNScreensTurboModule.cpp", ...) +// end +// ... +// s.source_files = source_files +// if !gamma_project_enabled +// s.exclude_files = "ios/gamma/**/*.#{source_files_exts}" +// else ... // -// One kind of condition is evaluated: a string ternary on an environment -// variable React Native's CocoaPods setup itself sets for every pod -// (`ident = ENV['VAR'] == 'v' ? 'a' : 'b'`, also `!=`), with the value that -// setup gives it: `1` for both. The environment is not read. React Native -// 0.87+ sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, -// so a `0` left in the shell could only break the build (and a persisted -// scaffold). react-native-worklets puts -// `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == '1' ? '-DHERMES_V1_ENABLED' -// : ''` in OTHER_CFLAGS; without the define it includes the legacy Hermes -// inspector headers, which the prebuilt artifacts do not ship. +// The field regexes below only understand literals, so this pre-pass runs the +// podspec's statements in order over a small, side-effect-free subset of Ruby +// and leaves the regexes a flat text: +// +// - values: string literals (single quotes verbatim, double quotes with +// `#{expr}` interpolation), `%w[...]`, array literals, numbers, `true`, +// `false`, `nil`, and locals (`name = expr`, also `+=` and `||=`; the last +// assignment that runs wins, as in Ruby); +// - `ENV['X']` and `ENV.fetch('X', default)`: `RCT_NEW_ARCH_ENABLED` and +// `RCT_HERMES_V1_ENABLED` are `1` (below), every other variable is unset. +// The environment is never read, so a scaffold does not depend on the shell; +// - `==`, `!=`, `!`/`not`, `&&`/`and`, `||`/`or`, `+` on strings and arrays, +// `a ? b : c`, `array.join(sep)`, `.to_s`, `.freeze`; +// - `if`/`elsif`/`else`/`unless`/`end` blocks and `stmt if cond` / `stmt +// unless cond` modifiers, at the top level and inside the spec and subspec +// blocks: a branch that does not run is blanked, the control lines of a +// condition that was evaluated are dropped; +// - `local.push(...)`, `local.append(...)`, `local.concat(...)`, `local << x`; +// - `recv. = expr` on the spec or a subspec (`s.`, `s.ios.`, `ss.`): +// a value that is not already a literal is rewritten to the literal it +// evaluates to. Inside a hash (`pod_target_xcconfig`, `resource_bundles`), +// `=> local` is replaced by the local's value. +// +// Anything else (method calls, hashes, symbols, `$config[...]`, blocks other +// than the spec's, conditions on any of these) is not evaluated: the text +// stays as written, and a local assigned from it, or under such a condition, is +// unknown from there on. Both branches of such a condition stay visible, as +// before (react-native-vision-camera's `if enableFrameProcessors` subspec). A +// `source_files` or `exclude_files` value that uses something unknown is +// returned in `unresolved`, and the scaffolder refuses the library +// (unresolvedSourcesReason): a glob read in part gives a target that builds +// and lacks the library's classes, so the app crashes at start +// (react-native-screens 4.24.0 lost all of ios/). +// +// `RCT_NEW_ARCH_ENABLED` and `RCT_HERMES_V1_ENABLED` get the value React +// Native's CocoaPods setup gives every pod, `1` for both. React Native 0.87+ +// sets both to `1` outright, and the prebuilt artifacts are V1 Hermes, so a +// `0` left in the shell could only break the build (and a persisted scaffold). +// react-native-worklets puts `hermes_v1_flag = ENV['RCT_HERMES_V1_ENABLED'] == +// '1' ? '-DHERMES_V1_ENABLED' : ''` in OTHER_CFLAGS; without the define it +// includes the legacy Hermes inspector headers, which the prebuilt artifacts +// do not ship. const RN_POD_ENV /*: {[string]: string} */ = { RCT_NEW_ARCH_ENABLED: '1', RCT_HERMES_V1_ENABLED: '1', }; -function rnPodEnvTernary(rhs /*: string */) /*: ?string */ { - const m = rhs.match( - /^ENV\[\s*(["'])([A-Z0-9_]+)\1\s*\]\s*(==|!=)\s*(["'])([^"']*)\4\s*\?\s*(?:"([^"]*)"|'([^']*)')\s*:\s*(?:"([^"]*)"|'([^']*)')$/, + +// A value the evaluator could not compute, and why. +class RubyUnresolved { + /*:: why: string; */ + constructor(why /*: string */) { + this.why = why; + } +} +const isUnresolved = (v /*: mixed */) /*: boolean */ => + v instanceof RubyUnresolved; + +// The source-glob fields an unevaluated expression must not reach silently. +const STRICT_FIELDS /*: Set */ = new Set([ + 'source_files', + 'exclude_files', +]); +const PLATFORM_SCOPES /*: Set */ = new Set([ + 'ios', + 'osx', + 'macos', + 'tvos', + 'visionos', + 'watchos', +]); + +// Tokens of one Ruby expression. A double-quoted string keeps its parts: +// literal text and the source of each `#{...}`. +function tokenizeRubyExpr(src /*: string */) /*: Array */ { + const tokens = []; + let i = 0; + // The end of a `#{...}` starting at `from` (just past `#{`), or -1. + const interpEnd = (from /*: number */) => { + let depth = 1; + let quote = ''; + for (let j = from; j < src.length; j++) { + const c = src[j]; + if (quote !== '') { + if (c === '\\') j++; + else if (c === quote) quote = ''; + } else if (c === '"' || c === "'") quote = c; + else if (c === '{') depth++; + else if (c === '}' && --depth === 0) return j; + } + return -1; + }; + const CLOSE = {'[': ']', '(': ')', '{': '}', '<': '>'}; + while (i < src.length) { + const c = src[i]; + if (/\s/.test(c)) { + i++; + } else if (c === "'") { + let v = ''; + let j = i + 1; + for (; j < src.length && src[j] !== "'"; j++) { + if (src[j] === '\\' && (src[j + 1] === "'" || src[j + 1] === '\\')) { + v += src[++j]; + } else v += src[j]; + } + if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; + tokens.push({t: 'str', parts: [v]}); + i = j + 1; + } else if (c === '"') { + const parts = []; + let v = ''; + let j = i + 1; + for (; j < src.length && src[j] !== '"'; j++) { + if (src[j] === '\\') { + const e = src[++j]; + v += e === 'n' ? '\n' : e === 't' ? '\t' : e; + } else if (src[j] === '#' && src[j + 1] === '{') { + const end = interpEnd(j + 2); + if (end < 0) return [{t: 'bad', v: src.slice(i)}]; + parts.push(v, {expr: src.slice(j + 2, end)}); + v = ''; + j = end; + } else v += src[j]; + } + if (j >= src.length) return [{t: 'bad', v: src.slice(i)}]; + parts.push(v); + tokens.push({t: 'str', parts}); + i = j + 1; + } else if (c === '%' && /^%w[[({<]/.test(src.slice(i, i + 3))) { + const close = CLOSE[src[i + 2]]; + const end = src.indexOf(close, i + 3); + if (end < 0) return [{t: 'bad', v: src.slice(i)}]; + tokens.push({ + t: 'words', + v: src + .slice(i + 3, end) + .split(/\s+/) + .filter(Boolean), + }); + i = end + 1; + } else if (/[0-9]/.test(c)) { + const m = src.slice(i).match(/^[0-9][0-9_.]*/); + const text = m != null ? m[0] : c; + tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); + i += text.length; + } else if (/[A-Za-z_]/.test(c)) { + const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); + const text = m != null ? m[0] : c; + tokens.push({t: 'id', v: text}); + i += text.length; + } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { + tokens.push({t: 'bad', v: src.slice(i)}); // a symbol + i = src.length; + } else { + const two = src.slice(i, i + 2); + if (['==', '!=', '&&', '||', '=>', '::', '<<', '=~'].includes(two)) { + tokens.push({t: 'op', v: two}); + i += 2; + } else { + tokens.push({t: 'op', v: c}); + i++; + } + } + } + return tokens; +} + +const rubyTruthy = (v /*: mixed */) /*: boolean */ => v !== false && v != null; + +function rubyEqual(a /*: mixed */, b /*: mixed */) /*: boolean */ { + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); + } + return a === b; +} + +// `#{v}`: Ruby's to_s for the values the evaluator knows. +function rubyToS(v /*: mixed */) /*: string | RubyUnresolved */ { + if (typeof v === 'string') return v; + if (v == null) return ''; + if (typeof v === 'boolean' || typeof v === 'number') return String(v); + return new RubyUnresolved('an array or hash inside `#{...}`'); +} + +/** + * Evaluates one Ruby expression with the locals in `env`. Returns the value, + * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list + * (`s.x = "a", "b"`) as an array. Never runs anything. + */ +function evalRubyExpr( + src /*: string */, + env /*: Map */, + list /*:: ?: boolean */, +) /*: mixed */ { + const tokens = tokenizeRubyExpr(src); + let pos = 0; + const peek = (v /*: string */) => + tokens[pos] != null && + (tokens[pos].t === 'op' || tokens[pos].t === 'id') && + tokens[pos].v === v; + const take = (v /*: string */) => { + if (!peek(v)) return false; + pos++; + return true; + }; + const fail = (why /*: string */) => new RubyUnresolved(why); + // Skips a balanced (...) / [...] / {...} group starting at `pos`. + const skipGroup = () => { + let depth = 0; + do { + const tk = tokens[pos++]; + if (tk == null) return; + if (tk.t === 'op' && '([{'.includes(tk.v)) depth++; + if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; + } while (depth > 0); + }; + // Comma-separated expressions up to `close` (already past the opener). + const parseItems = (close /*: string */) => { + const items = []; + while (!peek(close)) { + if (tokens[pos] == null) return fail(`a missing \`${close}\``); + items.push(parseTernary()); + if (!take(',')) break; + } + if (!take(close)) return fail(`a missing \`${close}\``); + return items.find(isUnresolved) ?? items; + }; + function parsePrimary() /*: mixed */ { + const tk = tokens[pos++]; + if (tk == null) return fail('an incomplete expression'); + if (tk.t === 'str') { + let out = ''; + for (const part of tk.parts) { + if (typeof part === 'string') { + out += part; + continue; + } + const inner = evalRubyExpr(part.expr, env); + if (isUnresolved(inner)) return inner; + const s = rubyToS(inner); + if (isUnresolved(s)) return s; + out += (s /*: any */); + } + return out; + } + if (tk.t === 'words') return tk.v; + if (tk.t === 'num') return tk.v; + if (tk.t === 'bad') return fail(`\`${tk.v}\``); + if (tk.t === 'op') { + if (tk.v === '(') { + const v = parseTernary(); + return take(')') ? v : fail('a missing `)`'); + } + if (tk.v === '[') return parseItems(']'); + if (tk.v === '{') return fail('a hash'); + return fail(`\`${tk.v}\``); + } + // An identifier. + const name = tk.v; + if (name === 'true') return true; + if (name === 'false') return false; + if (name === 'nil') return null; + if (name === 'ENV') { + if (take('[')) { + const key = parseTernary(); + if (!take(']')) return fail('a missing `]`'); + if (isUnresolved(key)) return key; + return typeof key === 'string' && Object.hasOwn(RN_POD_ENV, key) + ? RN_POD_ENV[key] + : null; + } + if (take('.') && take('fetch') && take('(')) { + const args = parseItems(')'); + if (isUnresolved(args)) return args; + const [key, fallback] = (args /*: any */); + if (typeof key !== 'string') return fail('`ENV.fetch` of a non-string'); + return Object.hasOwn(RN_POD_ENV, key) ? RN_POD_ENV[key] : fallback; + } + return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); + } + if (peek('(')) { + skipGroup(); + return fail(`the method call \`${name}(...)\``); + } + if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); + const v = env.get(name); + if (isUnresolved(v)) { + return fail(`\`${name}\`, which ${(v /*: any */).why}`); + } + return v; + } + function parsePostfix() /*: mixed */ { + let v = parsePrimary(); + while (peek('.') || peek('[')) { + if (take('[')) { + pos--; + skipGroup(); + v = isUnresolved(v) ? v : fail('an index `[...]`'); + continue; + } + take('.'); + const m = tokens[pos++]; + const method = m != null && m.t === 'id' ? m.v : '?'; + let args = []; + if (peek('(')) { + pos++; + const got = parseItems(')'); + if (isUnresolved(got)) { + v = isUnresolved(v) ? v : got; + continue; + } + args = (got /*: any */); + } + if (isUnresolved(v)) continue; + if ((method === 'freeze' || method === 'to_s') && typeof v === 'string') { + continue; + } + if (method === 'join' && Array.isArray(v)) { + const sep = args.length > 0 ? args[0] : ''; + const parts = v.flat(Infinity).map(rubyToS); + const bad = parts.find(isUnresolved); + v = + bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); + continue; + } + v = fail(`the method call \`.${method}\``); + } + return v; + } + function parseUnary() /*: mixed */ { + if (take('!')) { + const v = parseUnary(); + return isUnresolved(v) ? v : !rubyTruthy(v); + } + return parsePostfix(); + } + function parseAdd() /*: mixed */ { + let l = parseUnary(); + while (take('+')) { + const r = parseUnary(); + if (isUnresolved(l)) continue; + if (isUnresolved(r)) l = r; + else if (typeof l === 'string' && typeof r === 'string') l = l + r; + else if (Array.isArray(l) && Array.isArray(r)) l = [...l, ...r]; + else l = fail('`+` on values other than two strings or two arrays'); + } + return l; + } + function parseEq() /*: mixed */ { + const l = parseAdd(); + if (peek('==') || peek('!=')) { + const op = tokens[pos++].v; + const r = parseAdd(); + if (isUnresolved(l)) return l; + if (isUnresolved(r)) return r; + return op === '==' ? rubyEqual(l, r) : !rubyEqual(l, r); + } + if (peek('=~') || peek('<') || peek('>')) { + return fail(`the operator \`${tokens[pos].v}\``); + } + return l; + } + function parseNot() /*: mixed */ { + if (take('not')) { + const v = parseNot(); + return isUnresolved(v) ? v : !rubyTruthy(v); + } + return parseEq(); + } + function parseAnd() /*: mixed */ { + let l = parseNot(); + while (take('&&') || take('and')) { + const r = parseNot(); + if (!isUnresolved(l) && rubyTruthy(l)) l = r; + } + return l; + } + function parseOr() /*: mixed */ { + let l = parseAnd(); + while (take('||') || take('or')) { + const r = parseAnd(); + if (!isUnresolved(l) && !rubyTruthy(l)) l = r; + } + return l; + } + function parseTernary() /*: mixed */ { + const c = parseOr(); + if (!take('?')) return c; + const a = parseTernary(); + if (!take(':')) return fail('a ternary without `:`'); + const b = parseTernary(); + if (isUnresolved(c)) return c; + return rubyTruthy(c) ? a : b; + } + let value = parseTernary(); + if (list === true && peek(',')) { + const items = [value]; + while (take(',')) items.push(parseTernary()); + value = items.find(isUnresolved) ?? items; + } + if (pos < tokens.length && !isUnresolved(value)) { + const rest = tokens[pos]; + return fail( + rest.t === 'op' || rest.t === 'id' + ? `\`${rest.v}\` where it ends` + : 'more than one expression', + ); + } + return value; +} + +// A literal the field regexes read as written: quoted strings without +// `#{...}`, as one value, an array or a bare list. +function isPlainLiteral(rhs /*: string */) /*: boolean */ { + const str = `(?:"[^"\\\\#]*"|'[^'\\\\]*')`; + const list = `${str}(?:\\s*,\\s*${str})*`; + return new RegExp( + `^(?:${list}|\\[\\s*(?:${list}\\s*,?)?\\s*\\]|true|false)$`, + ).test(rhs.trim()); +} + +// The literal a field is rewritten to, or null when the value has none. +function rubyLiteral(v /*: mixed */) /*: ?string */ { + if (typeof v === 'string') return JSON.stringify(v); + if (typeof v === 'boolean') return String(v); + if (Array.isArray(v)) { + const flat = v.flat(Infinity); + if (!flat.every(x => typeof x === 'string')) return null; + return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; + } + return null; +} + +// The podspec's logical statements: lines joined while a bracket or string is +// open or the line ends in `,`, `\`, an operator or `=`. A heredoc's body +// belongs to the statement that opens it. `code` is the statement without +// trailing comments. +function rubyStatements( + lines /*: Array */, +) /*: Array<{start: number, end: number, code: string}> */ { + const out = []; + const scan = ( + line /*: string */, + state /*: {depth: number, quote: string} */, + ) => { + let code = ''; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (state.quote !== '') { + code += c; + if (c === '\\') code += line[++i] ?? ''; + else if (c === state.quote) state.quote = ''; + continue; + } + if (c === '#') break; + code += c; + if (c === '"' || c === "'") state.quote = c; + else if ('([{'.includes(c)) state.depth++; + else if (')]}'.includes(c)) state.depth--; + } + return code; + }; + let i = 0; + while (i < lines.length) { + const start = i; + const state = {depth: 0, quote: ''}; + const codes = []; + let heredoc = null; + while (i < lines.length) { + const code = scan(lines[i], state); + codes.push(code); + i++; + const h = code.match(/<<([-~]?)(["']?)([A-Za-z_]\w*)\2\s*$/); + if (h != null && state.quote === '') { + heredoc = {indented: h[1] !== '', id: h[3]}; + break; + } + const open = + state.depth > 0 || + state.quote !== '' || + /(?:,|\\|&&|\|\||[^=!<>]=|\+|\s\?|\s:)\s*$/.test(code); + if (!open) break; + } + if (i >= lines.length && (state.depth > 0 || state.quote !== '')) { + // Never closed: read the first line alone and go on from the next. + const code = scan(lines[start], {depth: 0, quote: ''}); + out.push({start, end: start, code}); + i = start + 1; + continue; + } + if (heredoc != null) { + const {indented, id} = heredoc; + while (i < lines.length) { + const l = lines[i++]; + if ((indented ? l.trim() : l) === id) break; + } + } + out.push({start, end: i - 1, code: codes.join('\n')}); + } + return out; +} + +// The index of a trailing `if`/`unless` modifier outside strings and brackets. +function modifierIndex(code /*: string */) /*: ?{at: number, kw: string} */ { + let quote = ''; + let depth = 0; + for (let i = 1; i < code.length; i++) { + const c = code[i]; + if (quote !== '') { + if (c === '\\') i++; + else if (c === quote) quote = ''; + continue; + } + if (c === '"' || c === "'") quote = c; + else if ('([{'.includes(c)) depth++; + else if (')]}'.includes(c)) depth--; + else if (depth === 0 && /\s/.test(code[i - 1])) { + const m = code.slice(i).match(/^(if|unless)\s/); + if (m != null) return {at: i, kw: m[1]}; + } + } + return null; +} + +/*:: +type Unresolved = {field: string, expr: string, why: string}; +type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; +*/ + +// Why a local set under `act` is unknown from there on. +function unknownUnder(act /*: Activity */) /*: RubyUnresolved */ { + return new RubyUnresolved( + act.state === 'maybe' + ? `is set under \`${act.why}\`, a condition the reader cannot evaluate` + : `is set inside \`${act.why}\`, a block the reader does not run`, ); - if (m == null || !Object.hasOwn(RN_POD_ENV, m[2])) return null; - const value = RN_POD_ENV[m[2]]; - const holds = m[3] === '==' ? value === m[5] : value !== m[5]; - return holds ? m[6] ?? m[7] : m[8] ?? m[9]; } -function resolveRubyConstants(content /*: string */) /*: string */ { - const strings /*: Map */ = new Map(); - const arrays /*: Map> */ = - new Map(); - const assignRe = /^[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*(.+?)[ \t]*$/gm; - for (const m of content.matchAll(assignRe)) { - const name = m[1]; - if (strings.has(name) || arrays.has(name)) continue; - const rhs = m[2]; - const str = rhs.match(/^(?:"([^"]*)"|'([^']*)')$/); - if (str != null) { - strings.set(name, str[1] ?? str[2]); + +// The branch an `elsif` opens, and what is known of the branches before it. +function elsifBranch( + prior /*: string */, + cond /*: string */, +) /*: {branch: string, prior: string} */ { + if (prior === 'yes') return {branch: 'no', prior: 'yes'}; + if (prior === 'no') return {branch: cond, prior: cond}; + // An earlier branch may have run. + return { + branch: cond === 'no' ? 'no' : 'maybe', + prior: cond === 'yes' ? 'yes' : 'maybe', + }; +} + +/** + * Runs the podspec's statements over the subset above. Returns the rewritten + * text (same line count) and each `source_files`/`exclude_files` assignment + * whose value could not be evaluated. + */ +function evaluateRubyLocals( + content /*: string */, +) /*: {text: string, unresolved: Array} */ { + const lines = content.split('\n'); + const out = lines.slice(); + const env /*: Map */ = new Map(); + const recvs /*: Set */ = new Set(); + const unresolved /*: Array */ = []; + // `if` blocks (which branch is being read) and other blocks. + const frames /*: Array */ = []; + const blank = (st /*: {start: number, end: number} */) => { + for (let k = st.start; k <= st.end; k++) out[k] = ''; + }; + // Whether the statement being read runs: 'yes', 'no', 'maybe' (under a + // condition it cannot evaluate) or 'opaque' (in a block it does not run), + // with the condition or block that decides. + const activity = () /*: Activity */ => { + let act /*: Activity */ = {state: 'yes', why: ''}; + for (const f of frames) { + const s = f.kind === 'if' ? f.branch : f.opaque ? 'opaque' : 'yes'; + if (s === 'no') return {state: 'no', why: ''}; + if (s !== 'yes' && act.state === 'yes') { + act = {state: s, why: f.kind === 'if' ? f.cond : f.code}; + } + } + return act; + }; + const condOf = (src /*: string */, negate /*: boolean */) => { + const v = evalRubyExpr(src, env); + if (isUnresolved(v)) return 'maybe'; + return rubyTruthy(v) !== negate ? 'yes' : 'no'; + }; + // Lines that stay as written: `#{local}` (a known string) in their + // double-quoted literals, and `=> local` inside a hash, get the value. + const interpolate = ( + st /*: {start: number, end: number} */, + hash /*: boolean */, + ) => { + const known = (id /*: string */) => { + const v = env.get(id); + return typeof v === 'string' ? v : null; + }; + for (let k = st.start; k <= st.end; k++) { + out[k] = out[k].replace( + /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, + lit => + lit[0] === '"' + ? lit.replace( + /#\{\s*([A-Za-z_]\w*)\s*\}/g, + (whole, id) => known(id) ?? whole, + ) + : lit, + ); + if (hash) { + out[k] = out[k].replace( + /(=>\s*)([A-Za-z_]\w*)(?=\s*(?:,|\}|$))/g, + (whole, arrow, id) => { + const lit = env.has(id) ? rubyLiteral(env.get(id)) : null; + return lit != null ? arrow + lit : whole; + }, + ); + } + } + }; + const setLocal = ( + name /*: string */, + value /*: mixed */, + act /*: Activity */, + ) => { + env.set(name, act.state === 'yes' ? value : unknownUnder(act)); + }; + + for (const st of rubyStatements(lines)) { + const code = st.code.trim(); + if (code === '') continue; + const act = activity(); + const oneLine = /[\s;]end\s*;?$/.test(code); + const top = frames[frames.length - 1]; + let m; + m = oneLine ? null : code.match(/^(if|unless)\s+([\s\S]+?)(?:\s+then)?$/); + if (m != null) { + // Under a branch that does not run, every branch is dead. + const branch = + act.state === 'no' || act.state === 'opaque' + ? act.state + : condOf(m[2], m[1] === 'unless'); + frames.push({ + kind: 'if', + branch, + prior: act.state === 'no' ? 'yes' : branch, + cond: m[2], + evaluated: branch !== 'maybe' && branch !== 'opaque', + ctrl: [st], + }); continue; } - const fromEnv = rnPodEnvTernary(rhs); - if (fromEnv != null) { - strings.set(name, fromEnv); + if (top?.kind === 'if') { + if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { + top.ctrl.push(st); + if (top.branch === 'opaque') continue; + const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); + if (cond === 'maybe') top.evaluated = false; + Object.assign(top, elsifBranch(top.prior, cond), {cond: m[1]}); + continue; + } + if (code === 'else') { + top.ctrl.push(st); + if (top.branch !== 'opaque') { + top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; + } + continue; + } + } + if (/^end\b/.test(code) && top != null) { + frames.pop(); + // An evaluated condition leaves no control lines behind. + if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { + for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); + blank(st); + } continue; } - const arr = rhs.match(/^\[([^\]]*)\]$/); - if (arr != null) { - const items = []; - for (const it of arr[1].matchAll(/"([^"]*)"|'([^']*)'/g)) { - items.push({value: it[1] ?? it[2], dq: it[1] != null}); + const opensBlock = + !oneLine && + (/^(?:case|begin|while|until|for|def|class|module)\b/.test(code) || + /\bdo(?:\s*\|[^|]*\|)?\s*$/.test(code) || + /=\s*(?:if|unless|case|begin)\b/.test(code)); + if (opensBlock) { + // The spec's and its subspecs' blocks run; any other is opaque. + const spec = code.match(/Pod::Spec\.new\s+do\s*\|\s*(\w+)\s*\|\s*$/); + const sub = code.match( + /^(\w+)\.subspec\s[\s\S]*\bdo\s*\|\s*(\w+)\s*\|\s*$/, + ); + const recv = + spec?.[1] ?? (sub != null && recvs.has(sub[1]) ? sub[2] : null); + if (recv != null) recvs.add(recv); + const assigned = code.match(/^([A-Za-z_]\w*)\s*=/); + if (assigned != null) { + setLocal(assigned[1], null, {state: 'opaque', why: code}); } - arrays.set(name, items); + frames.push({kind: 'block', opaque: recv == null, code}); + if (act.state === 'no') blank(st); + continue; } - } - if (strings.size === 0 && arrays.size === 0) return content; - const interpolate = (text /*: string */) => - text.replace(/#\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g, (whole, id) => - strings.has(id) ? (strings.get(id) /*: any */) : whole, + if (act.state === 'no') { + blank(st); + continue; + } + // A trailing `if`/`unless` modifier. + let core = code; + let stAct = act; + const mod = modifierIndex(code); + if (mod != null) { + core = code.slice(0, mod.at).trim(); + const cond = code.slice(mod.at + mod.kw.length).trim(); + const c = + act.state === 'yes' ? condOf(cond, mod.kw === 'unless') : act.state; + if (c === 'no') { + blank(st); + continue; + } + if (c === 'maybe' && act.state === 'yes') { + stAct = {state: 'maybe', why: cond}; + } + } + // `recv.field = expr` on the spec or a subspec. Under a condition it + // cannot evaluate, or in a block it does not run, it is read as if it ran, + // as the field regexes always did: a literal stays as written, an + // expression is evaluated or, in a source glob, refused. + const field = core.match( + /^([A-Za-z_]\w*)(?:\.([a-z]+))?\.([a-z_]+)\s*=(?![=~>])\s*([\s\S]+)$/, ); - // Constants may be built from earlier ones: resolve the arrays' items too - // (double-quoted items only). - const arrayValues /*: Map> */ = new Map(); - for (const [k, v] of arrays) { - arrayValues.set(k, v.map(i => (i.dq ? interpolate(i.value) : i.value))); - } - // Only double-quoted string literals interpolate; scan literal by literal - // (a line never spans a string here) so `'ios/*.#{x}'` stays as written. - const interpolated = content.replace( - /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, - lit => (lit[0] === '"' ? interpolate(lit) : lit), - ); - const quote = (v /*: string */) => JSON.stringify(v); - return interpolated.replace( - /^(\s*[A-Za-z_]\w*(?:\.(?:ios|osx|tvos|visionos|watchos))?\.[A-Za-z_]+\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)[ \t]*$/gm, - (whole, lhs, id) => { - if (strings.has(id)) return lhs + quote((strings.get(id) /*: any */)); - if (arrayValues.has(id)) { - return ( - lhs + '[' + (arrayValues.get(id) /*: any */).map(quote).join(', ') + ']' + if ( + field != null && + recvs.has(field[1]) && + (field[2] == null || PLATFORM_SCOPES.has(field[2])) + ) { + const [, recv, scope, name, rhs] = field; + // Only the spec's own and its `ios` scope count. + if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; + const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; + const v = evalRubyExpr(rhs, env, true); + const lit = isUnresolved(v) ? null : rubyLiteral(v); + if (lit != null) { + blank(st); + const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; + out[st.start] = `${indent}${lhs} = ${lit}`; + } else if (STRICT_FIELDS.has(name)) { + unresolved.push({ + field: lhs, + expr: rhs.trim(), + why: isUnresolved(v) + ? `it uses ${(v /*: any */).why}` + : 'its value is not a string or an array of strings', + }); + } else { + interpolate(st, /^\{/.test(rhs.trim())); + } + continue; + } + // `name = expr`, `name += expr`, `name ||= expr`. + const assign = core.match( + /^([A-Za-z_]\w*)\s*(\+=|\|\|=|=)(?![=~>])\s*([\s\S]+)$/, + ); + if (assign != null && !recvs.has(assign[1])) { + const [, name, op, rhs] = assign; + let v = evalRubyExpr(rhs, env); + if (op !== '=' && !isUnresolved(v)) { + const vars = new Map([ + ['old', env.has(name) ? env.get(name) : null], + ['new', v], + ]); + v = evalRubyExpr(op === '+=' ? 'old + new' : 'old || new', vars); + } + if (isUnresolved(v)) { + v = new RubyUnresolved( + `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + + `(${(v /*: any */).why})`, ); } - return whole; - }, - ); + setLocal(name, v, stAct); + interpolate(st, false); + continue; + } + // `name.push(...)`, `name << x`; any other change to a local makes it + // unknown. + const change = core.match(/^([A-Za-z_]\w*)\s*(?:\.|\[|<<)/); + if (change != null && env.has(change[1]) && !recvs.has(change[1])) { + const name = change[1]; + const old = env.get(name); + const add = + core.match(/^\w+\s*\.(push|append|concat)\s*\(([\s\S]*)\)$/) ?? + core.match(/^\w+\s*\.(push|append|concat)\s+([\s\S]+)$/) ?? + core.match(/^\w+\s*(<<)\s*([\s\S]+)$/); + let v /*: mixed */ = new RubyUnresolved( + `is changed by \`${core}\`, which the reader cannot evaluate`, + ); + if (add != null && Array.isArray(old)) { + // `<<` adds one value; push/append/concat take a list. + const args = evalRubyExpr( + add[1] === '<<' ? `[(${add[2]})]` : `[${add[2]}]`, + env, + ); + if (Array.isArray(args)) { + if (add[1] !== 'concat') v = [...old, ...args]; + else if (args.every(Array.isArray)) v = [...old, ...args.flat()]; + } + } + setLocal(name, v, stAct); + continue; + } + interpolate(st, false); + } + return {text: out.join('\n'), unresolved}; } // The library's own version. Podspecs load the package.json next to them @@ -307,8 +1037,10 @@ function resolvePackageVersion( // Comment-only lines are dropped so a commented-out `# s.header_dir` cannot win // over the live one. A trailing `#` and a `#` inside a string survive: only the // first non-whitespace character counts. -function readPodspecSource(podspecPath /*: string */) /*: string */ { - return resolveRubyConstants( +function readPodspecEvaluated( + podspecPath /*: string */, +) /*: {text: string, unresolved: Array} */ { + return evaluateRubyLocals( resolvePackageVersion( fs .readFileSync(podspecPath, 'utf8') @@ -319,6 +1051,9 @@ function readPodspecSource(podspecPath /*: string */) /*: string */ { ), ); } +function readPodspecSource(podspecPath /*: string */) /*: string */ { + return readPodspecEvaluated(podspecPath).text; +} // The main spec's block variable: `Pod::Spec.new do |podspec|` -> `podspec`. // Falls back to the two conventional names when the header is not found. @@ -447,7 +1182,7 @@ function regexPodspec( podspecPath /*: string */, opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, ) /*: RawSpec */ { - const content = readPodspecSource(podspecPath); + const {text: content, unresolved} = readPodspecEvaluated(podspecPath); const dropped = new Set(opts?.dropSubspecs ?? []); const mainName = mainReceiverName(content); const MAIN_RECV = mainRecvPattern(mainName); @@ -811,6 +1546,7 @@ function regexPodspec( ), __regex_partial__: true, __warnings__: warnings, + __unresolved__: unresolved, }; } @@ -1384,9 +2120,40 @@ function flattenSubspecs( partial, // Default: overridden in readPodspec, which can see the podspec source. usesInstallModulesDependencies: false, + // $FlowFixMe[incompatible-type] runtime-validated dynamic shape + unresolvedSources: Array.isArray(rawSpec.__unresolved__) + ? rawSpec.__unresolved__ + : [], }; } +/** + * Why the podspec's source globs cannot be scaffolded, or null: each + * `source_files`/`exclude_files` value the regex path could not evaluate. A + * glob read in part gives a target that builds without some of the library's + * files (react-native-screens 4.24.0 lost all of ios/, and the app crashed at + * start), so the scaffolder refuses the library instead. Other callers (name + * resolution, header search paths) keep reading the model as before. + */ +function unresolvedSourcesReason( + podspecPath /*: string */, + model /*: PodspecModel */, +) /*: ?string */ { + const list /*: Array */ = model.unresolvedSources ?? []; + if (list.length === 0) return null; + return ( + `${podspecPath}: ` + + list + .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) + .join('; ') + + '. The podspec reader evaluates locals, string interpolation, arrays, ' + + "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + + 'the globs it could read would leave some of the library\'s files out of ' + + 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + + 'reads the podspec, or give the library a Package.swift of its own.' + ); +} + // --------------------------------------------------------------------------- // Top-level entry // --------------------------------------------------------------------------- @@ -1552,4 +2319,5 @@ module.exports = { runPodIpcSpec, regexPodspec, flattenSubspecs, + unresolvedSourcesReason, }; diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index a8076ae..341c374 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -45,7 +45,11 @@ const { } = require('./expand-spm-dependencies'); const {expandSpmSourceGlobs} = require('./generate-spm-autolinking'); const {MIN_IOS_VERSION_SUPPORTED} = require('./ios-deployment-target'); -const {findPodspecs, readPodspecCached} = require('./read-podspec'); +const { + findPodspecs, + readPodspecCached, + unresolvedSourcesReason, +} = require('./read-podspec'); const { REACT_CODEGEN_PACKAGE_NAME, REACT_CODEGEN_PRODUCTS, @@ -2280,6 +2284,12 @@ function scaffoldPackageSwiftForDep( reason: `Podspec read failed: ${e.message}`, }; } + // A source glob the podspec reader could not evaluate: a target built from + // the rest would lack some of the library's files. + const unresolved = unresolvedSourcesReason(podspecPath, model); + if (unresolved != null) { + return {depName, status: 'error', reason: unresolved}; + } const spec = translatePodspecToSpmTarget( model, diff --git a/vendor/rn-spm/spm/spm-types.js b/vendor/rn-spm/spm/spm-types.js index 73dc6c8..6ce647d 100644 --- a/vendor/rn-spm/spm/spm-types.js +++ b/vendor/rn-spm/spm/spm-types.js @@ -471,6 +471,10 @@ export type PodspecModel = { // flag as an implicit React-core dependency (a plain ObjC module using the // helper has no `codegenConfig` to key off). usesInstallModulesDependencies: boolean, + // The `source_files`/`exclude_files` values the regex fallback could not + // evaluate (a method call, an unknown local): the scaffolder refuses the + // library rather than build it from a partial source list. + unresolvedSources?: Array<{field: string, expr: string, why: string}>, }; // Intermediate translation result — concrete data the Swift emitter consumes. From b7f841cce4e65ea1cac3bb2af5ae8774b85fcf75 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 21:06:17 -0600 Subject: [PATCH 11/16] chore: bump the scaffold revision to 6 --- patches/react-native+0.88.0.patch | 73 ++++++++++--------- patches/react-native+0.88.1.patch | 73 ++++++++++--------- src/pipeline/patches.ts | 2 +- tests/capabilities.test.ts | 2 +- .../datetimepicker/Package.swift | 2 +- .../Package.swift | 2 +- .../react-native-pager-view/Package.swift | 2 +- .../Package@swift-6.5.swift | 2 +- .../react-native-screens/Package.swift | 2 +- .../react-native-svg/Package.swift | 2 +- .../react-native-webview/Package.swift | 2 +- tests/patches.test.ts | 52 +++++++------ tests/rn-scaffolder.test.ts | 18 ++--- vendor/rn-spm/spm/scaffold-package-swift.js | 5 +- 14 files changed, 126 insertions(+), 113 deletions(-) diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index 1d117a6..2cf5960 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1959,7 +1959,7 @@ index 8fcf04b..6ed3f14 100644 + unresolvedSourcesReason, }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..341c374 100644 +index cf7e587..c19356d 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -45,7 +45,11 @@ const { @@ -1983,7 +1983,7 @@ index cf7e587..341c374 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +118,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,279 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -2000,7 +2000,10 @@ index cf7e587..341c374 100644 +// bare spelling; and Swift compilation conditions. Revision 5: pod header +// forwarders that `#import` the pod's public headers instead of `@import`ing +// its modules, which stopped every Objective-C++ file that included them. -+const RN_XTOOL_SCAFFOLD_REVISION = 5; ++// Revision 6 (fix 28): source globs built from Ruby locals and conditions ++// (react-native-screens 4.24.0 had no ios/ sources), and the branches a ++// condition rules out left out of the target. ++const RN_XTOOL_SCAFFOLD_REVISION = 6; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -2260,7 +2263,7 @@ index cf7e587..341c374 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +420,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +423,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -2634,7 +2637,7 @@ index cf7e587..341c374 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +809,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +812,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -2663,7 +2666,7 @@ index cf7e587..341c374 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +907,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +910,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -2676,7 +2679,7 @@ index cf7e587..341c374 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +987,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +990,92 @@ function translatePodspecToSpmTarget( } } @@ -2797,7 +2800,7 @@ index cf7e587..341c374 100644 } } -@@ -427,15 +1138,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1141,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2855,7 +2858,7 @@ index cf7e587..341c374 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1248,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1251,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2907,7 +2910,7 @@ index cf7e587..341c374 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1314,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1317,101 @@ function translatePodspecToSpmTarget( ); } @@ -3009,7 +3012,7 @@ index cf7e587..341c374 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1417,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1420,201 @@ function translatePodspecToSpmTarget( } } @@ -3213,7 +3216,7 @@ index cf7e587..341c374 100644 warnings, }; } -@@ -565,6 +1636,9 @@ type EmitContext = { +@@ -565,6 +1639,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -3223,7 +3226,7 @@ index cf7e587..341c374 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1703,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1706,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -3250,7 +3253,7 @@ index cf7e587..341c374 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1812,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1815,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -3283,7 +3286,7 @@ index cf7e587..341c374 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1855,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1858,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -3295,7 +3298,7 @@ index cf7e587..341c374 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1875,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1878,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -3369,7 +3372,7 @@ index cf7e587..341c374 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1950,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1953,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -3378,7 +3381,7 @@ index cf7e587..341c374 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1960,13 @@ let package = Package( +@@ -778,13 +1963,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -3395,7 +3398,7 @@ index cf7e587..341c374 100644 ) `; } -@@ -844,6 +2026,61 @@ function reportSwiftName( +@@ -844,6 +2029,61 @@ function reportSwiftName( } } @@ -3457,7 +3460,7 @@ index cf7e587..341c374 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2193,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -3470,7 +3473,7 @@ index cf7e587..341c374 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2214,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -3479,7 +3482,7 @@ index cf7e587..341c374 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2242,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -3524,7 +3527,7 @@ index cf7e587..341c374 100644 } catch (e) { return { depName, -@@ -1008,39 +2284,27 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2287,27 @@ function scaffoldPackageSwiftForDep( reason: `Podspec read failed: ${e.message}`, }; } @@ -3579,7 +3582,7 @@ index cf7e587..341c374 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2336,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2339,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -3587,7 +3590,7 @@ index cf7e587..341c374 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2346,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2349,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -3627,7 +3630,7 @@ index cf7e587..341c374 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2385,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2388,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -3728,7 +3731,7 @@ index cf7e587..341c374 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2484,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2487,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -3741,7 +3744,7 @@ index cf7e587..341c374 100644 return { depName, -@@ -1128,6 +2498,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2501,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -3749,7 +3752,7 @@ index cf7e587..341c374 100644 }; } -@@ -1141,7 +2512,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2515,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -3758,7 +3761,7 @@ index cf7e587..341c374 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2533,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2536,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -3767,7 +3770,7 @@ index cf7e587..341c374 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2665,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2668,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -3779,7 +3782,7 @@ index cf7e587..341c374 100644 }; */ -@@ -1323,6 +2699,17 @@ function scaffoldAll( +@@ -1323,6 +2702,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -3797,7 +3800,7 @@ index cf7e587..341c374 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2717,23 @@ function scaffoldAll( +@@ -1330,24 +2720,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -3833,7 +3836,7 @@ index cf7e587..341c374 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2772,9 @@ function scaffoldAll( +@@ -1386,6 +2775,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3843,7 +3846,7 @@ index cf7e587..341c374 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2793,9 @@ function scaffoldAll( +@@ -1404,6 +2796,9 @@ function scaffoldAll( } module.exports = { diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index 1d117a6..2cf5960 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1959,7 +1959,7 @@ index 8fcf04b..6ed3f14 100644 + unresolvedSourcesReason, }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..341c374 100644 +index cf7e587..c19356d 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -45,7 +45,11 @@ const { @@ -1983,7 +1983,7 @@ index cf7e587..341c374 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +118,276 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,279 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -2000,7 +2000,10 @@ index cf7e587..341c374 100644 +// bare spelling; and Swift compilation conditions. Revision 5: pod header +// forwarders that `#import` the pod's public headers instead of `@import`ing +// its modules, which stopped every Objective-C++ file that included them. -+const RN_XTOOL_SCAFFOLD_REVISION = 5; ++// Revision 6 (fix 28): source globs built from Ruby locals and conditions ++// (react-native-screens 4.24.0 had no ios/ sources), and the branches a ++// condition rules out left out of the target. ++const RN_XTOOL_SCAFFOLD_REVISION = 6; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -2260,7 +2263,7 @@ index cf7e587..341c374 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +420,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +423,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -2634,7 +2637,7 @@ index cf7e587..341c374 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +809,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +812,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -2663,7 +2666,7 @@ index cf7e587..341c374 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +907,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +910,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -2676,7 +2679,7 @@ index cf7e587..341c374 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +987,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +990,92 @@ function translatePodspecToSpmTarget( } } @@ -2797,7 +2800,7 @@ index cf7e587..341c374 100644 } } -@@ -427,15 +1138,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1141,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -2855,7 +2858,7 @@ index cf7e587..341c374 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1248,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1251,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -2907,7 +2910,7 @@ index cf7e587..341c374 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1314,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1317,101 @@ function translatePodspecToSpmTarget( ); } @@ -3009,7 +3012,7 @@ index cf7e587..341c374 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1417,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1420,201 @@ function translatePodspecToSpmTarget( } } @@ -3213,7 +3216,7 @@ index cf7e587..341c374 100644 warnings, }; } -@@ -565,6 +1636,9 @@ type EmitContext = { +@@ -565,6 +1639,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -3223,7 +3226,7 @@ index cf7e587..341c374 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1703,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1706,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -3250,7 +3253,7 @@ index cf7e587..341c374 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1812,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1815,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -3283,7 +3286,7 @@ index cf7e587..341c374 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1855,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1858,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -3295,7 +3298,7 @@ index cf7e587..341c374 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1875,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1878,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -3369,7 +3372,7 @@ index cf7e587..341c374 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1950,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1953,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -3378,7 +3381,7 @@ index cf7e587..341c374 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1960,13 @@ let package = Package( +@@ -778,13 +1963,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -3395,7 +3398,7 @@ index cf7e587..341c374 100644 ) `; } -@@ -844,6 +2026,61 @@ function reportSwiftName( +@@ -844,6 +2029,61 @@ function reportSwiftName( } } @@ -3457,7 +3460,7 @@ index cf7e587..341c374 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2190,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2193,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -3470,7 +3473,7 @@ index cf7e587..341c374 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2211,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2214,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -3479,7 +3482,7 @@ index cf7e587..341c374 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2239,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2242,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -3524,7 +3527,7 @@ index cf7e587..341c374 100644 } catch (e) { return { depName, -@@ -1008,39 +2284,27 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2287,27 @@ function scaffoldPackageSwiftForDep( reason: `Podspec read failed: ${e.message}`, }; } @@ -3579,7 +3582,7 @@ index cf7e587..341c374 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2336,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2339,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -3587,7 +3590,7 @@ index cf7e587..341c374 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2346,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2349,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -3627,7 +3630,7 @@ index cf7e587..341c374 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2385,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2388,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -3728,7 +3731,7 @@ index cf7e587..341c374 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2484,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2487,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -3741,7 +3744,7 @@ index cf7e587..341c374 100644 return { depName, -@@ -1128,6 +2498,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2501,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -3749,7 +3752,7 @@ index cf7e587..341c374 100644 }; } -@@ -1141,7 +2512,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2515,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -3758,7 +3761,7 @@ index cf7e587..341c374 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2533,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2536,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -3767,7 +3770,7 @@ index cf7e587..341c374 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2665,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2668,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -3779,7 +3782,7 @@ index cf7e587..341c374 100644 }; */ -@@ -1323,6 +2699,17 @@ function scaffoldAll( +@@ -1323,6 +2702,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -3797,7 +3800,7 @@ index cf7e587..341c374 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2717,23 @@ function scaffoldAll( +@@ -1330,24 +2720,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -3833,7 +3836,7 @@ index cf7e587..341c374 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2772,9 @@ function scaffoldAll( +@@ -1386,6 +2775,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -3843,7 +3846,7 @@ index cf7e587..341c374 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2793,9 @@ function scaffoldAll( +@@ -1404,6 +2796,9 @@ function scaffoldAll( } module.exports = { diff --git a/src/pipeline/patches.ts b/src/pipeline/patches.ts index 40d813a..adeba7c 100644 --- a/src/pipeline/patches.ts +++ b/src/pipeline/patches.ts @@ -359,7 +359,7 @@ const SLOT_LABEL_RE = /^\+\/\/ Cache slot: (\S+)\/dual-flavor\s*$/m; const REVISION_RE = /^\+\/\/ (?:rn|expo)-xtool-scaffold-revision: (\d+)\s*$/m; /** The scaffolder's RN_XTOOL_SCAFFOLD_REVISION (patches/react-native+0.88.{0,1}.patch and vendor/rn-spm). */ -export const SCAFFOLD_REVISION = 5; +export const SCAFFOLD_REVISION = 6; const PATCH_PODS_RE = /^\+\/\/ rn-xtool-pods: (.*?)\s*$/m; const MANIFEST_PODS_RE = /^\/\/ rn-xtool-pods: (.*?)\s*$/m; diff --git a/tests/capabilities.test.ts b/tests/capabilities.test.ts index e2b7bab..a2db48b 100644 --- a/tests/capabilities.test.ts +++ b/tests/capabilities.test.ts @@ -605,7 +605,7 @@ describe("detectCapabilities", () => { }); const lines = [ "// AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package.", - "// rn-xtool-scaffold-revision: 5", + "// rn-xtool-scaffold-revision: 6", "// rn-xtool-pods: AppAuth=3.0.0", "// Cache slot: 0.88.1/dual-flavor", ]; diff --git a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift index fe8832e..480f6f3 100644 --- a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift +++ b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["ios","ios/fabric","ios/fabric/cpp/react/renderer/components/RNDateTimePicker","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift index 8a94b2f..bac444b 100644 --- a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["apple/Handlers","apple","shared/runtime","shared/shadowNodes/react/renderer/components/rngesturehandler_codegen","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift index efafa95..2db17bd 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.4;(experimentalMultiLang) // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift index 3a221f3..e03f505 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.5 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift index df191ac..ed24bb1 100644 --- a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["common/cpp","common/cpp/react/renderer/components/rnscreens","common/cpp/react/renderer/components/rnscreens/utils","cpp","ios","ios/bridging","ios/conversion","ios/events","ios/helpers/container","ios/helpers/image","ios/helpers/scroll-view","ios/integrations","ios/safe-area","ios/stubs","ios/tabs","ios/tabs/bottom-accessory","ios/tabs/extensions","ios/tabs/host","ios/tabs/screen","ios/utils","ios/utils/extensions",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift index d7c72b8..b817f81 100644 --- a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["common/cpp","apple/Brushes","apple/Elements","apple/Filters/MetalCI","apple/Filters","apple","apple/Shapes","apple/Text","apple/Utils","apple/ViewManagers","common/cpp/react/renderer/components/rnsvg",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift index c68d3c5..6907046 100644 --- a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 5 +// rn-xtool-scaffold-revision: 6 // rn-xtool-swift-importer-paths: ["apple","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/patches.test.ts b/tests/patches.test.ts index 9b3fa33..7028350 100644 --- a/tests/patches.test.ts +++ b/tests/patches.test.ts @@ -916,7 +916,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "@scope+lib+1.0.0.patch"), scaffoldPatch(null, 1)); // Revision 2 wrote no importer paths for a clang-only target. await writeFile(path.join(root, "patches", "react-native-screens+4.30.1.patch"), scaffoldPatch("0.87.1", 2)); - await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 5)); + await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 6)); // Both stale: the slot warning wins, one line per patch. await writeFile(path.join(root, "patches", "react-native-safe-area-context+5.6.0.patch"), scaffoldPatch("0.86.3", 1)); await installPkg(root, "react-native-screens"); @@ -924,15 +924,15 @@ describe("scaffold patches from another React Native version", () => { await installPkg(root, "react-native-svg"); await installPkg(root, "react-native-safe-area-context"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it so rn-xtool " + + "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it so rn-xtool " + "regenerates it (also remove node_modules/@scope/lib and reinstall: that copy still has the old Package.swift)", "⚠ patches/react-native-safe-area-context+5.6.0.patch was scaffolded for React Native 0.86.3; delete it so rn-xtool " + "regenerates it for 0.87.1 (also remove node_modules/react-native-safe-area-context and reinstall: that copy still has " + "the old Package.swift)", - "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it so " + + "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", - "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 5); delete it so " + + "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 6); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -945,7 +945,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.88.1", 3)); await installPkg(root, "react-native-svg"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 5); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 6); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -963,7 +963,7 @@ describe("scaffold patches from another React Native version", () => { expect(scaffoldPatchWarnings(root)).toEqual([ "⚠ patches/react-native-screens+4.30.0.patch was scaffolded for React Native 0.88.0; delete it so rn-xtool regenerates " + "it for 0.88.1 (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)", - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 5); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -1038,7 +1038,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("replaces an older node_modules copy of a current persisted patch (a teammate's pull)", async () => { const root = await project(); await installPkg(root, "react-native-screens", "4.30.0"); - const current = { "Package.swift": manifest(5, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; + const current = { "Package.swift": manifest(6, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; await put(root, "patches/react-native-screens+4.30.0.patch", newFilesPatch("react-native-screens", current)); // What the old patch left in node_modules: revision 1, slot 0.86.3, a stub the new scaffold no longer writes. await put(root, "node_modules/react-native-screens/Package.swift", manifest(1, "0.86.3")); @@ -1051,7 +1051,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(existsSync(path.join(root, "node_modules/react-native-screens/include/rnscreens/Gone.h"))).toBe(true); expect(lines).toEqual([ "ℹ node_modules/react-native-screens/Package.swift was scaffolded with revision 1 for React Native 0.86.3, " + - "older than patches/react-native-screens+4.30.0.patch (revision 5, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-screens+4.30.0.patch (revision 6, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); // Idempotent: the next build changes nothing. @@ -1067,7 +1067,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the const forwarder = "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the public headers of the pod AppAuth.\n" + "#import \n#import \n"; - const current = { "Package.swift": manifest(5, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; + const current = { "Package.swift": manifest(6, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; await put(root, "patches/react-native-app-auth+8.5.1.patch", newFilesPatch("react-native-app-auth", current)); await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(3, "0.87.1")); await put(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h", forwarder); @@ -1077,7 +1077,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h")).toBe(forwarder); expect(lines).toEqual([ "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded with revision 3 for React Native 0.87.1, " + - "older than patches/react-native-app-auth+8.5.1.patch (revision 5, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-app-auth+8.5.1.patch (revision 6, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); }, 30_000); @@ -1100,7 +1100,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the " line 3", "", ].join("\n"); - await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(5, "0.87.1") }) + fix); + await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(6, "0.87.1") }) + fix); await put(root, "node_modules/lib/Package.swift", manifest(1, "0.86.3")); await put(root, "node_modules/lib/ios/Foo.m", "line 1\nnew\nline 3\n"); for (const run of [1, 2]) { @@ -1109,7 +1109,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/lib/Package.swift"), `run ${run}`).toBe(manifest(1, "0.86.3")); expect(lines, `run ${run}`).toEqual([ "⚠ node_modules/lib/Package.swift was scaffolded with revision 1 for React Native 0.86.3, older than " + - "patches/lib+1.0.0.patch (revision 5, React Native 0.87.1), and that patch also changes the library's own " + + "patches/lib+1.0.0.patch (revision 6, React Native 0.87.1), and that patch also changes the library's own " + "files, so rn-xtool does not replace it: run rm -rf node_modules/lib && npm install, then build again", ]); } @@ -1118,14 +1118,14 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("treats the pre-rename marker in node_modules as an older revision", async () => { const root = await project(); await installPkg(root, "react-native-svg", "15.16.0"); - await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(5, "0.87.1") })); + await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(6, "0.87.1") })); await put(root, "node_modules/react-native-svg/Package.swift", manifest(1, "0.87.1", "expo-xtool-scaffold-revision")); const lines: string[] = []; await applyPatches(root, undefined, { ...noBundled, log: (l) => lines.push(l) }); - expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(5, "0.87.1")); + expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(6, "0.87.1")); expect(lines).toEqual([ "ℹ node_modules/react-native-svg/Package.swift was scaffolded with revision 1 for React Native 0.87.1, older than " + - "patches/react-native-svg+15.16.0.patch (revision 5, React Native 0.87.1): rn-xtool replaced it with the " + + "patches/react-native-svg+15.16.0.patch (revision 6, React Native 0.87.1): rn-xtool replaced it with the " + "persisted one", ]); }, 30_000); @@ -1133,32 +1133,36 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("removes a stale scaffold with no persisted patch, so the rn-spm step scaffolds it again", async () => { const root = await project(); await put(root, "node_modules/react-native-webview/Package.swift", manifest(2, "0.87.1")); - await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(5, "0.86.3")); + await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(6, "0.86.3")); await put(root, "node_modules/legacy-lib/Package.swift", manifest(1, null, "expo-xtool-scaffold-revision")); // Revision 4 (0.1.0-alpha.6) wrote pod header forwarders with @import, which Objective-C++ cannot compile. await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(4, "0.87.1")); + // Revision 5 read the source globs react-native-screens 4.24.0 builds from Ruby locals as empty. + await put(root, "node_modules/react-native-screens/Package.swift", manifest(5, "0.87.1")); const lines: string[] = []; await applyPatches(root, async () => ({ exitCode: 0 }), { ...noBundled, log: (l) => lines.push(l) }); - for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib", "react-native-app-auth"]) { + for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib", "react-native-app-auth", "react-native-screens"]) { expect(existsSync(path.join(root, "node_modules", pkg, "Package.swift")), pkg).toBe(false); } expect(lines).toEqual([ "ℹ node_modules/@react-native-community/datetimepicker/Package.swift was scaffolded for React Native 0.86.3, not " + "0.87.1: rn-xtool removed it so the rn-spm step scaffolds it again", - "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 5): " + + "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 6): " + "rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 4, now " + - "5): rn-xtool removed it so the rn-spm step scaffolds it again", + "6): rn-xtool removed it so the rn-spm step scaffolds it again", + "ℹ node_modules/react-native-screens/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 5, now " + + "6): rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-webview/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 2, now " + - "5): rn-xtool removed it so the rn-spm step scaffolds it again", + "6): rn-xtool removed it so the rn-spm step scaffolds it again", ]); }); it("leaves current, foreign and stale-patch manifests alone", async () => { const root = await project(); const files: Record = { - // Current: revision 5 on the installed React Native. - "node_modules/current-lib/Package.swift": manifest(5, "0.87.1"), + // Current: revision 6 on the installed React Native. + "node_modules/current-lib/Package.swift": manifest(6, "0.87.1"), // Not rn-xtool's: the upstream scaffolder without rn-xtool's marker (a library may ship it), or hand-written. "node_modules/upstream-lib/Package.swift": manifest(0, null, null), "node_modules/own-lib/Package.swift": "// swift-tools-version: 6.0\nimport PackageDescription\n", @@ -1166,8 +1170,8 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the "node_modules/react-native-screens/Package.swift": manifest(1, "0.86.3"), "patches/react-native-screens+4.30.0.patch": newFilesPatch("react-native-screens", { "Package.swift": manifest(1, "0.86.3") }), // A current patch over a current copy. - "node_modules/react-native-svg/Package.swift": manifest(5, "0.87.1"), - "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(5, "0.87.1") }), + "node_modules/react-native-svg/Package.swift": manifest(6, "0.87.1"), + "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(6, "0.87.1") }), }; for (const [rel, text] of Object.entries(files)) await put(root, rel, text); for (const pkg of ["react-native-screens", "react-native-svg"]) await installPkg(root, pkg); diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 81de46e..1551a88 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -157,7 +157,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(src("read-podspec.js")).toContain("const RN_POD_ENV"); expect(src("read-podspec.js")).toContain("env: {...process.env, ...RN_POD_ENV}"); const f = src("scaffold-package-swift.js"); - expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 5"); + expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 6"); expect(f).toContain("rn-xtool-swift-importer-paths"); expect(f).toContain("function importsOwnSwiftHeader"); expect(f).toContain("function clangModuleExcludes"); @@ -1109,7 +1109,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () it("emits the rn-xtool-scaffold-revision marker next to AUTO-SCAFFOLDED-VERSION", () => { const pkg = readFileSync(path.join(fresh(), "Package.swift"), "utf8"); - expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 5$/m); + expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 6$/m); }); it("keeps a scaffold that carries the current marker", () => { @@ -1122,14 +1122,14 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () writeFileSync(file, readFileSync(file, "utf8").replace(/^\/\/ rn-xtool-scaffold-revision: \d+\n/m, "").replace("exact:", "from:")); expect(scaffoldAgain(root)).toBe("written"); const pkg = readFileSync(file, "utf8"); - expect(pkg).toContain("rn-xtool-scaffold-revision: 5"); + expect(pkg).toContain("rn-xtool-scaffold-revision: 6"); expect(pkg).toContain('exact: "1.5.0"'); }); it("regenerates a scaffold whose marker is lower than the current revision", () => { const root = fresh(); const file = path.join(root, "Package.swift"); - writeFileSync(file, readFileSync(file, "utf8").replace("revision: 5", "revision: 4")); + writeFileSync(file, readFileSync(file, "utf8").replace("revision: 6", "revision: 5")); expect(scaffoldAgain(root)).toBe("written"); }); }); @@ -1214,7 +1214,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { // Mixed (pager-view) or clang-only, each of these targets searches beyond its public headers path, so each // manifest records its importer paths right after the revision line. for (const k of manifests) { - expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); + expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); } expect(now.files).toEqual(golden.files); }, @@ -1315,7 +1315,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { it("17: records the Swift importer paths", () => { for (const manifest of ["Package.swift", "Package@swift-6.5.swift"]) { const pkg = file(`react-native-screens/${manifest}`); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("."); expect(paths).toContain("ios/bridging"); @@ -1330,7 +1330,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { expect(pkg.split("\n")[0]).toBe("// swift-tools-version: 6.0"); expect(files["react-native-screens/Package@swift-6.5.swift"]).toBeUndefined(); expect(pkg).toContain('publicHeadersPath: "ios",'); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("ios/utils"); expect(paths).toEqual(searchPaths(pkg)); @@ -2149,7 +2149,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { const pkg = manifest(scaffold(`${APPAUTH_DEP}\n s.dependency "SwiftUIIntrospect", '~> 1.0'`, table)); // Clang-only, searching beyond its public headers: after the importer-paths line. expect(pkg).toMatch( - /^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, + /^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, ); // Pure Swift (no importer-paths line): after the revision line. const swift = tempDir(); @@ -2161,7 +2161,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { `Pod::Spec.new do |s|\n s.name = "Foo"\n s.source_files = "ios/**/*.swift"\n${APPAUTH_DEP}\nend\n`, ); const swiftPkg = manifest(withTable(table, () => scaffoldLibraries(VENDORED_RN_SPM, { foo: swift }))); - expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 5\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); + expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); // No pinned pod, no line. expect(manifest(scaffold("", table))).not.toContain("rn-xtool-pods"); }); diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index 341c374..c19356d 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -131,7 +131,10 @@ const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; // bare spelling; and Swift compilation conditions. Revision 5: pod header // forwarders that `#import` the pod's public headers instead of `@import`ing // its modules, which stopped every Objective-C++ file that included them. -const RN_XTOOL_SCAFFOLD_REVISION = 5; +// Revision 6 (fix 28): source globs built from Ruby locals and conditions +// (react-native-screens 4.24.0 had no ios/ sources), and the branches a +// condition rules out left out of the target. +const RN_XTOOL_SCAFFOLD_REVISION = 6; const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; // An importer (Swift, or a Clang module) builds the target's module from its From e1f56a071f986df0be6f21e14d0589780719e0ba Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 21:13:56 -0600 Subject: [PATCH 12/16] fix: check codegen classes in the packed app --- docs/troubleshooting.md | 44 ++++++++ src/commands/build.ts | 8 ++ src/commands/install.ts | 30 ++++- src/pipeline/codegenClasses.ts | 201 +++++++++++++++++++++++++++++++++ src/pods/postPack.ts | 12 +- tests/build.test.ts | 26 +++++ tests/codegenClasses.test.ts | 183 ++++++++++++++++++++++++++++++ tests/install.test.ts | 26 +++++ 8 files changed, 520 insertions(+), 10 deletions(-) create mode 100644 src/pipeline/codegenClasses.ts create mode 100644 tests/codegenClasses.test.ts diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ac3d397..480ea2e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -1022,6 +1022,50 @@ the `Package.swift` of every other library, persisted in `patches/` or edited by unavailable. When every resource named is a privacy manifest, the line ends "Development builds run without them; privacy manifests are read only at App Store submission." instead; there is nothing to do for a development build. +### `RCTThirdPartyComponentsProvider thirdPartyFabricComponents` + +An app that crashes at start with `NSInvalidArgumentException` in `+[RCTThirdPartyComponentsProvider +thirdPartyFabricComponents]` (`-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil +object`) lacks the class of a third-party Fabric component. React Native's codegen writes a dictionary of +`NSClassFromString(@"")` for every component the autolinked libraries declare, and one class missing from the +app is a nil value that stops it. The build itself succeeded: the library's target compiled without the files that +define its classes. + +`build` checks for it after `xtool-build`, and `install` (with `run`) checks the app xtool builds again before it +installs it: every class named in `ios/build/generated/ios/ReactCodegen/RCTThirdPartyComponentsProvider.mm` and +`RCTModuleProviders.mm` must be defined in the App binary or in a framework under `App.app/Frameworks`. When one is +not, rn-xtool removes the packed app and its `.ipa`, installs nothing and stops: + +``` +React Native's codegen names classes the packed app does not define, so rn-xtool removed it and does not install it: + - RNSFullWindowOverlay (component RNSFullWindowOverlay, react-native-screens) + - RNSModalScreen (component RNSModalScreen, react-native-screens) + … + - and 12 more +With a component class missing, the app would crash at start: +[RCTThirdPartyComponentsProvider thirdPartyFabricComponents] throws NSInvalidArgumentException (-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object). +Check the sources of node_modules/react-native-screens/Package.swift: its target was built without the files that define them. A scaffold persisted in patches/ by an older rn-xtool can be the cause: delete that patch, reinstall the library and build again. +``` + +Each line names the class, the component (or module) and the library that declares it, from the provider file or the +library's `codegenConfig`, else "a library". A missing module provider class does not crash the app: the message says +`With a module class missing, React Native logs "Module provider cannot be found in the runtime" and the +module is unavailable.` + +- **react-native-screens 4.24.0 scaffolded by an older rn-xtool:** its podspec builds `source_files` from Ruby locals + and conditions, which the podspec reader did not evaluate before scaffolder revision 6, so the scaffolded `RNScreens` + target held only the C++ of its `common` subspec ([fix 28](upstream/react-native-scaffolder.md)). The revision + warning above names its persisted patch; re-scaffold it as in [Scaffolded libraries](#scaffolded-libraries). +- **A podspec the reader cannot evaluate** stops the scaffold instead of building such a target: ``✖ Scaffolding + failed: : `s.source_files = ` cannot be evaluated: it uses . …``. The reader + evaluates locals, string interpolation, arrays, `ENV['…']`, comparisons, ternaries and `if`/`unless` blocks + ([how it works](how-it-works.md#cocoapods-only-libraries)); a method call or a value it does not know in a source + glob is refused. Installing CocoaPods (`gem install cocoapods`) lets `pod ipc spec` read the podspec instead, or give + the library a `Package.swift` of its own. +- **A hand-edited `Package.swift`** that leaves out the files defining a class: put them back. +- **"ℹ The packed app's binaries list no Objective-C class symbols, so rn-xtool could not check the classes React + Native's codegen providers name.":** the binaries have no symbol table, so nothing is checked and the build goes on. + xtool's debug builds keep their symbols; if you see this line, [report it](#reporting-a-problem). + ## Newer than the verified versions Each supported line has a floor: the oldest version rn-xtool accepts. A newer patch of the line builds, with a diff --git a/src/commands/build.ts b/src/commands/build.ts index f8df93f..e5b29e2 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -55,6 +55,7 @@ import { emptyTargetsOf } from "../pods/emptyTargets.js"; import { PODS_LOCK } from "../pods/lock.js"; import type { PodRoot } from "../pods/resolve.js"; import { postPackChecks, postPackPods, type PostPackPods } from "../pods/postPack.js"; +import { checkCodegenClasses } from "../pipeline/codegenClasses.js"; import { stagePodBinaries, type StagedPods } from "../pods/stage.js"; import { runPodsStep, type PodsStepDeps, type PodsStepResult } from "../pods/step.js"; @@ -220,6 +221,11 @@ export interface BuildDeps { stagePods: (paths: ProjectPaths, result: PodsStepResult) => Promise; /** After xtool-build, with binary pods: the packed app's bundles, frameworks and force-loaded classes (spec goal 7). */ postPack: (appBundle: string, pods: PostPackPods) => Promise; + /** + * After xtool-build: every class React Native's codegen providers name is in the packed app; the lines to print, or + * a throw after removing the app (src/pipeline/codegenClasses.ts). + */ + codegenClasses: (root: string, appBundle: string) => Promise; /** The app's CODE_SIGN_ENTITLEMENTS file (Debug); throws an EntitlementsError when xtool could not sign with it. */ readEntitlements: (project: ProjectInfo, iosDir: string) => AppEntitlements | undefined; log: (s: string) => void; @@ -263,6 +269,7 @@ const realDeps: BuildDeps = { pods: (root, roots, table, opts) => runPodsStep(root, roots, table, opts), stagePods: (paths, result) => stagePodBinaries(paths, result), postPack: (appBundle, pods) => postPackChecks(appBundle, pods, makeNmRunner()), + codegenClasses: (root, appBundle) => checkCodegenClasses(root, appBundle, makeNmRunner()), emptyTargets: (root, opts) => { const table = mergedPodTable(opts.pods); return emptyTargetsOf(table, [...scaffoldedPods(root, table, opts).values()].flat()); @@ -586,5 +593,6 @@ export async function build( await step("xtool-build", () => d.devBuild(d.xtoolBin(config), paths.iosXtool)); // A failure leaves the state without the fingerprint, so the next run builds again. if (postPack !== undefined) await d.postPack(paths.appBundle, postPack); + for (const line of await d.codegenClasses(paths.root, paths.appBundle)) d.log(line); await writeState(paths.iosXtool, { ...state, depsFingerprint }); } diff --git a/src/commands/install.ts b/src/commands/install.ts index 0ebb541..a3eb909 100644 --- a/src/commands/install.ts +++ b/src/commands/install.ts @@ -24,6 +24,7 @@ import { detectLanRoute, isPrivateIpv4, looksLikeTunnel, type LanRoute } from ". import { projectPaths } from "../paths.js"; import { writeEmptyTargetObjects } from "../pods/emptyTargets.js"; import { postPackChecks, type PostPackPods } from "../pods/postPack.js"; +import { checkCodegenClasses, hasCodegenClasses } from "../pipeline/codegenClasses.js"; import { makeNmRunner } from "../pipeline/symbols.js"; import { IOS_MIN } from "../versions.js"; import { readState, rememberDevice, writeState, type BuildState } from "../state.js"; @@ -59,6 +60,9 @@ export interface InstallDeps { /** With binary pods: xtool builds the app first, so the post-pack checks read it before anything installs. */ devBuild?: (bin: string, iosXtoolDir: string) => Promise; postPack?: (appBundle: string, pods: PostPackPods) => Promise; + /** Whether React Native's codegen providers name classes: then xtool builds the app first and they are checked. */ + hasCodegenClasses?: (root: string) => boolean; + codegenClasses?: (root: string, appBundle: string) => Promise; }; wifi?: { /** This computer's default route (address + interface), unless `lanIp` is configured. */ @@ -205,13 +209,27 @@ async function emptyObjects(x: NonNullable, iosXtool: stri /** * Row 88: with binary pods, the app xtool installs comes from `.build`, not from the App.app build checked. xtool * builds and packs it first (`xtool dev run` and `xtool dev build --ipa` then find nothing to rebuild), and the - * post-pack checks read it: a refused app is removed and never installed. + * post-pack checks read it: a refused app is removed and never installed. The same holds for the classes React + * Native's codegen providers name: a build refused for a missing one would otherwise be rebuilt and installed here. */ -async function checkedApp(x: NonNullable, bin: string, root: string, state: InstallState): Promise { - if (state.postPack === undefined) return; +async function checkedApp( + x: NonNullable, + bin: string, + root: string, + state: InstallState, + log: (s: string) => void, +): Promise { + const codegen = (x.hasCodegenClasses ?? hasCodegenClasses)(root); + if (state.postPack === undefined && !codegen) return; const paths = projectPaths(root); await explainingXtool(() => (x.devBuild ?? devBuild)(bin, paths.iosXtool)); - await (x.postPack ?? ((app, pods) => postPackChecks(app, pods, makeNmRunner())))(paths.appBundle, state.postPack); + if (state.postPack !== undefined) { + await (x.postPack ?? ((app, pods) => postPackChecks(app, pods, makeNmRunner())))(paths.appBundle, state.postPack); + } + if (codegen) { + const check = x.codegenClasses ?? ((r, app) => checkCodegenClasses(r, app, makeNmRunner())); + for (const line of await check(paths.root, paths.appBundle)) log(line); + } } export async function install(root: string, deps: InstallDeps = {}, opts: InstallOptions = {}): Promise { @@ -232,7 +250,7 @@ export async function install(root: string, deps: InstallDeps = {}, opts: Instal if (!state) throw new Error("No build found. Run `rn-xtool build` first."); await restaged(x, root, state, log); await emptyObjects(x, iosXtool, state); - await checkedApp(x, bin, root, state); + await checkedApp(x, bin, root, state, log); await explainingXtool(() => (x.devRun ?? devRun)(bin, iosXtool)); const id = installedBundleId(auth.teamId, state.bundleIdentifier); // Which iPhone got this build: `run` must not skip the install for a different one. The id is the one xtool signs @@ -257,7 +275,7 @@ async function installNetwork(root: string, deps: InstallDeps, opts: InstallOpti await restaged(x, root, state, log); await emptyObjects(x, iosXtool, state); - await checkedApp(x, bin, root, state); + await checkedApp(x, bin, root, state, log); const ipa = await explainingXtool(() => (x.devBuildIpa ?? devBuildIpa)(bin, iosXtool)); const bundleId = installedBundleId(auth.teamId, state.bundleIdentifier); const route: LanRoute = config.lanIp diff --git a/src/pipeline/codegenClasses.ts b/src/pipeline/codegenClasses.ts new file mode 100644 index 0000000..6fdb7ce --- /dev/null +++ b/src/pipeline/codegenClasses.ts @@ -0,0 +1,201 @@ +/** + * The classes React Native's codegen looks up by name at app start must be in the app. The generated + * `RCTThirdPartyComponentsProvider.mm` builds a dictionary literal of `NSClassFromString(@"")` for every + * third-party Fabric component: one class missing from the binary is a nil value, and the app stops at start with + * NSInvalidArgumentException in `+[RCTThirdPartyComponentsProvider thirdPartyFabricComponents]`. `RCTModuleProviders.mm` + * does the same for TurboModule providers, and React Native logs "Module provider cannot be found in the + * runtime" and goes on without the module. A library whose scaffolded Package.swift left out its Objective-C sources + * (react-native-screens 4.24.0 before fix 28) builds and links without them, so this is checked on the packed app: + * `build` runs it after xtool-build, and `install` on the app xtool builds before it installs. Nothing is repaired: a + * missing class removes the packed app and its .ipa and stops with the list. + */ +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { troubleshootingUrl } from "../docs.js"; +import { projectPaths } from "../paths.js"; +import { appBinary, removePackedApp } from "../pods/postPack.js"; +import type { NmRunner } from "./symbols.js"; + +export const CODEGEN_CLASSES_LINK = troubleshootingUrl("rctthirdpartycomponentsprovider-thirdpartyfabriccomponents"); + +/** One class the generated providers name. */ +export interface CodegenClass { + kind: "component" | "module"; + /** The component (`RNSScreen`) or module (`RNCWebViewModule`) name. */ + name: string; + /** The Objective-C class name `NSClassFromString` looks up (`RNSScreenView`). */ + className: string; + /** The npm package codegen took it from, when known. */ + library?: string; +} + +const COMPONENTS_FILE = "RCTThirdPartyComponentsProvider.mm"; +const MODULES_FILE = "RCTModuleProviders.mm"; +/** `@"Name": NSClassFromString(@"Class"), // library` (also `[Class class]`). */ +const COMPONENT_RE = /@"([^"]+)"\s*:\s*(?:NSClassFromString\(\s*@"([^"]+)"\s*\)|\[\s*([A-Za-z_]\w*)\s+class\s*\])\s*,?[ \t]*(?:\/\/[ \t]*(\S+))?/g; +/** `@"Module": @"ProviderClass", // library` */ +const MODULE_RE = /@"([^"]+)"\s*:\s*@"([^"]+)"\s*,?[ \t]*(?:\/\/[ \t]*(\S+))?/g; + +function readText(file: string): string | undefined { + try { + return readFileSync(file, "utf8"); + } catch { + return undefined; + } +} + +/** The classes `ios/build/generated/ios/ReactCodegen`'s providers name; none when codegen wrote no providers. */ +export function codegenClasses(generatedIos: string): CodegenClass[] { + const dir = path.join(generatedIos, "ReactCodegen"); + const out: CodegenClass[] = []; + const components = readText(path.join(dir, COMPONENTS_FILE)); + if (components !== undefined) { + for (const m of components.matchAll(COMPONENT_RE)) { + out.push({ kind: "component", name: m[1]!, className: (m[2] ?? m[3])!, ...(m[4] !== undefined && { library: m[4] }) }); + } + } + const modules = readText(path.join(dir, MODULES_FILE)); + // Only the mapping literal: the file's RCTLogError format strings are `@"..."` too, never `@"x": @"y"`. + const mapping = modules?.match(/moduleMapping\s*=\s*@\{([\s\S]*?)\};/)?.[1]; + if (mapping !== undefined) { + for (const m of mapping.matchAll(MODULE_RE)) { + out.push({ kind: "module", name: m[1]!, className: m[2]!, ...(m[3] !== undefined && { library: m[3] }) }); + } + } + return out; +} + +/** Each autolinked library's codegen classes (`codegenConfig.ios`), for providers that do not say the library. */ +function librariesByClass(root: string): Map { + const byClass = new Map(); + let deps: Record = {}; + try { + const json = JSON.parse(readFileSync(path.join(projectPaths(root).autolinking, "autolinking.json"), "utf8")) as { + dependencies?: Record; + }; + deps = json.dependencies ?? {}; + } catch { + return byClass; + } + for (const [name, dep] of Object.entries(deps)) { + if (typeof dep.root !== "string") continue; + let ios: Record | undefined; + try { + const pkg = JSON.parse(readFileSync(path.join(dep.root, "package.json"), "utf8")) as { codegenConfig?: { ios?: Record } }; + ios = pkg.codegenConfig?.ios; + } catch { + continue; + } + if (ios === undefined) continue; + const add = (cls: unknown) => typeof cls === "string" && !byClass.has(cls) && byClass.set(cls, name); + for (const key of ["componentProvider", "modulesProvider"]) { + const map = ios[key]; + if (map !== null && typeof map === "object") for (const cls of Object.values(map)) add(cls); + } + const components = ios["components"]; + if (components !== null && typeof components === "object") { + for (const c of Object.values(components)) add((c as { className?: unknown } | null)?.className); + } + } + return byClass; +} + +const CLASS = /^_OBJC_CLASS_\$_(\S+)$/; + +/** The Objective-C classes `file`'s arm64 code defines, by runtime name. */ +async function definedClasses(nm: NmRunner, file: string): Promise { + const out = await nm(["--arch=arm64", "--defined-only", "-j", file]); + return out + .split("\n") + .map((l) => CLASS.exec(l.trim())?.[1]) + .filter((c): c is string => c !== undefined); +} + +/** The App binary and each embedded framework's binary: where the classes may live. */ +function appImages(appBundle: string): string[] { + const images = [appBinary(appBundle)]; + const frameworks = path.join(appBundle, "Frameworks"); + let entries: string[] = []; + try { + entries = readdirSync(frameworks); + } catch { + return images; + } + for (const e of entries.sort()) { + if (e.endsWith(".framework")) { + const binary = path.join(frameworks, e, e.slice(0, -".framework".length)); + if (existsSync(binary)) images.push(binary); + } else if (e.endsWith(".dylib")) { + images.push(path.join(frameworks, e)); + } + } + return images; +} + +/** `NSClassFromString(@"Module.Class")` finds a Swift class by its mangled runtime name, `_TtC6Module5Class`. */ +function runtimeName(className: string): string { + const parts = className.split("."); + return parts.length === 2 && parts.every((p) => p !== "") ? `_TtC${parts.map((p) => `${p.length}${p}`).join("")}` : className; +} + +const SHOWN = 8; + +/** + * Checks that every class the codegen providers of `root` name is defined in the packed `appBundle` (its App binary or + * an embedded framework). Returns the lines to print; throws, after removing the app and its .ipa, when one is + * missing. + */ +export async function checkCodegenClasses(root: string, appBundle: string, nm: NmRunner): Promise { + const wanted = codegenClasses(projectPaths(root).generatedIos); + if (wanted.length === 0) return []; + const defined = new Set(); + for (const image of appImages(appBundle)) { + if (existsSync(image)) for (const c of await definedClasses(nm, image)) defined.add(c); + } + if (defined.size === 0) { + // A binary without its symbol table (stripped) cannot be checked; nothing is refused on that. + return [ + `ℹ The packed app's binaries list no Objective-C class symbols, so rn-xtool could not check the ${wanted.length} classes ` + + "React Native's codegen providers name.", + ]; + } + const missing = wanted.filter((c) => !defined.has(runtimeName(c.className))); + if (missing.length === 0) return []; + const byClass = missing.some((c) => c.library === undefined) ? librariesByClass(root) : new Map(); + const libraries = new Set(); + const items = missing.map((c) => { + const library = c.library ?? byClass.get(c.className); + if (library !== undefined) libraries.add(library); + return ` - ${c.className} (${c.kind} ${c.name}, ${library ?? "a library"})`; + }); + const shown = [...items.slice(0, SHOWN), ...(items.length > SHOWN ? [` - and ${items.length - SHOWN} more`] : [])]; + const effects: string[] = []; + if (missing.some((c) => c.kind === "component")) { + effects.push( + "With a component class missing, the app would crash at start: +[RCTThirdPartyComponentsProvider thirdPartyFabricComponents] " + + "throws NSInvalidArgumentException (-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object).", + ); + } + if (missing.some((c) => c.kind === "module")) { + effects.push('With a module class missing, React Native logs "Module provider cannot be found in the runtime" and the module is unavailable.'); + } + const named = [...libraries].sort(); + const where = + named.length > 0 + ? `Check the sources of ${named.map((l) => `node_modules/${l}/Package.swift`).join(", ")}: ` + : "Check the sources of the library's Package.swift: "; + await removePackedApp(appBundle); + throw new Error( + "React Native's codegen names classes the packed app does not define, so rn-xtool removed it and does not install it:\n" + + `${shown.join("\n")}\n` + + `${effects.join(" ")}\n` + + `${where}its target was built without the files that define them. A scaffold persisted in patches/ by an older ` + + "rn-xtool can be the cause: delete that patch, reinstall the library and build again.\n" + + `See ${CODEGEN_CLASSES_LINK}`, + ); +} + +/** Whether the codegen providers of `root` name any class, so `install` checks the app before installing it. */ +export function hasCodegenClasses(root: string): boolean { + return codegenClasses(projectPaths(root).generatedIos).length > 0; +} diff --git a/src/pods/postPack.ts b/src/pods/postPack.ts index c28ca7e..f7ec193 100644 --- a/src/pods/postPack.ts +++ b/src/pods/postPack.ts @@ -48,7 +48,7 @@ async function definedClasses(nm: NmRunner, file: string): Promise { } /** The App binary: `CFBundleExecutable` of App.app/Info.plist, else `App`. */ -function appBinary(appBundle: string): string { +export function appBinary(appBundle: string): string { try { const info = plist.parse(readFileSync(path.join(appBundle, "Info.plist"), "utf8")) as Record; if (typeof info.CFBundleExecutable === "string" && info.CFBundleExecutable !== "") return path.join(appBundle, info.CFBundleExecutable); @@ -58,6 +58,12 @@ function appBinary(appBundle: string): string { return path.join(appBundle, "App"); } +/** Row 88: a refused app is not left where `run` would take it as built, nor its .ipa beside it. */ +export async function removePackedApp(appBundle: string): Promise { + await rm(appBundle, { recursive: true, force: true }); + await rm(path.join(path.dirname(appBundle), `${path.basename(appBundle, ".app")}.ipa`), { force: true }); +} + export async function postPackChecks(appBundle: string, pods: PostPackPods, nm: NmRunner): Promise { const items: string[] = []; for (const b of pods.bundles) { @@ -81,9 +87,7 @@ export async function postPackChecks(appBundle: string, pods: PostPackPods, nm: items.push(...missing.slice(0, SHOWN), ...(missing.length > SHOWN ? [` - and ${missing.length - SHOWN} more`] : [])); } if (items.length > 0) { - // Row 88: a refused app is not left where `run` would take it as built, nor its .ipa beside it. - await rm(appBundle, { recursive: true, force: true }); - await rm(path.join(path.dirname(appBundle), `${path.basename(appBundle, ".app")}.ipa`), { force: true }); + await removePackedApp(appBundle); throw new PodsError(`The packed app is not what the CocoaPods binaries need, so rn-xtool removed it and does not install it:\n${items.join("\n")}\nSee ${PODS_LINK}`); } } diff --git a/tests/build.test.ts b/tests/build.test.ts index 8141db6..815ef5a 100644 --- a/tests/build.test.ts +++ b/tests/build.test.ts @@ -177,6 +177,7 @@ function setup(over: { isPortFree?: (p: number) => Promise; isMetroRunn postPack: async () => { calls.push("post-pack"); }, + codegenClasses: async () => [], emptyTargets: over.emptyTargets ?? (() => []), log: (s) => logs.push(s), }; @@ -205,6 +206,31 @@ describe("build", () => { expect(quiet.logs.some((l) => l.startsWith("ℹ Not copied into the app"))).toBe(false); }); + it("checks the codegen classes in the packed app after xtool-build, before it records the build as done", async () => { + const t = setup(); + const seen: string[][] = []; + await build(t.root, {}, { + ...t.deps, + codegenClasses: async (root, app) => { + t.calls.push("codegen-classes"); + seen.push([root, app]); + return ["ℹ codegen line"]; + }, + }); + expect(t.calls.slice(-2)).toEqual(["xtool-build", "codegen-classes"]); + expect(seen).toEqual([[t.root, join(t.root, "ios-xtool", "xtool", "App.app")]]); + expect(t.logs).toContain("ℹ codegen line"); + expect((await readState(join(t.root, "ios-xtool")))?.depsFingerprint).toBe("fp-test"); + + const failing = setup(); + const refused = "React Native's codegen names classes the packed app does not define"; + const codegenClasses = async (): Promise => { + throw new Error(refused); + }; + await expect(build(failing.root, {}, { ...failing.deps, codegenClasses })).rejects.toThrow(refused); + expect((await readState(join(failing.root, "ios-xtool")))?.depsFingerprint).toBeUndefined(); + }); + it("hands the scaffolded libraries' resource bundles to generate, read after rn-spm", async () => { const t = setup(); const bundle = { key: "RNSVGFilters", baseDir: "/p/svg", globs: ["apple/**/*.iphoneos.metallib"], owner: "react-native-svg" }; diff --git a/tests/codegenClasses.test.ts b/tests/codegenClasses.test.ts new file mode 100644 index 0000000..113faac --- /dev/null +++ b/tests/codegenClasses.test.ts @@ -0,0 +1,183 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { troubleshootingUrl } from "../src/docs.js"; +import { checkCodegenClasses, codegenClasses, hasCodegenClasses } from "../src/pipeline/codegenClasses.js"; +import type { NmRunner } from "../src/pipeline/symbols.js"; + +const LINK = troubleshootingUrl("rctthirdpartycomponentsprovider-thirdpartyfabriccomponents"); +let root: string; +let app: string; +beforeEach(() => { + root = mkdtempSync(path.join(tmpdir(), "codegen-classes-")); + app = path.join(root, "ios-xtool", "xtool", "App.app"); + mkdirSync(app, { recursive: true }); + writeFileSync(path.join(app, "App"), "binary"); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const codegenDir = () => path.join(root, "ios", "build", "generated", "ios", "ReactCodegen"); +/** React Native's generated RCTThirdPartyComponentsProvider.mm with these mapping lines. */ +function components(lines: string[]): void { + mkdirSync(codegenDir(), { recursive: true }); + writeFileSync( + path.join(codegenDir(), "RCTThirdPartyComponentsProvider.mm"), + "#import \n\n@implementation RCTThirdPartyComponentsProvider\n\n" + + "+ (NSDictionary> *)thirdPartyFabricComponents\n{\n" + + " dispatch_once(&nativeComponentsToken, ^{\n thirdPartyComponents = @{\n" + + lines.map((l) => `\t\t${l}\n`).join("") + + " };\n });\n\n return thirdPartyComponents;\n}\n\n@end\n", + ); +} +/** React Native's generated RCTModuleProviders.mm with these mapping lines. */ +function modules(lines: string[]): void { + mkdirSync(codegenDir(), { recursive: true }); + writeFileSync( + path.join(codegenDir(), "RCTModuleProviders.mm"), + "@implementation RCTModuleProviders\n\n+ (NSDictionary> *)moduleProviders\n{\n" + + " dispatch_once(&onceToken, ^{\n NSDictionary * moduleMapping = @{\n" + + lines.map((l) => ` \t\t${l}\n`).join("") + + " };\n\n for (NSString *key in moduleMapping) {\n" + + ' if (!klass) {\n RCTLogError(@"Module provider %@ cannot be found in the runtime", moduleProviderName);\n }\n' + + " }\n });\n return providers;\n}\n\n@end\n", + ); +} +const screen = (component: string, cls: string) => `@"${component}": NSClassFromString(@"${cls}"), // react-native-screens`; +/** A fake llvm-nm: each Mach-O defines these Objective-C classes. */ +function fakeNm(byFile: Record, seen: string[] = []): NmRunner { + return async (args) => { + expect(args).toEqual(["--arch=arm64", "--defined-only", "-j", args.at(-1)!]); + const file = args.at(-1)!; + seen.push(path.relative(app, file)); + const classes = byFile[path.relative(app, file)]; + if (classes === undefined) throw new Error(`unexpected file ${file}`); + return ["_main", ...classes.flatMap((c) => [`_OBJC_CLASS_$_${c}`, `_OBJC_METACLASS_$_${c}`])].join("\n"); + }; +} + +describe("codegenClasses", () => { + it("reads the component and module providers, with the library each line names", () => { + components([ + '@"RNSScreen": NSClassFromString(@"RNSScreenView"), // react-native-screens', + '@"RNDateTimePicker": NSClassFromString(@"RNDateTimePickerComponentView"), // @react-native-community/datetimepicker', + '@"Legacy": [LegacyView class],', + ]); + modules(['@"RNCWebViewModule": @"RNCWebViewModule", // react-native-webview']); + expect(codegenClasses(path.join(root, "ios", "build", "generated", "ios"))).toEqual([ + { kind: "component", name: "RNSScreen", className: "RNSScreenView", library: "react-native-screens" }, + { + kind: "component", + name: "RNDateTimePicker", + className: "RNDateTimePickerComponentView", + library: "@react-native-community/datetimepicker", + }, + { kind: "component", name: "Legacy", className: "LegacyView" }, + { kind: "module", name: "RNCWebViewModule", className: "RNCWebViewModule", library: "react-native-webview" }, + ]); + expect(hasCodegenClasses(root)).toBe(true); + }); + + it("finds nothing without providers, or with empty ones", () => { + expect(hasCodegenClasses(root)).toBe(false); + components([]); + modules([]); + expect(hasCodegenClasses(root)).toBe(false); + }); +}); + +describe("checkCodegenClasses", () => { + it("passes when every class is in the App binary or an embedded framework, and keeps the app", async () => { + components([screen("RNSScreen", "RNSScreenView"), '@"SwiftView": NSClassFromString(@"MyKit.SwiftView"), // my-kit']); + modules(['@"RNCWebViewModule": @"RNCWebViewModule", // react-native-webview']); + mkdirSync(path.join(app, "Frameworks", "MyKit.framework"), { recursive: true }); + writeFileSync(path.join(app, "Frameworks", "MyKit.framework", "MyKit"), "binary"); + writeFileSync(path.join(root, "ios-xtool", "xtool", "App.ipa"), "ipa"); + const seen: string[] = []; + const nm = fakeNm({ App: ["RNSScreenView", "RNCWebViewModule"], "Frameworks/MyKit.framework/MyKit": ["_TtC5MyKit9SwiftView"] }, seen); + await expect(checkCodegenClasses(root, app, nm)).resolves.toEqual([]); + expect(seen).toEqual(["App", "Frameworks/MyKit.framework/MyKit"]); + expect(existsSync(app)).toBe(true); + expect(existsSync(path.join(root, "ios-xtool", "xtool", "App.ipa"))).toBe(true); + }); + + it("does not read the binaries when codegen wrote no providers", async () => { + await expect(checkCodegenClasses(root, app, async () => expect.fail("nm ran"))).resolves.toEqual([]); + }); + + it("refuses an app without the classes react-native-screens 4.24.0 declares, and removes it and its .ipa", async () => { + // The real app's crash: RNScreens.o compiled from the common subspec's C++ alone, so no RNS class was linked. + const screens = [ + ["RNSFullWindowOverlay", "RNSFullWindowOverlay"], + ["RNSModalScreen", "RNSModalScreen"], + ["RNSScreenContainer", "RNSScreenContainerView"], + ["RNSScreenContentWrapper", "RNSScreenContentWrapper"], + ["RNSScreenFooter", "RNSScreenFooter"], + ["RNSScreen", "RNSScreenView"], + ["RNSScreenNavigationContainer", "RNSScreenNavigationContainerView"], + ["RNSScreenStackHeaderConfig", "RNSScreenStackHeaderConfig"], + ["RNSScreenStackHeaderSubview", "RNSScreenStackHeaderSubview"], + ["RNSScreenStack", "RNSScreenStackView"], + ]; + components([ + '@"RNGestureHandlerButton": NSClassFromString(@"RNGestureHandlerButtonComponentView"), // react-native-gesture-handler', + ...screens.map(([c, cls]) => screen(c!, cls!)), + ]); + writeFileSync(path.join(root, "ios-xtool", "xtool", "App.ipa"), "ipa"); + const nm = fakeNm({ App: ["RNGestureHandlerButtonComponentView", "AppDelegate"] }); + await expect(checkCodegenClasses(root, app, nm)).rejects.toThrow( + "React Native's codegen names classes the packed app does not define, so rn-xtool removed it and does not install it:\n" + + " - RNSFullWindowOverlay (component RNSFullWindowOverlay, react-native-screens)\n" + + " - RNSModalScreen (component RNSModalScreen, react-native-screens)\n" + + " - RNSScreenContainerView (component RNSScreenContainer, react-native-screens)\n" + + " - RNSScreenContentWrapper (component RNSScreenContentWrapper, react-native-screens)\n" + + " - RNSScreenFooter (component RNSScreenFooter, react-native-screens)\n" + + " - RNSScreenView (component RNSScreen, react-native-screens)\n" + + " - RNSScreenNavigationContainerView (component RNSScreenNavigationContainer, react-native-screens)\n" + + " - RNSScreenStackHeaderConfig (component RNSScreenStackHeaderConfig, react-native-screens)\n" + + " - and 2 more\n" + + "With a component class missing, the app would crash at start: +[RCTThirdPartyComponentsProvider " + + "thirdPartyFabricComponents] throws NSInvalidArgumentException (-[__NSPlaceholderDictionary " + + "initWithObjects:forKeys:count:]: attempt to insert nil object).\n" + + "Check the sources of node_modules/react-native-screens/Package.swift: its target was built without the files " + + "that define them. A scaffold persisted in patches/ by an older rn-xtool can be the cause: delete that patch, " + + "reinstall the library and build again.\n" + + `See ${LINK}`, + ); + expect(existsSync(app)).toBe(false); + expect(existsSync(path.join(root, "ios-xtool", "xtool", "App.ipa"))).toBe(false); + }); + + it("names a missing module provider, and a library from its package.json when the provider line does not", async () => { + components(['@"FooView": NSClassFromString(@"FooComponentView"),', '@"Bar": [BarView class],']); + modules(['@"RNCWebViewModule": @"RNCWebViewModule", // react-native-webview']); + const foo = path.join(root, "node_modules", "react-native-foo"); + mkdirSync(foo, { recursive: true }); + writeFileSync( + path.join(foo, "package.json"), + JSON.stringify({ name: "react-native-foo", codegenConfig: { ios: { components: { FooView: { className: "FooComponentView" } } } } }), + ); + const autolinking = path.join(root, "ios", "build", "generated", "autolinking"); + mkdirSync(autolinking, { recursive: true }); + writeFileSync(path.join(autolinking, "autolinking.json"), JSON.stringify({ dependencies: { "react-native-foo": { root: foo } } })); + const error = await checkCodegenClasses(root, app, fakeNm({ App: ["AppDelegate"] })).catch((e: Error) => e); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain( + " - FooComponentView (component FooView, react-native-foo)\n" + + " - BarView (component Bar, a library)\n" + + " - RNCWebViewModule (module RNCWebViewModule, react-native-webview)\n", + ); + expect(message).toContain('With a module class missing, React Native logs "Module provider cannot be found in the runtime"'); + expect(message).toContain("Check the sources of node_modules/react-native-foo/Package.swift, node_modules/react-native-webview/Package.swift:"); + }); + + it("only says so when the binaries list no class at all (a stripped binary), and keeps the app", async () => { + components([screen("RNSScreen", "RNSScreenView")]); + await expect(checkCodegenClasses(root, app, fakeNm({ App: [] }))).resolves.toEqual([ + "ℹ The packed app's binaries list no Objective-C class symbols, so rn-xtool could not check the 1 classes React " + + "Native's codegen providers name.", + ]); + expect(existsSync(app)).toBe(true); + }); +}); diff --git a/tests/install.test.ts b/tests/install.test.ts index 962f6a4..f83c55b 100644 --- a/tests/install.test.ts +++ b/tests/install.test.ts @@ -456,6 +456,32 @@ describe("install with binary pods (row 88)", () => { expect(calls).toEqual(["dev run"]); }); + it("checks the codegen classes of the app xtool builds before xtool dev run installs it, without binary pods too", async () => { + const codegen = (check: () => Promise) => { + const { deps, calls } = usb({ state: { postPack: undefined } }); + const logs: string[] = []; + const xtool = { + ...deps.xtool, + hasCodegenClasses: (root: string) => root === "/p", + codegenClasses: async (root: string, app: string) => { + calls.push(`codegen-classes ${root} ${app}`); + return check(); + }, + }; + return { deps: { ...deps, xtool, log: (s: string) => void logs.push(s) }, calls, logs }; + }; + const ok = codegen(async () => ["ℹ codegen line"]); + await install("/p", ok.deps); + expect(ok.calls).toEqual(["dev build /p/ios-xtool", "codegen-classes /p /p/ios-xtool/xtool/App.app", "dev run"]); + expect(ok.logs).toContain("ℹ codegen line"); + + const refused = codegen(async () => { + throw new Error("React Native's codegen names classes the packed app does not define"); + }); + await expect(install("/p", refused.deps)).rejects.toThrow("codegen names classes"); + expect(refused.calls).not.toContain("dev run"); + }); + it("checks the app before xtool builds the ipa, and does not install a refused one over Wi-Fi", async () => { const calls: string[] = []; const installOverWifi = vi.fn(); From 7d28ecf2b99b03415ce4ac70ac3c8b45bc04ce16 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Thu, 5 Nov 2026 21:16:32 -0600 Subject: [PATCH 13/16] docs: describe podspec locals and codegen checks --- CHANGELOG.md | 11 +++- docs/how-it-works.md | 19 ++++++ docs/libraries.md | 2 +- docs/troubleshooting.md | 29 ++++++---- docs/upstream/react-native-scaffolder.md | 73 +++++++++++++++++++++--- vendor/rn-spm/README.md | 2 +- 6 files changed, 113 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1415c6..9b44442 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,8 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea ## [Unreleased] ### Upgrading from 0.1.0-alpha.6 -- The scaffolder is now revision 5, so every scaffold patch rn-xtool persisted in your `patches/` before this release - gets a warning at each `build`: "⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 5); +- The scaffolder is now revision 6, so every scaffold patch rn-xtool persisted in your `patches/` before this release + gets a warning at each `build`: "⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 6); delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old Package.swift)". Do what it says. A scaffolded library without a persisted patch is scaffolded again by itself. - A `pods..forwardHeaders` entry in `rn-xtool.config.json` that lists modules is refused: list the pod's public @@ -41,6 +41,13 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea - A library that was also built for Android gets its scaffold persisted, instead of "⚠ Did not persist 's scaffold: the patch would contain a binary file (node_modules//android/build/…/BuildConfig.dex)" and a new scaffold at every build: the patch holds the files the scaffold wrote and those its existing patch held. +- react-native-screens 4.24.0 scaffolds with its `ios/` sources, instead of a target with only its C++ and an app that + crashed at start: the podspec reader evaluates Ruby locals, interpolation, `ENV` lookups, ternaries, `if`/`unless` + blocks and `push` on a local array, and leaves out the branches a condition rules out; a source glob it cannot + evaluate stops that library's scaffold with the podspec, the field and the expression. +- `build` and `install` stop, and remove the packed app, when a class React Native's codegen providers name is not in + the app, naming the class, its component or module and its library, instead of installing an app that would crash + at start in `+[RCTThirdPartyComponentsProvider thirdPartyFabricComponents]`. ## [0.1.0-alpha.6] - 2026-11-05 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index d9dd19e..8f37b34 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -352,6 +352,25 @@ patch above is what makes that scaffolder work for real-world podspecs. `Scaffolding failed: `, followed by that library's own warnings, one block per failed library. Nothing is persisted for a failed library, and React Native does not run a second time ([troubleshooting.md](troubleshooting.md#scaffolded-libraries)). +- The scaffolder reads a podspec with `pod ipc spec` when CocoaPods is installed, and otherwise with its own reader, + which runs the podspec's statements over the subset of Ruby podspecs use for their fields: locals (`name = …`, `+=`, + `||=`; the last assignment that runs wins), single- and double-quoted strings with `#{…}` interpolation, arrays and + `%w[…]`, `ENV['…']` and `ENV.fetch` (`RCT_NEW_ARCH_ENABLED` and `RCT_HERMES_V1_ENABLED` are `1`, as React Native's + CocoaPods setup sets them, and every other variable is unset, whatever the shell says), `==`, `!=`, `!`, `&&`, + `||`, ternaries, `+` on strings and arrays, `join`, `if`/`elsif`/`else`/`unless` blocks and `if`/`unless` + modifiers, and `push`, `<<` and `concat` on a local array. A branch its condition rules out is left out, as + CocoaPods leaves it out; both branches of a condition it cannot evaluate (a method call such as + `respond_to?(:install_modules_dependencies, true)`) are read. A `source_files` or `exclude_files` value that uses + anything else (a method call, a local it could not evaluate) fails that library's scaffold, with a reason that + names the podspec, the field and the expression, since a target built from the globs it could read would lack some + of the library's files + ([fix 28](upstream/react-native-scaffolder.md#28-scriptsspmread-podspecjs-source-globs-built-from-ruby-locals-and-conditions-are-read-in-part)). +- After `xtool-build`, `build` checks that every class React Native's codegen providers name + (`ios/build/generated/ios/ReactCodegen/RCTThirdPartyComponentsProvider.mm` and `RCTModuleProviders.mm`) is defined + in the App binary or an embedded framework; `install` checks the app xtool builds again before it installs it. A + missing component class would crash the app at start in `+[RCTThirdPartyComponentsProvider + thirdPartyFabricComponents]`, so rn-xtool removes the packed app and stops, naming the class, the component or + module and the library ([troubleshooting.md](troubleshooting.md#rctthirdpartycomponentsprovider-thirdpartyfabriccomponents)). - The scaffolded `Package.swift` holds no resources. rn-xtool builds the library's unconditional `resource_bundles` whose names and globs are plain strings as `.bundle` at the root of `App.app` (react-native-svg's `RNSVGFilters.bundle`, react-native-device-info's privacy bundle; [CocoaPods binaries](#cocoapods-binaries)). After diff --git a/docs/libraries.md b/docs/libraries.md index 26f48d4..dc4fd7a 100644 --- a/docs/libraries.md +++ b/docs/libraries.md @@ -46,7 +46,7 @@ Legend: ✅ works · ⚠️ works with caveats · ❌ fails · ⏳ not tested ye |---|---|---|---|---|---|---|---|---|---|---| | expo-haptics | ~58.0.7 | Expo source package (autolinked) | ✅ 2026-10-23 | ✅ 2026-10-23 | ✅ 2026-10-28 (57.0.3) | **58.0.21 set** ✅ 2026-10-28 (hybrid: bare + Expo modules, expo 58.0.21, React Native 0.88.1); ✅ 2026-10-26 on React Native 0.88.0 and expo 58.0.19, a set this release refuses | — | — | — | notificationAsync + impactAsync vibrate on device | | react-native-safe-area-context | ~5.10.1 | RN lib with its own Package.swift (self-managed) | ✅ 2026-10-23 | ✅ 2026-10-23 | ✅ 2026-10-28 (5.7.0, insets on a native-stack screen) | ⏳ | ⏳ | ⏳ | 5.11.1: build ✅ 2026-11-04 (in the template; device ⏳) | linked without changes | -| react-native-screens | ~4.30.0 | CocoaPods-only → `npx react-native spm scaffold` generated Package.swift | ✅ 2026-10-23 | ✅ 2026-10-23 (after scaffolder fixes 3-5); **58.0.21 set** ✅ 2026-10-28 (4.30.1, scaffolded, in the template) | ✅ 2026-10-28 (4.26.2, native-stack through expo-router) | ✅ 2026-10-26 | ✅ 2026-10-27 | ✅ 2026-10-27 | ⏳ | the app crashed at startup (`Screen native module hasn't been linked`): the scaffolder could not resolve the Ruby locals in `RNScreens.podspec` (`source_files_exts`, `source_files`), so `ios/` sources were missing; see `docs/upstream/react-native-scaffolder.md` #3. Fix 4 then merges the `common` subspec (`common/cpp`, `cpp/`) that fix 3 had stopped leaking in, which `RNSTabsHostShadowNode.h` needs (#4). Fix 5 emulates the `common` subspec's `header_dir = "rnscreens"` so `` resolves (#5). Scaffold persisted with patch-package (`patches/react-native-screens+4.30.0.patch` in the app); rn-xtool runs `scaffold` automatically when RN reports a missing Package.swift | +| react-native-screens | ~4.30.0 | CocoaPods-only → `npx react-native spm scaffold` generated Package.swift | ✅ 2026-10-23 | ✅ 2026-10-23 (after scaffolder fixes 3-5); **58.0.21 set** ✅ 2026-10-28 (4.30.1, scaffolded, in the template) | ✅ 2026-10-28 (4.26.2, native-stack through expo-router) | ✅ 2026-10-26 | ✅ 2026-10-27 | ✅ 2026-10-27 | ⏳ | the app crashed at startup (`Screen native module hasn't been linked`): the scaffolder could not resolve the Ruby locals in `RNScreens.podspec` (`source_files_exts`, `source_files`), so `ios/` sources were missing; see `docs/upstream/react-native-scaffolder.md` #3. Fix 4 then merges the `common` subspec (`common/cpp`, `cpp/`) that fix 3 had stopped leaking in, which `RNSTabsHostShadowNode.h` needs (#4). Fix 5 emulates the `common` subspec's `header_dir = "rnscreens"` so `` resolves (#5). Scaffold persisted with patch-package (`patches/react-native-screens+4.30.0.patch` in the app); rn-xtool runs `scaffold` automatically when RN reports a missing Package.swift. 4.24.0 builds its globs from Ruby locals set under conditions, which the scaffolder read in part before fix 28: its `ios/` sources were missing, and a bare 0.85 app built, installed and crashed at start in `+[RCTThirdPartyComponentsProvider thirdPartyFabricComponents]` ([troubleshooting](troubleshooting.md#rctthirdpartycomponentsprovider-thirdpartyfabriccomponents)); since fix 28 (scaffold revision 6) it scaffolds its `ios/` sources, and `build` checks that every codegen class is in the app. 4.24.0 with fix 28: build ⏳, device ⏳ | | react-native-gesture-handler | 3.3.0 | CocoaPods-only → scaffold | ✅ 2026-10-23 (auto-scaffold + patched scaffolder) | ✅ 2026-10-23; **58.0.21 set** ✅ 2026-10-28 (3.3.0, scaffolded, in the template) | ✅ 2026-10-28 (2.32.0, Pan and Tap) | ✅ 2026-10-26 | ✅ 2026-10-27 | ✅ 2026-10-27 | ⏳ | RN scaffolder bugs found: (1) `read-podspec` keeps only the first value of `s.source_files = "a", "b"` (lost `shared/**`); (2) `publicHeadersPath: "apple"` holds an umbrella header next to subdirs → SwiftPM rejects; using the `include//` shim fixes it. Both are generic → patched in rn-xtool and to be upstreamed to RN | | react-native-reanimated (+ worklets) | 4.7.1 (+ worklets 0.13.0) | ships Package.swift (self-managed) | ✅ 2026-10-23 | ✅ 2026-10-23; **58.0.21 set** ✅ 2026-10-28 (4.7.1 + worklets 0.13.0, in the template) | ✅ 2026-10-28 (4.5.1 + worklets 0.10.1; keeps animating while the JS thread is blocked) | ✅ 2026-10-26 (needs the worklets Babel plugin) | ⏳ | ✅ 2026-10-27 | 4.3.4 + worklets 0.8.3: ✅ 2026-11-04 (on a device; needs the worklets Babel plugin and scaffolder fix 19); 4.5.1 + worklets 0.10.1: build ✅ 2026-11-04 (device ⏳) | manifest uses CFGetTypeID → fails on Linux host; rn-xtool rewrites it in the `patches` step (by content, so later versions with the same snippet too; old project `patches/` stay harmless), upstream PR pending; see `docs/upstream/reanimated-worklets-manifest.md` | | expo-router | ~58.0.28 | Expo source package (Swift that imports react-native-screens' module) | **58.0.21 set** ✅ 2026-10-28 (the template) | **58.0.21 set** ✅ 2026-10-28 (the template's tabs; the reference app's two native-stack routes with safe-area insets) | ✅ 2026-10-28 (57.0.29) | ⏳ | — | — | — | needs screens + safe-area-context. Swift that imports a scaffolded library needs its header search paths: scaffolder fix 17 records them (the `rn-xtool-swift-importer-paths` line) and rn-xtool's Expo patch passes them on, see `docs/upstream/react-native-scaffolder.md`. It also pulls in `@react-native-masked-view/masked-view` 0.3.2 (scaffolded) and `@expo/ui` (a mixed Expo module). On SDK 57, npm's default peers (react-native-reanimated 4.7.1, react-native-worklets 0.13.1, react-native-gesture-handler 3.4.0, react-native-screens 4.30.1) also build and launch (2026-10-28, launch only), after scaffolder fixes 17 (clang-only part) and 18 for screens 4.30. On SDK 57, run `npx expo install react-dom` after adding expo-router, see [troubleshooting](troubleshooting.md#expo-sdk-57) | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 480ea2e..91fc8a5 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -830,20 +830,24 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin `npm install`, and the next build applies the patch again. A nested package's patch (`+++.patch`) is named ` => `. A package installed at another version than its patch's is not skipped: patch-package applies the patch with its own version warning. -- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 5); delete it so rn-xtool +- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 6); delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old Package.swift)":** the `patches` step found a persisted scaffold patch from an older scaffolder. Revision 1 patches lack the Swift importer paths of mixed libraries, revision 2 patches lack those of clang-only libraries and their module map, revision 3 - patches lack fixes 20–22 and 24 (fixes 17 to 24 in [the scaffolder fixes](upstream/react-native-scaffolder.md)), and - revision 4 patches hold pod header forwarders that `@import` modules (fix 13). Without those fixes, Swift code that + patches lack fixes 20–22 and 24 (fixes 17 to 24 in [the scaffolder fixes](upstream/react-native-scaffolder.md)), + revision 4 patches hold pod header forwarders that `@import` modules (fix 13), and revision 5 patches may lack the + sources of a podspec that builds its globs from Ruby locals and conditions (fix 28: react-native-screens 4.24.0 got no + `ios/` sources). Without those fixes, Swift code that imports a scaffolded library (the app, or expo-router importing react-native-screens) can fail with `'RNSReactBaseView.h' file not found` (a mixed library, such as react-native-screens 4.26) or `'RNSDefines.h' file not found` (a clang-only one, such as react-native-screens 4.30), and an Objective-C++ file that imports - `` stops with `use of '@import' when modules are disabled`. Do what the warning says: delete the + `` stops with `use of '@import' when modules are disabled`, and an app with react-native-screens + 4.24.0 stops at `build` with [the codegen classes + check](#rctthirdpartycomponentsprovider-thirdpartyfabriccomponents). Do what the warning says: delete the patch, remove the library from `node_modules` and reinstall it, then build; rn-xtool scaffolds it again and persists - the new patch. This release's scaffolder is revision 5, so each scaffold patch persisted before it gets the line at + the new patch. This release's scaffolder is revision 6, so each scaffold patch persisted before it gets the line at every build until it is regenerated, for example `⚠ patches/react-native-screens+4.30.0.patch was written by an - older rn-xtool scaffolder (revision 4, now 5); delete it so rn-xtool regenerates it (also remove + older rn-xtool scaffolder (revision 4, now 6); delete it so rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)`. Until then the build goes on with the older manifest. - **"⚠ patches/ was scaffolded for React Native ; delete it so rn-xtool regenerates it for @@ -852,21 +856,21 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin Do the same as for the revision warning above. Both warnings also read patches with the marker's name before the rename, `expo-xtool-scaffold-revision` (apps scaffolded before 0.1.0-alpha.1). - **"ℹ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 5, React Native ): rn-xtool replaced it with the persisted one":** a teammate + patches/ (revision 6, React Native ): rn-xtool replaced it with the persisted one":** a teammate committed a regenerated scaffold patch, and your `node_modules` still had the copy an older patch wrote (patch-package does not replace a file that exists). rn-xtool owns these generated files, so the `patches` step removes the files the current patch creates and patch-package writes them again; the line is printed once patch-package has done so. Nothing to do; files the older scaffold wrote and the current one does not stay in place. This happens only when the patch holds nothing but scaffolded new files. - **"⚠ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 5, React Native ), and that patch also changes the library's own files, so + patches/ (revision 6, React Native ), and that patch also changes the library's own files, so rn-xtool does not replace it: run rm -rf node_modules/ && npm install, then build again":** the same case, but the persisted patch also holds your own fix to the library. rn-xtool persists a scaffold with `patch-package `, which writes everything that differs from the published package into one patch. Removing only the scaffold files would leave a patch that patch-package can apply neither forward nor backward, so rn-xtool changes nothing and the build goes on with the older manifest. Run the command: the reinstall gives the published package, and the next build applies the whole patch. -- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 5)" (or +- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 6)" (or "was scaffolded for React Native , not "), followed by "rn-xtool removed it so the rn-spm step scaffolds it again":** a library has no persisted patch, and the manifest rn-xtool generated for it is out of date, for example after you deleted a stale patch but kept the package installed. The `rn-spm` step scaffolds it again @@ -914,9 +918,10 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin rn-xtool 0.1.0-alpha.6 (scaffolder revision 4) wrote the pod table's `forwardHeaders` as `@import` lines. Objective-C++ compiles with `-fmodules -fno-cxx-modules`, Xcode's default, so `@import` is an error there; react-native-app-auth's own `RNAppAuth.m` is Objective-C and compiled. Later releases write the forwarder as one - `#import` per public header of the pod, which compiles in `.m` and `.mm` files alike, and their scaffolder revision 5 - replaces an older scaffold: a copy in `node_modules` without a persisted patch is scaffolded again by itself, and a - persisted patch gets the `⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 5)` line + `#import` per public header of the pod, which compiles in `.m` and `.mm` files alike, and their scaffolder revision + (5 and later) replaces an older scaffold: a copy in `node_modules` without a persisted patch is scaffolded again by + itself, and a persisted patch gets the `⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, + now 6)` line above, whose steps regenerate it. A `forwardHeaders` entry of your config that still lists modules is refused with `… lists the module ; list the pod's public headers instead`: list the headers, as in [Libraries that depend on CocoaPods pods](#libraries-that-depend-on-cocoapods-pods). diff --git a/docs/upstream/react-native-scaffolder.md b/docs/upstream/react-native-scaffolder.md index b3800eb..3c3f9c7 100644 --- a/docs/upstream/react-native-scaffolder.md +++ b/docs/upstream/react-native-scaffolder.md @@ -190,8 +190,9 @@ Fix: a pre-pass `resolveRubyConstants(content)` over the comment-stripped source single-line `ident = 'str' | "str" | ["a", "b"]` assignments (first wins), replaces `#{ident}` for known string constants, and rewrites `s. = ident` (and `ss.`/`s.ios.` forms) to the literal value. Unknown interpolations and identifiers are left untouched; `ENV[...]` and `if` conditions are not -evaluated (except fix 19's). The existing field regexes are unchanged. See the `resolveRubyConstants` hunk in -`patches/react-native+0.88.1.patch`. +evaluated (except fix 19's). The existing field regexes are unchanged. Fix 28 replaced this pass with an evaluator +that runs the podspec's assignments and conditions in order (`evaluateRubyLocals`); the cases above are a subset of +it. ## 4. `scripts/spm/read-podspec.js`: the regex parser is blind to subspec blocks @@ -625,8 +626,8 @@ style), for `RCT_NEW_ARCH_ENABLED` and `RCT_HERMES_V1_ENABLED`. The value is `1` says: React Native 0.87 and 0.88 set both to `1` outright, and the prebuilt artifacts are V1 Hermes, so a `0` left in the shell could only break the build, and a persisted scaffold with it. The `pod ipc` path, taken when the CocoaPods gem is on `PATH`, runs `pod ipc spec` with the same two values in its environment; upstream it set only -`RCT_NEW_ARCH_ENABLED`, and only when the environment did not. Any other `ENV[...]` condition, and every `if`, is -still not evaluated. The scaffolded worklets target then gets +`RCT_NEW_ARCH_ENABLED`, and only when the environment did not. Any other `ENV[...]` condition, and every `if`, was +not evaluated until fix 28, which reads every other variable as unset. The scaffolded worklets target then gets `.define("HERMES_V1_ENABLED")` in its C and C++ settings, and 0.8.3 builds on React Native 0.85.0. worklets 0.10.1 (the Expo SDK 57 pin) gets the same define in a new scaffold; a scaffold persisted earlier keeps its manifest until `RN_XTOOL_SCAFFOLD_REVISION` 4 (fixes 20 to 24) marks it as older. @@ -790,6 +791,64 @@ lock holds the versions), so a version change does not make a persisted scaffold product name is the library's error, naming the key. Only libraries that depend on such a pod get new content, and every earlier scaffold of them was refused, so no revision bump. +## 28. `scripts/spm/read-podspec.js`: source globs built from Ruby locals and conditions are read in part + +react-native-screens 4.24.0 builds its globs from locals assigned under conditions: + +```ruby +new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1' +source_files_exts = new_arch_enabled ? '{h,m,mm,cpp,swift}' : '{h,m,mm,swift}' +source_files = ["ios/**/*.#{source_files_exts}"] +if !new_arch_enabled + source_files.push("cpp/RNScreensTurboModule.cpp", "cpp/RNScreensTurboModule.h") +end +... + s.source_files = source_files + if !gamma_project_enabled + s.exclude_files = "ios/gamma/**/*.#{source_files_exts}" + else + s.exclude_files = "ios/stubs/**/*.#{source_files_exts}" + end +``` + +Fix 3's pass did not evaluate a ternary on a local, so `#{source_files_exts}` stayed in the glob, which matched +nothing. The scaffolded `RNScreens` target held only the `common` subspec's `common/cpp/**` and `cpp/**` files (49 +entries) and none of `ios/`: it built and linked without a single Objective-C class, and the app crashed at start with +`NSInvalidArgumentException` in `+[RCTThirdPartyComponentsProvider thirdPartyFabricComponents]` (a nil class for each +of the 20 components codegen expects). Nothing warned: a glob that matches nothing is not an error. 4.26 and 4.30 +write `source_files_exts` as a literal, which fix 3 read. + +Fix: `evaluateRubyLocals` runs the comment-stripped podspec's statements in order over a side-effect-free subset of +Ruby and hands the field regexes a flat text with the same line count. It evaluates locals (`=`, `+=`, `||=`, the last +assignment that runs wins), single-quoted strings verbatim and double-quoted ones with `#{expr}` interpolation, arrays +and `%w[...]`, numbers, `true`/`false`/`nil`, `ENV['X']` and `ENV.fetch('X', default)` (fix 19's two variables are +`1`, every other one is unset; the environment is never read), `==`, `!=`, `!`/`not`, `&&`/`and`, `||`/`or`, `+` on +strings and arrays, ternaries, `array.join(sep)`, `.to_s` and `.freeze`, `if`/`elsif`/`else`/`unless`/`end` blocks +and `stmt if cond` / `stmt unless cond` modifiers (at the top level and inside the spec and subspec blocks), and +`push`/`append`/`concat`/`<<` on a local array. A branch that does not run is blanked, and the control lines of a +condition it evaluated are dropped, so a subspec under `if new_arch_enabled` is read as a plain subspec and an +`exclude_files` in a dead `else` no longer applies. A `recv. = expr` on the spec or a subspec (`s.`, `s.ios.`, +`ss.`) whose value is not already a literal is rewritten to the literal it evaluates to; inside a hash +(`pod_target_xcconfig`, `resource_bundles`) `=> local` is replaced by the local's value. Anything else (method calls, +hashes, symbols, `$config[...]`, blocks other than the spec's) is not evaluated: the text stays as written, a local +assigned from it or under a condition on it is unknown from there on, and both branches of such a condition stay +visible, as before (react-native-vision-camera's `if enableFrameProcessors` subspec, fix 20). + +A `source_files` or `exclude_files` value that uses something unknown no longer degrades silently: the model carries it +in `unresolvedSources`, and `scaffoldPackageSwiftForDep` returns `status: 'error'` with a reason naming the podspec, +the field and the expression, for example ``: `s.source_files = sources_for("ios")` cannot be evaluated: it +uses the method call `sources_for(...)`.`` Name resolution and header search paths keep +reading the model as before. + +Effect on the libraries checked: screens 4.24.0 scaffolds 195 sources (147 under `ios/`), gamma excluded, as one +clang-only target (every Swift file is under `ios/gamma`), with `ios/bridging/Swift-Bridging.h` left out of its module +map (fix 18, it imports the module's own `-Swift.h`). react-native-svg 15.16.0 no longer excludes +`apple/Utils/RNSVGFabricConversions.h` (excluded only in its old-architecture `else` branch), so the header is in its +sources and its module map is no longer written. The other libraries of the reference app, of the bare 0.86 and 0.87 +apps and of the Expo SDK 57 and 58 apps read the same sources as before; their dependencies and `exclude_files` lose +what only a dead `else` branch declared (`React-Core`, `React-jsc`, datetimepicker's `ios/fabric`). The scaffold +revision moves to 6. + ## Known limitation (deferred): pure-Swift packages importing a mixed Expo module A Swift module built with a bridging header (every mixed target) makes each Swift importer re-read that @@ -804,9 +863,9 @@ every generated or scaffolded Swift target that depends on a mixed module the sa `tests/rn-scaffolder.test.ts` loads the patched modules from the reference app and checks the fixes against fixtures (skipped when the reference app is not present; set `RN_XTOOL_REF_APP` to point at it). It also -asserts that each hunk is present in the installed RN files. Fixes 14 to 27 are tested on the vendored copy (`vendor/rn-spm/spm`), so they never skip, +asserts that each hunk is present in the installed RN files. Fixes 14 to 28 are tested on the vendored copy (`vendor/rn-spm/spm`), so they never skip, against podspec fixtures from the SDK 57 pins in `tests/fixtures/podspecs/` (worklets 0.10.1, reanimated 4.5.1, -screens 4.26.2, gesture-handler 2.32.0), from screens 4.30.1 (the clang-only importer paths and module map) and from -worklets 0.8.3 (the `RCT_HERMES_V1_ENABLED` ternary). A golden test re-scaffolds the reference app's libraries and compares them +screens 4.26.2, gesture-handler 2.32.0), from screens 4.30.1 (the clang-only importer paths and module map), from +worklets 0.8.3 (the `RCT_HERMES_V1_ENABLED` ternary) and from screens 4.24.0 (fix 28's locals and conditions). A golden test re-scaffolds the reference app's libraries and compares them with `tests/fixtures/scaffold-golden/`. Upstream, equivalent tests belong in RN's own `__tests__` next to `read-podspec` and `scaffold-package-swift`. diff --git a/vendor/rn-spm/README.md b/vendor/rn-spm/README.md index b879a13..76382d6 100644 --- a/vendor/rn-spm/README.md +++ b/vendor/rn-spm/README.md @@ -6,7 +6,7 @@ versions that ship no `scripts/spm` of their own. - Origin: react-native 0.88.0, MIT, Meta Platforms, Inc. and affiliates (see `LICENSE`). - Modifications, in order: - 1. The 27 fixes of `docs/upstream/react-native-scaffolder.md`, applied with + 1. The 28 fixes of `docs/upstream/react-native-scaffolder.md`, applied with `patches/react-native+0.88.0.patch` (`patch -p4`, run in the extracted `scripts/`). 2. Five rn-xtool edits (E1-E5) in `rn-xtool-edits.patch` (`patch -p1`, run in this directory): the codegen template resolves relative to this copy, the installed React Native root comes From 95973c6713216aa7d61db7473fba6cd0aa46d92d Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Fri, 6 Nov 2026 07:09:32 -0600 Subject: [PATCH 14/16] fix: keep podspec flags the reader read before --- patches/react-native+0.88.0.patch | 500 +++++++++++++++--- patches/react-native+0.88.1.patch | 500 +++++++++++++++--- .../cpp/worklets/Tools/WorkletsVersion.cpp | 0 .../scripts/worklets_utils.rb | 103 ++++ tests/rn-scaffolder.test.ts | 50 +- vendor/rn-spm/rn-xtool-edits.patch | 2 +- vendor/rn-spm/spm/read-podspec.js | 451 ++++++++++++++-- 7 files changed, 1388 insertions(+), 218 deletions(-) create mode 100644 tests/fixtures/podspecs/RNWorklets-0.8.3/Common/cpp/worklets/Tools/WorkletsVersion.cpp create mode 100644 tests/fixtures/podspecs/RNWorklets-0.8.3/scripts/worklets_utils.rb diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index 2cf5960..ac862f2 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -1,5 +1,5 @@ diff --git a/node_modules/react-native/scripts/spm/read-podspec.js b/node_modules/react-native/scripts/spm/read-podspec.js -index 8fcf04b..6ed3f14 100644 +index 8fcf04b..6897fdb 100644 --- a/node_modules/react-native/scripts/spm/read-podspec.js +++ b/node_modules/react-native/scripts/spm/read-podspec.js @@ -102,13 +102,12 @@ function runPodIpcSpec(podspecPath /*: string */) /*: RawSpec | null */ { @@ -22,7 +22,7 @@ index 8fcf04b..6ed3f14 100644 }); } catch { cleanupPatchedPodspec(patchedPath); -@@ -170,58 +169,1072 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { +@@ -170,58 +169,1412 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { // Regex fallback // --------------------------------------------------------------------------- @@ -89,21 +89,143 @@ index 8fcf04b..6ed3f14 100644 + RCT_HERMES_V1_ENABLED: '1', +}; + -+// A value the evaluator could not compute, and why. ++// A value the evaluator could not compute, and why. A string with an ++// interpolation it could not compute keeps that `#{...}` as written in ++// `partial`, as fix 3's pass did: fix 8 still reads ++// `REACT_NATIVE_MINOR_VERSION=#{...}` from it, and what is left is reported. +class RubyUnresolved { -+ /*:: why: string; */ -+ constructor(why /*: string */) { ++ /*:: why: string; partial: ?string; */ ++ constructor(why /*: string */, partial /*:: ?: ?string */) { + this.why = why; ++ this.partial = partial ?? null; + } +} +const isUnresolved = (v /*: mixed */) /*: boolean */ => + v instanceof RubyUnresolved; ++// A string value's text, also a partial one's; null for anything else. ++function rubyText(v /*: mixed */) /*: ?string */ { ++ if (typeof v === 'string') return v; ++ return v instanceof RubyUnresolved ? v.partial : null; ++} ++// A Ruby symbol (`:name`). ++class RubySymbol { ++ /*:: name: string; */ ++ constructor(name /*: string */) { ++ this.name = name; ++ } ++} ++// A Ruby hash: insertion-ordered, keyed by string or symbol. ++class RubyHash { ++ /*:: entries: Map; */ ++ constructor() { ++ this.entries = new Map(); ++ } ++ static keyOf(k /*: mixed */) /*: ?string */ { ++ if (typeof k === 'string') return `s:${k}`; ++ if (k instanceof RubySymbol) return `y:${k.name}`; ++ return null; ++ } ++ get(k /*: mixed */) /*: mixed */ { ++ const key = RubyHash.keyOf(k); ++ return key != null ? (this.entries.get(key)?.value ?? null) : null; ++ } ++ set(k /*: mixed */, value /*: mixed */) /*: boolean */ { ++ const key = RubyHash.keyOf(k); ++ if (key == null) return false; ++ this.entries.set(key, {key: k, value}); ++ return true; ++ } ++} ++// JSON (a package.json) as Ruby values: objects become hashes with string keys. ++function fromJson(v /*: mixed */) /*: mixed */ { ++ if (Array.isArray(v)) return v.map(fromJson); ++ if (v != null && typeof v === 'object') { ++ const h = new RubyHash(); ++ for (const [k, x] of Object.entries(v)) h.set(k, fromJson(x)); ++ return h; ++ } ++ return v; ++} + +// The source-glob fields an unevaluated expression must not reach silently. +const STRICT_FIELDS /*: Set */ = new Set([ + 'source_files', + 'exclude_files', +]); ++// Fields that name the library: read as literals only, as before. ++const IDENTITY_FIELDS /*: Set */ = new Set([ ++ 'name', ++ 'module_name', ++ 'version', ++]); ++// Fields whose whole value an unevaluated part changes: refused too. ++const WHOLE_FIELDS /*: Set */ = new Set([ ++ 'compiler_flags', ++ 'header_dir', ++ 'header_mappings_dir', ++ 'frameworks', ++ 'framework', ++ 'weak_frameworks', ++ 'weak_framework', ++ 'libraries', ++ 'library', ++]); ++// The xcconfig hashes, and the keys of them the scaffolder reads. A part of ++// those values it cannot evaluate is left out with a warning that names it: ++// podspecs put optional, configuration-driven flags there (worklets' static ++// feature flags, vision-camera's frame processor switch), which CocoaPods ++// computes from the app and the Podfile. ++const XCCONFIG_FIELDS /*: Set */ = new Set([ ++ 'pod_target_xcconfig', ++ 'user_target_xcconfig', ++ 'xcconfig', ++]); ++const XCCONFIG_READ_KEY_RE = ++ /(["'])(OTHER_CFLAGS|GCC_PREPROCESSOR_DEFINITIONS|HEADER_SEARCH_PATHS|SWIFT_ACTIVE_COMPILATION_CONDITIONS)(\[[^\]]*\])?\1\s*=>/g; ++const XCCONFIG_ANY_KEY_RE = /(["'])[A-Z_]+(\[[^\]]*\])?\1\s*=>/g; ++ ++// Each `#{...}` left in `text` that the scaffolder does not handle itself. ++// Fix 8 gives `REACT_NATIVE_{MAJOR,MINOR,PATCH}_VERSION=#{...}` the installed ++// React Native's number, and a token with an Xcode `$(...)` (`$(PODS_ROOT)/ ++// #{...}`) is dropped for that already. ++function unresolvedInterpolations(text /*: string */) /*: Array */ { ++ const out = []; ++ for (let i = text.indexOf('#{'); i >= 0; i = text.indexOf('#{', i + 2)) { ++ let depth = 0; ++ let end = -1; ++ for (let j = i + 1; j < text.length; j++) { ++ if (text[j] === '{') depth++; ++ else if (text[j] === '}' && --depth === 0) { ++ end = j; ++ break; ++ } ++ } ++ if (end < 0) break; ++ const before = text.slice(0, i).split(/[\s"']/).pop() ?? ''; ++ const after = text.slice(end + 1).split(/[\s"']/)[0] ?? ''; ++ const token = before + text.slice(i, end + 1) + after; ++ const rnVersion = /REACT_NATIVE_(?:MAJOR|MINOR|PATCH)_VERSION=$/.test(before); ++ if (!rnVersion && !/\$[({]/.test(token)) out.push(text.slice(i, end + 1)); ++ } ++ return out; ++} ++// The first value in `v` it could not evaluate (also inside arrays and hashes). ++function unresolvedIn(v /*: mixed */) /*: ?RubyUnresolved */ { ++ if (v instanceof RubyUnresolved) return v; ++ if (Array.isArray(v)) { ++ for (const x of v) { ++ const u = unresolvedIn(x); ++ if (u != null) return u; ++ } ++ } ++ if (v instanceof RubyHash) { ++ for (const {value} of v.entries.values()) { ++ const u = unresolvedIn(value); ++ if (u != null) return u; ++ } ++ } ++ return null; ++} +const PLATFORM_SCOPES /*: Set */ = new Set([ + 'ios', + 'osx', @@ -186,13 +308,19 @@ index 8fcf04b..6ed3f14 100644 + const text = m != null ? m[0] : c; + tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); + i += text.length; -+ } else if (/[A-Za-z_]/.test(c)) { -+ const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); ++ } else if (/[A-Za-z_]/.test(c) || (c === '$' && /[A-Za-z_]/.test(src[i + 1] ?? ''))) { ++ // `$name` is a global. ++ const m = src.slice(i).match(/^\$?[A-Za-z_]\w*(?:[?!](?=\())?/); + const text = m != null ? m[0] : c; + tokens.push({t: 'id', v: text}); + i += text.length; -+ } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { -+ tokens.push({t: 'bad', v: src.slice(i)}); // a symbol ++ } else if (c === ':' && /[A-Za-z_]/.test(src[i + 1] ?? '') && src[i - 1] !== ':') { ++ const m = src.slice(i + 1).match(/^[A-Za-z_]\w*[?!]?/); ++ const text = m != null ? m[0] : ''; ++ tokens.push({t: 'sym', v: text}); ++ i += 1 + text.length; ++ } else if (c === ':' && /["']/.test(src[i + 1] ?? '')) { ++ tokens.push({t: 'bad', v: src.slice(i)}); // a quoted symbol + i = src.length; + } else { + const two = src.slice(i, i + 2); @@ -214,6 +342,9 @@ index 8fcf04b..6ed3f14 100644 + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); + } ++ if (a instanceof RubySymbol && b instanceof RubySymbol) { ++ return a.name === b.name; ++ } + return a === b; +} + @@ -222,9 +353,26 @@ index 8fcf04b..6ed3f14 100644 + if (typeof v === 'string') return v; + if (v == null) return ''; + if (typeof v === 'boolean' || typeof v === 'number') return String(v); ++ if (v instanceof RubySymbol) return v.name; + return new RubyUnresolved('an array or hash inside `#{...}`'); +} + ++// `File.read` reads only inside the podspec's own directory. ++function readInside(dir /*: mixed */, file /*: mixed */) /*: mixed */ { ++ if (typeof dir !== 'string' || typeof file !== 'string') { ++ return new RubyUnresolved('`File.read` of a path it cannot evaluate'); ++ } ++ const full = path.resolve(dir, file); ++ if (full !== dir && !full.startsWith(dir + path.sep)) { ++ return new RubyUnresolved(`\`File.read\` outside the podspec's directory (${file})`); ++ } ++ try { ++ return fs.readFileSync(full, 'utf8'); ++ } catch { ++ return new RubyUnresolved(`\`File.read\` of a file that cannot be read (${path.relative(dir, full)})`); ++ } ++} ++ +/** + * Evaluates one Ruby expression with the locals in `env`. Returns the value, + * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list @@ -257,6 +405,27 @@ index 8fcf04b..6ed3f14 100644 + if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; + } while (depth > 0); + }; ++ // `{k => v, k: v}` (already past `{`). A value it cannot evaluate stays in ++ // the hash as unresolved, so the other entries can still be read. ++ const parseHash = () => { ++ const h = new RubyHash(); ++ while (!peek('}')) { ++ if (tokens[pos] == null) return fail('a missing `}`'); ++ let key; ++ if (tokens[pos].t === 'id' && tokens[pos + 1]?.t === 'op' && tokens[pos + 1].v === ':') { ++ key = new RubySymbol(tokens[pos].v); ++ pos += 2; ++ } else { ++ key = parseTernary(); ++ if (!take('=>')) return fail('a hash entry without `=>`'); ++ } ++ const value = parseTernary(); ++ if (isUnresolved(key) || !h.set(key, value)) return fail('a hash key it cannot evaluate'); ++ if (!take(',')) break; ++ } ++ if (!take('}')) return fail('a missing `}`'); ++ return h; ++ }; + // Comma-separated expressions up to `close` (already past the opener). + const parseItems = (close /*: string */) => { + const items = []; @@ -266,26 +435,34 @@ index 8fcf04b..6ed3f14 100644 + if (!take(',')) break; + } + if (!take(close)) return fail(`a missing \`${close}\``); -+ return items.find(isUnresolved) ?? items; ++ // A partial string stays an element; anything else unknown fails it. ++ return items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; + }; + function parsePrimary() /*: mixed */ { + const tk = tokens[pos++]; + if (tk == null) return fail('an incomplete expression'); + if (tk.t === 'str') { + let out = ''; ++ let why = null; + for (const part of tk.parts) { + if (typeof part === 'string') { + out += part; + continue; + } + const inner = evalRubyExpr(part.expr, env); -+ if (isUnresolved(inner)) return inner; -+ const s = rubyToS(inner); -+ if (isUnresolved(s)) return s; -+ out += (s /*: any */); ++ const s = isUnresolved(inner) ? inner : rubyToS(inner); ++ if (typeof s === 'string') { ++ out += s; ++ continue; ++ } ++ // Kept as written, or as the partial text of a partial string. ++ const u /*: RubyUnresolved */ = (s /*: any */); ++ why ??= u.why; ++ out += u.partial ?? `#{${part.expr}}`; + } -+ return out; ++ return why != null ? new RubyUnresolved(why, out) : out; + } ++ if (tk.t === 'sym') return new RubySymbol(tk.v); + if (tk.t === 'words') return tk.v; + if (tk.t === 'num') return tk.v; + if (tk.t === 'bad') return fail(`\`${tk.v}\``); @@ -295,7 +472,7 @@ index 8fcf04b..6ed3f14 100644 + return take(')') ? v : fail('a missing `)`'); + } + if (tk.v === '[') return parseItems(']'); -+ if (tk.v === '{') return fail('a hash'); ++ if (tk.v === '{') return parseHash(); + return fail(`\`${tk.v}\``); + } + // An identifier. @@ -321,14 +498,50 @@ index 8fcf04b..6ed3f14 100644 + } + return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); + } ++ // The package.json load podspecs share: `JSON.parse(File.read(File.join( ++ // __dir__, "package.json")))`, also with `File.dirname(__FILE__)`. ++ if ((name === 'File' || name === 'JSON') && peek('.')) { ++ pos++; ++ const m = tokens[pos++]; ++ const method = m != null && m.t === 'id' ? m.v : '?'; ++ const call = `${name}.${method}`; ++ if (!take('(')) return fail(`the method \`${call}\``); ++ const args = parseItems(')'); ++ if (isUnresolved(args)) return args; ++ const a = (args /*: any */); ++ if (call === 'File.join' && a.every(x => typeof x === 'string')) { ++ return path.join(...a); ++ } ++ if (call === 'File.dirname' && typeof a[0] === 'string') { ++ return path.dirname(a[0]); ++ } ++ if (call === 'File.read' && a.length === 1) { ++ return readInside(env.get('__dir__'), a[0]); ++ } ++ if (call === 'JSON.parse' && typeof a[0] === 'string') { ++ try { ++ return fromJson(JSON.parse(a[0])); ++ } catch { ++ return fail('`JSON.parse` of text that is not JSON'); ++ } ++ } ++ return fail(`the method call \`${call}(...)\``); ++ } + if (peek('(')) { + skipGroup(); + return fail(`the method call \`${name}(...)\``); + } -+ if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); ++ if (!env.has(name)) { ++ return fail( ++ name.startsWith('$') ++ ? `the global \`${name}\`, which the podspec does not set` ++ : `the unknown identifier \`${name}\``, ++ ); ++ } + const v = env.get(name); + if (isUnresolved(v)) { -+ return fail(`\`${name}\`, which ${(v /*: any */).why}`); ++ const u /*: RubyUnresolved */ = (v /*: any */); ++ return new RubyUnresolved(`\`${name}\`, which ${u.why}`, u.partial); + } + return v; + } @@ -336,9 +549,13 @@ index 8fcf04b..6ed3f14 100644 + let v = parsePrimary(); + while (peek('.') || peek('[')) { + if (take('[')) { -+ pos--; -+ skipGroup(); -+ v = isUnresolved(v) ? v : fail('an index `[...]`'); ++ const key = parseTernary(); ++ if (!take(']')) return fail('a missing `]`'); ++ if (isUnresolved(v)) continue; ++ if (isUnresolved(key)) v = key; ++ else if (v instanceof RubyHash) v = v.get(key); ++ else if (Array.isArray(v) && typeof key === 'number') v = v[key] ?? null; ++ else v = fail('an index `[...]` on a value it cannot index'); + continue; + } + take('.'); @@ -360,10 +577,19 @@ index 8fcf04b..6ed3f14 100644 + } + if (method === 'join' && Array.isArray(v)) { + const sep = args.length > 0 ? args[0] : ''; -+ const parts = v.flat(Infinity).map(rubyToS); -+ const bad = parts.find(isUnresolved); -+ v = -+ bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); ++ const parts = v ++ .flat(Infinity) ++ .map(x => (isUnresolved(x) ? x : rubyToS(x))); ++ const texts = parts.map(rubyText); ++ const partial = parts.find(isUnresolved); ++ if (typeof sep !== 'string') v = fail('`join`'); ++ else if (texts.every(x => x != null)) { ++ const joined = texts.join(sep); ++ v = ++ partial != null ++ ? new RubyUnresolved((partial /*: any */).why, joined) ++ : joined; ++ } else v = partial; + continue; + } + v = fail(`the method call \`.${method}\``); @@ -381,6 +607,13 @@ index 8fcf04b..6ed3f14 100644 + let l = parseUnary(); + while (take('+')) { + const r = parseUnary(); ++ const lt = rubyText(l); ++ const rt = rubyText(r); ++ if (lt != null && rt != null && (isUnresolved(l) || isUnresolved(r))) { ++ const u /*: RubyUnresolved */ = (isUnresolved(l) ? l : r /*: any */); ++ l = new RubyUnresolved(u.why, lt + rt); ++ continue; ++ } + if (isUnresolved(l)) continue; + if (isUnresolved(r)) l = r; + else if (typeof l === 'string' && typeof r === 'string') l = l + r; @@ -439,7 +672,7 @@ index 8fcf04b..6ed3f14 100644 + if (list === true && peek(',')) { + const items = [value]; + while (take(',')) items.push(parseTernary()); -+ value = items.find(isUnresolved) ?? items; ++ value = items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; + } + if (pos < tokens.length && !isUnresolved(value)) { + const rest = tokens[pos]; @@ -462,15 +695,29 @@ index 8fcf04b..6ed3f14 100644 + ).test(rhs.trim()); +} + -+// The literal a field is rewritten to, or null when the value has none. ++// The literal a field is rewritten to, or null when the value has none. A ++// partial string is written with its `#{...}` as written; a hash entry whose ++// value has no literal is left out (the field regexes never read it). +function rubyLiteral(v /*: mixed */) /*: ?string */ { -+ if (typeof v === 'string') return JSON.stringify(v); ++ const text = rubyText(v); ++ if (text != null) return JSON.stringify(text); + if (typeof v === 'boolean') return String(v); + if (Array.isArray(v)) { -+ const flat = v.flat(Infinity); -+ if (!flat.every(x => typeof x === 'string')) return null; ++ const flat = v.flat(Infinity).map(rubyText); ++ if (!flat.every(x => x != null)) return null; + return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; + } ++ if (v instanceof RubyHash) { ++ const items = []; ++ for (const {key, value} of v.entries.values()) { ++ const lit = rubyLiteral(value); ++ if (lit == null) continue; ++ const k = ++ key instanceof RubySymbol ? `:${key.name}` : JSON.stringify(key); ++ items.push(`${k} => ${lit}`); ++ } ++ return `{ ${items.join(', ')} }`; ++ } + return null; +} + @@ -567,7 +814,11 @@ index 8fcf04b..6ed3f14 100644 + +/*:: +type Unresolved = {field: string, expr: string, why: string}; -+type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; ++type Activity = { ++ state: 'yes' | 'no' | 'maybe' | 'opaque', ++ why: string, ++ modifier?: boolean, ++}; +*/ + +// Why a local set under `act` is unknown from there on. @@ -600,12 +851,41 @@ index 8fcf04b..6ed3f14 100644 + */ +function evaluateRubyLocals( + content /*: string */, -+) /*: {text: string, unresolved: Array} */ { ++ podspecPath /*:: ?: string */, ++) /*: {text: string, unresolved: Array, dropped: Array} */ { + const lines = content.split('\n'); + const out = lines.slice(); + const env /*: Map */ = new Map(); ++ if (podspecPath != null) { ++ env.set('__dir__', path.dirname(path.resolve(podspecPath))); ++ env.set('__FILE__', path.resolve(podspecPath)); ++ } + const recvs /*: Set */ = new Set(); + const unresolved /*: Array */ = []; ++ // What was left out of an xcconfig value the scaffolder reads, as warnings. ++ const dropped /*: Array */ = []; ++ const noteXcconfig = (lhs /*: string */, text /*: string */) => { ++ for (const m of text.matchAll(XCCONFIG_READ_KEY_RE)) { ++ const start = (m.index ?? 0) + m[0].length; ++ XCCONFIG_ANY_KEY_RE.lastIndex = start; ++ const next = XCCONFIG_ANY_KEY_RE.exec(text); ++ const value = text.slice(start, next != null ? next.index : undefined); ++ const key = m[2] + (m[3] ?? ''); ++ for (const span of unresolvedInterpolations(value)) { ++ dropped.push( ++ `Left out of ${lhs} ${key}: \`${span}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, ++ ); ++ } ++ const bare = value.match(/^\s*([A-Za-z_$]\w*)\s*,?\s*\}?\s*$/); ++ if (bare != null && rubyText(env.get(bare[1])) == null) { ++ dropped.push( ++ `Left out of ${lhs} ${key}: \`${bare[1]}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, ++ ); ++ } ++ } ++ }; ++ const statementText = (st /*: {start: number, end: number} */) => ++ out.slice(st.start, st.end + 1).join('\n'); + // `if` blocks (which branch is being read) and other blocks. + const frames /*: Array */ = []; + const blank = (st /*: {start: number, end: number} */) => { @@ -636,10 +916,9 @@ index 8fcf04b..6ed3f14 100644 + st /*: {start: number, end: number} */, + hash /*: boolean */, + ) => { -+ const known = (id /*: string */) => { -+ const v = env.get(id); -+ return typeof v === 'string' ? v : null; -+ }; ++ // Spliced into a double-quoted literal, so its own quotes are escaped. ++ const known = (id /*: string */) => ++ rubyText(env.get(id))?.replace(/[\\"]/g, '\\$&'); + for (let k = st.start; k <= st.end; k++) { + out[k] = out[k].replace( + /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, @@ -662,12 +941,38 @@ index 8fcf04b..6ed3f14 100644 + } + } + }; ++ // A local set in a branch of a condition it cannot evaluate keeps its value ++ // for the rest of that branch (webview sets `folly_compiler_flags` and uses ++ // it in `compiler_flags` under `defined?(...)`), the next branch sees the ++ // value from before, and after `end` it is unknown. In any other block it ++ // does not run, or under a modifier, it is unknown at once. + const setLocal = ( + name /*: string */, + value /*: mixed */, + act /*: Activity */, + ) => { -+ env.set(name, act.state === 'yes' ? value : unknownUnder(act)); ++ if (act.state === 'yes') { ++ env.set(name, value); ++ return; ++ } ++ const frame = act.modifier ++ ? null ++ : [...frames].reverse().find(f => f.kind === 'if' && f.branch === 'maybe'); ++ if (frame == null) { ++ env.set(name, unknownUnder(act)); ++ return; ++ } ++ if (!frame.saved.has(name)) { ++ frame.saved.set(name, env.has(name) ? {value: env.get(name)} : null); ++ } ++ env.set(name, value); ++ }; ++ // The next branch of `frame` sees the locals as they were before it. ++ const restoreSaved = (frame /*: any */) => { ++ for (const [name, saved] of frame.saved) { ++ if (saved == null) env.delete(name); ++ else env.set(name, saved.value); ++ } + }; + + for (const st of rubyStatements(lines)) { @@ -689,14 +994,17 @@ index 8fcf04b..6ed3f14 100644 + branch, + prior: act.state === 'no' ? 'yes' : branch, + cond: m[2], ++ firstCond: m[2], + evaluated: branch !== 'maybe' && branch !== 'opaque', + ctrl: [st], ++ saved: new Map(), + }); + continue; + } + if (top?.kind === 'if') { + if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { + top.ctrl.push(st); ++ restoreSaved(top); + if (top.branch === 'opaque') continue; + const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); + if (cond === 'maybe') top.evaluated = false; @@ -705,6 +1013,7 @@ index 8fcf04b..6ed3f14 100644 + } + if (code === 'else') { + top.ctrl.push(st); ++ restoreSaved(top); + if (top.branch !== 'opaque') { + top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; + } @@ -713,6 +1022,9 @@ index 8fcf04b..6ed3f14 100644 + } + if (/^end\b/.test(code) && top != null) { + frames.pop(); ++ for (const name of top.saved?.keys() ?? []) { ++ env.set(name, unknownUnder({state: 'maybe', why: top.firstCond})); ++ } + // An evaluated condition leaves no control lines behind. + if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { + for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); @@ -760,7 +1072,7 @@ index 8fcf04b..6ed3f14 100644 + continue; + } + if (c === 'maybe' && act.state === 'yes') { -+ stAct = {state: 'maybe', why: cond}; ++ stAct = {state: 'maybe', why: cond, modifier: true}; + } + } + // `recv.field = expr` on the spec or a subspec. Under a condition it @@ -776,25 +1088,47 @@ index 8fcf04b..6ed3f14 100644 + (field[2] == null || PLATFORM_SCOPES.has(field[2])) + ) { + const [, recv, scope, name, rhs] = field; -+ // Only the spec's own and its `ios` scope count. ++ // Only the spec's own and its `ios` scope count. The identity fields ++ // keep fix 3's reading (literals only): evaluating `s.name = ++ // package['name']` would rename the scaffolded target. + if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; ++ if (IDENTITY_FIELDS.has(name)) { ++ interpolate(st, false); ++ continue; ++ } + const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; ++ const refuse = (why /*: string */) => ++ unresolved.push({field: lhs, expr: rhs.trim(), why}); ++ // A hash literal stays as written, its `#{local}` and `=> local` filled in. ++ if (/^\{/.test(rhs.trim())) { ++ interpolate(st, true); ++ if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, statementText(st)); ++ continue; ++ } + const v = evalRubyExpr(rhs, env, true); -+ const lit = isUnresolved(v) ? null : rubyLiteral(v); ++ const lit = rubyLiteral(v); ++ const u = unresolvedIn(v); ++ if (STRICT_FIELDS.has(name) && (lit == null || u != null)) { ++ refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); ++ } else if (WHOLE_FIELDS.has(name)) { ++ if (lit == null) { ++ refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); ++ } else if (u != null && unresolvedInterpolations(lit).length > 0) { ++ refuse(`it uses ${u.why}`); ++ } ++ } + if (lit != null) { + blank(st); + const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; + out[st.start] = `${indent}${lhs} = ${lit}`; -+ } else if (STRICT_FIELDS.has(name)) { -+ unresolved.push({ -+ field: lhs, -+ expr: rhs.trim(), -+ why: isUnresolved(v) -+ ? `it uses ${(v /*: any */).why}` -+ : 'its value is not a string or an array of strings', -+ }); ++ if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, lit); + } else { -+ interpolate(st, /^\{/.test(rhs.trim())); ++ interpolate(st, false); ++ if (XCCONFIG_FIELDS.has(name)) { ++ dropped.push( ++ `Left out ${lhs} = ${rhs.trim()}: the podspec reader cannot evaluate it${u != null ? ` (${u.why})` : ''}; CocoaPods passes its value.`, ++ ); ++ } + } + continue; + } @@ -816,6 +1150,7 @@ index 8fcf04b..6ed3f14 100644 + v = new RubyUnresolved( + `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + + `(${(v /*: any */).why})`, ++ (v /*: any */).partial, + ); + } + setLocal(name, v, stAct); @@ -851,7 +1186,7 @@ index 8fcf04b..6ed3f14 100644 + } + interpolate(st, false); + } -+ return {text: out.join('\n'), unresolved}; ++ return {text: out.join('\n'), unresolved, dropped: Array.from(new Set(dropped))}; +} + +// The library's own version. Podspecs load the package.json next to them @@ -896,7 +1231,7 @@ index 8fcf04b..6ed3f14 100644 // first non-whitespace character counts. +function readPodspecEvaluated( + podspecPath /*: string */, -+) /*: {text: string, unresolved: Array} */ { ++) /*: {text: string, unresolved: Array, dropped: Array} */ { + return evaluateRubyLocals( + resolvePackageVersion( + fs @@ -906,6 +1241,7 @@ index 8fcf04b..6ed3f14 100644 + .join('\n'), + path.dirname(podspecPath), + ), ++ podspecPath, + ); +} function readPodspecSource(podspecPath /*: string */) /*: string */ { @@ -1049,15 +1385,20 @@ index 8fcf04b..6ed3f14 100644 */ -function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { - const content = readPodspecSource(podspecPath); +- const warnings /*: Array */ = []; +function regexPodspec( + podspecPath /*: string */, + opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, +) /*: RawSpec */ { -+ const {text: content, unresolved} = readPodspecEvaluated(podspecPath); ++ const { ++ text: content, ++ unresolved, ++ dropped: leftOut, ++ } = readPodspecEvaluated(podspecPath); + const dropped = new Set(opts?.dropSubspecs ?? []); + const mainName = mainReceiverName(content); + const MAIN_RECV = mainRecvPattern(mainName); - const warnings /*: Array */ = []; ++ const warnings /*: Array */ = [...leftOut]; + // The main spec's own statements, and each subspec block apart. The readers + // below default to the main text and receiver; a subspec is read with the + // same readers anchored on its block variable, then merged like @@ -1122,7 +1463,7 @@ index 8fcf04b..6ed3f14 100644 } // The fields that identify the spec, and only when the receiver spelling -@@ -235,9 +1248,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -235,9 +1588,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: // s. = ["a", "b"] (array) // s. = "single" (single value treated as 1-element array) @@ -1153,7 +1494,7 @@ index 8fcf04b..6ed3f14 100644 if (mArr != null) { const inner = mArr[1]; const out /*: Array */ = []; -@@ -249,16 +1280,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -249,16 +1620,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { } return out; } @@ -1196,7 +1537,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; out.push(m[1]); } -@@ -269,21 +1321,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -269,21 +1661,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // s.framework "X" → ["X"] // s.framework = "X" → ["X"] // s.frameworks = ["X","Y"] → ["X","Y"] @@ -1227,7 +1568,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; const itemRe = /["']([^"']+)["']/g; while (true) { -@@ -298,12 +1354,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -298,12 +1694,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: 'HEADER_SEARCH_PATHS' => '...' or => ["...","..."] // Returns the raw token strings (still containing $(PODS_TARGET_SRCROOT) // etc.); substitution happens at translation time. @@ -1244,7 +1585,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; const itemRe = /["']((?:[^"'\\]|\\.)+)["']/g; while (true) { -@@ -321,7 +1379,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -321,7 +1719,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { const strRe = /["']HEADER_SEARCH_PATHS["']\s*=>\s*["']((?:[^"'\\]|\\.)+)["']/g; while (true) { @@ -1253,7 +1594,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; for (const token of m[1].split(/\s+/)) { if (token.length > 0) { -@@ -332,15 +1390,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -332,15 +1730,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { return Array.from(new Set(out)); } @@ -1309,7 +1650,7 @@ index 8fcf04b..6ed3f14 100644 ); } if (/install_modules_dependencies/.test(content)) { -@@ -354,26 +1450,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -354,26 +1790,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { ); } @@ -1426,7 +1767,7 @@ index 8fcf04b..6ed3f14 100644 }; } -@@ -423,6 +1596,58 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -423,6 +1936,58 @@ function shellTokenize(value /*: string */) /*: Array */ { return tokens; } @@ -1485,7 +1826,7 @@ index 8fcf04b..6ed3f14 100644 // --------------------------------------------------------------------------- // Subspec flattening // --------------------------------------------------------------------------- -@@ -438,8 +1663,16 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -438,8 +2003,16 @@ function shellTokenize(value /*: string */) /*: Array */ { * - String fields → top-level wins; if absent, take the first subspec's value * - pod_target_xcconfig HEADER_SEARCH_PATHS → array-union across all selected subspecs * - dependencies → array-union of name strings (version constraints dropped) @@ -1503,7 +1844,7 @@ index 8fcf04b..6ed3f14 100644 const warnings /*: Array */ = []; // $FlowFixMe[prop-missing] dynamic shape const partial /*: boolean */ = rawSpec.__regex_partial__ === true; -@@ -456,7 +1689,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -456,7 +2029,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // - `default_subspecs`: array of names (or undefined → use all subspecs) const subspecs = Array.isArray(rawSpec.subspecs) ? rawSpec.subspecs : []; let selected = subspecs; @@ -1517,7 +1858,7 @@ index 8fcf04b..6ed3f14 100644 const wanted = new Set(rawSpec.default_subspecs); selected = subspecs.filter(s => { // $FlowFixMe[prop-missing] dynamic shape -@@ -464,6 +1702,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -464,6 +2042,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return name != null && wanted.has(name); }); } @@ -1528,7 +1869,7 @@ index 8fcf04b..6ed3f14 100644 const layers = [rawSpec, ...selected]; function mergeArrayField(key /*: string */) /*: Array */ { -@@ -482,6 +1724,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -482,6 +2064,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return Array.from(new Set(out)); } @@ -1546,7 +1887,7 @@ index 8fcf04b..6ed3f14 100644 // Only the spec's own value: a subspec's `header_dir` names that subspec's // headers, and several subspecs can disagree. function specStringField(key /*: string */) /*: string | null */ { -@@ -544,6 +1797,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -544,6 +2137,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // `-D`s are safe to forward; arbitrary flags may be machine- or // example-app-specific. $(inherited), unresolved $(...) tokens, and invalid // C identifiers are skipped. @@ -1567,7 +1908,7 @@ index 8fcf04b..6ed3f14 100644 function mergePreprocessorDefines() /*: Array */ { const out /*: Array */ = []; const seen /*: Set */ = new Set(); -@@ -554,7 +1821,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -554,7 +2161,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { config /*: ?('debug' | 'release') */, ) => { if (!validName.test(name)) return; @@ -1592,7 +1933,7 @@ index 8fcf04b..6ed3f14 100644 return; // unresolved Xcode/Ruby token — don't emit a broken define } const key = `${name}|${config ?? ''}`; -@@ -571,6 +1854,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -571,6 +2194,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { 'xcconfig', 'user_target_xcconfig', ]; @@ -1613,7 +1954,7 @@ index 8fcf04b..6ed3f14 100644 for (const layer of layers) { if (layer == null || typeof layer !== 'object') continue; for (const xcKey of XCCONFIG_KEYS) { -@@ -627,44 +1924,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -627,44 +2264,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return out; } @@ -1758,7 +2099,7 @@ index 8fcf04b..6ed3f14 100644 } } return out; -@@ -677,6 +2049,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -677,6 +2389,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { ? false : true; // RN ecosystem default @@ -1779,7 +2120,7 @@ index 8fcf04b..6ed3f14 100644 return { name: specStringField('name') ?? '', version: specStringField('version') ?? '', -@@ -693,23 +2079,81 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -693,23 +2419,82 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // header_mappings_dir copy step, which SPM has no equivalent for. headerMappingsDirs: mergeArrayField('header_mappings_dir'), headerDir: specStringField('header_dir'), @@ -1853,17 +2194,18 @@ index 8fcf04b..6ed3f14 100644 + .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) + .join('; ') + + '. The podspec reader evaluates locals, string interpolation, arrays, ' + -+ "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + -+ 'the globs it could read would leave some of the library\'s files out of ' + -+ 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + -+ 'reads the podspec, or give the library a Package.swift of its own.' ++ "ENV['...'], package.json reads, comparisons, ternaries and if/unless " + ++ 'blocks; building from the part it could read would leave some of the ' + ++ "library's files or settings out of its target. Install CocoaPods (`gem " + ++ 'install cocoapods`) so `pod ipc spec` reads the podspec, or give the ' + ++ 'library a Package.swift of its own.' + ); +} + // --------------------------------------------------------------------------- // Top-level entry // --------------------------------------------------------------------------- -@@ -722,15 +2166,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -722,15 +2507,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { * Throws when the file doesn't exist. Otherwise always returns a * PodspecModel — warnings on the model surface partial parses to the * caller, who can decide whether to proceed or abort scaffolding for that @@ -1886,7 +2228,7 @@ index 8fcf04b..6ed3f14 100644 // Record whether the podspec calls `install_modules_dependencies(s)`. We // strip that helper before `pod ipc` and the regex parser can't expand it, // so the React-Core family it injects never lands in `model.dependencies`. -@@ -746,21 +2193,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { +@@ -746,21 +2534,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { return model; } @@ -1937,7 +2279,7 @@ index 8fcf04b..6ed3f14 100644 podspecModels.set(key, model); return model; } -@@ -794,12 +2266,13 @@ function readPodspecNames( +@@ -794,12 +2607,13 @@ function readPodspecNames( if (hasShadowingSubspec(source)) { return null; } @@ -1952,7 +2294,7 @@ index 8fcf04b..6ed3f14 100644 const name = field('name'); const moduleName = field('module_name'); -@@ -840,4 +2313,5 @@ module.exports = { +@@ -840,4 +2654,5 @@ module.exports = { runPodIpcSpec, regexPodspec, flattenSubspecs, diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index 2cf5960..ac862f2 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -1,5 +1,5 @@ diff --git a/node_modules/react-native/scripts/spm/read-podspec.js b/node_modules/react-native/scripts/spm/read-podspec.js -index 8fcf04b..6ed3f14 100644 +index 8fcf04b..6897fdb 100644 --- a/node_modules/react-native/scripts/spm/read-podspec.js +++ b/node_modules/react-native/scripts/spm/read-podspec.js @@ -102,13 +102,12 @@ function runPodIpcSpec(podspecPath /*: string */) /*: RawSpec | null */ { @@ -22,7 +22,7 @@ index 8fcf04b..6ed3f14 100644 }); } catch { cleanupPatchedPodspec(patchedPath); -@@ -170,58 +169,1072 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { +@@ -170,58 +169,1412 @@ function cleanupPatchedPodspec(patchedPath /*: ?string */) /*: void */ { // Regex fallback // --------------------------------------------------------------------------- @@ -89,21 +89,143 @@ index 8fcf04b..6ed3f14 100644 + RCT_HERMES_V1_ENABLED: '1', +}; + -+// A value the evaluator could not compute, and why. ++// A value the evaluator could not compute, and why. A string with an ++// interpolation it could not compute keeps that `#{...}` as written in ++// `partial`, as fix 3's pass did: fix 8 still reads ++// `REACT_NATIVE_MINOR_VERSION=#{...}` from it, and what is left is reported. +class RubyUnresolved { -+ /*:: why: string; */ -+ constructor(why /*: string */) { ++ /*:: why: string; partial: ?string; */ ++ constructor(why /*: string */, partial /*:: ?: ?string */) { + this.why = why; ++ this.partial = partial ?? null; + } +} +const isUnresolved = (v /*: mixed */) /*: boolean */ => + v instanceof RubyUnresolved; ++// A string value's text, also a partial one's; null for anything else. ++function rubyText(v /*: mixed */) /*: ?string */ { ++ if (typeof v === 'string') return v; ++ return v instanceof RubyUnresolved ? v.partial : null; ++} ++// A Ruby symbol (`:name`). ++class RubySymbol { ++ /*:: name: string; */ ++ constructor(name /*: string */) { ++ this.name = name; ++ } ++} ++// A Ruby hash: insertion-ordered, keyed by string or symbol. ++class RubyHash { ++ /*:: entries: Map; */ ++ constructor() { ++ this.entries = new Map(); ++ } ++ static keyOf(k /*: mixed */) /*: ?string */ { ++ if (typeof k === 'string') return `s:${k}`; ++ if (k instanceof RubySymbol) return `y:${k.name}`; ++ return null; ++ } ++ get(k /*: mixed */) /*: mixed */ { ++ const key = RubyHash.keyOf(k); ++ return key != null ? (this.entries.get(key)?.value ?? null) : null; ++ } ++ set(k /*: mixed */, value /*: mixed */) /*: boolean */ { ++ const key = RubyHash.keyOf(k); ++ if (key == null) return false; ++ this.entries.set(key, {key: k, value}); ++ return true; ++ } ++} ++// JSON (a package.json) as Ruby values: objects become hashes with string keys. ++function fromJson(v /*: mixed */) /*: mixed */ { ++ if (Array.isArray(v)) return v.map(fromJson); ++ if (v != null && typeof v === 'object') { ++ const h = new RubyHash(); ++ for (const [k, x] of Object.entries(v)) h.set(k, fromJson(x)); ++ return h; ++ } ++ return v; ++} + +// The source-glob fields an unevaluated expression must not reach silently. +const STRICT_FIELDS /*: Set */ = new Set([ + 'source_files', + 'exclude_files', +]); ++// Fields that name the library: read as literals only, as before. ++const IDENTITY_FIELDS /*: Set */ = new Set([ ++ 'name', ++ 'module_name', ++ 'version', ++]); ++// Fields whose whole value an unevaluated part changes: refused too. ++const WHOLE_FIELDS /*: Set */ = new Set([ ++ 'compiler_flags', ++ 'header_dir', ++ 'header_mappings_dir', ++ 'frameworks', ++ 'framework', ++ 'weak_frameworks', ++ 'weak_framework', ++ 'libraries', ++ 'library', ++]); ++// The xcconfig hashes, and the keys of them the scaffolder reads. A part of ++// those values it cannot evaluate is left out with a warning that names it: ++// podspecs put optional, configuration-driven flags there (worklets' static ++// feature flags, vision-camera's frame processor switch), which CocoaPods ++// computes from the app and the Podfile. ++const XCCONFIG_FIELDS /*: Set */ = new Set([ ++ 'pod_target_xcconfig', ++ 'user_target_xcconfig', ++ 'xcconfig', ++]); ++const XCCONFIG_READ_KEY_RE = ++ /(["'])(OTHER_CFLAGS|GCC_PREPROCESSOR_DEFINITIONS|HEADER_SEARCH_PATHS|SWIFT_ACTIVE_COMPILATION_CONDITIONS)(\[[^\]]*\])?\1\s*=>/g; ++const XCCONFIG_ANY_KEY_RE = /(["'])[A-Z_]+(\[[^\]]*\])?\1\s*=>/g; ++ ++// Each `#{...}` left in `text` that the scaffolder does not handle itself. ++// Fix 8 gives `REACT_NATIVE_{MAJOR,MINOR,PATCH}_VERSION=#{...}` the installed ++// React Native's number, and a token with an Xcode `$(...)` (`$(PODS_ROOT)/ ++// #{...}`) is dropped for that already. ++function unresolvedInterpolations(text /*: string */) /*: Array */ { ++ const out = []; ++ for (let i = text.indexOf('#{'); i >= 0; i = text.indexOf('#{', i + 2)) { ++ let depth = 0; ++ let end = -1; ++ for (let j = i + 1; j < text.length; j++) { ++ if (text[j] === '{') depth++; ++ else if (text[j] === '}' && --depth === 0) { ++ end = j; ++ break; ++ } ++ } ++ if (end < 0) break; ++ const before = text.slice(0, i).split(/[\s"']/).pop() ?? ''; ++ const after = text.slice(end + 1).split(/[\s"']/)[0] ?? ''; ++ const token = before + text.slice(i, end + 1) + after; ++ const rnVersion = /REACT_NATIVE_(?:MAJOR|MINOR|PATCH)_VERSION=$/.test(before); ++ if (!rnVersion && !/\$[({]/.test(token)) out.push(text.slice(i, end + 1)); ++ } ++ return out; ++} ++// The first value in `v` it could not evaluate (also inside arrays and hashes). ++function unresolvedIn(v /*: mixed */) /*: ?RubyUnresolved */ { ++ if (v instanceof RubyUnresolved) return v; ++ if (Array.isArray(v)) { ++ for (const x of v) { ++ const u = unresolvedIn(x); ++ if (u != null) return u; ++ } ++ } ++ if (v instanceof RubyHash) { ++ for (const {value} of v.entries.values()) { ++ const u = unresolvedIn(value); ++ if (u != null) return u; ++ } ++ } ++ return null; ++} +const PLATFORM_SCOPES /*: Set */ = new Set([ + 'ios', + 'osx', @@ -186,13 +308,19 @@ index 8fcf04b..6ed3f14 100644 + const text = m != null ? m[0] : c; + tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); + i += text.length; -+ } else if (/[A-Za-z_]/.test(c)) { -+ const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); ++ } else if (/[A-Za-z_]/.test(c) || (c === '$' && /[A-Za-z_]/.test(src[i + 1] ?? ''))) { ++ // `$name` is a global. ++ const m = src.slice(i).match(/^\$?[A-Za-z_]\w*(?:[?!](?=\())?/); + const text = m != null ? m[0] : c; + tokens.push({t: 'id', v: text}); + i += text.length; -+ } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { -+ tokens.push({t: 'bad', v: src.slice(i)}); // a symbol ++ } else if (c === ':' && /[A-Za-z_]/.test(src[i + 1] ?? '') && src[i - 1] !== ':') { ++ const m = src.slice(i + 1).match(/^[A-Za-z_]\w*[?!]?/); ++ const text = m != null ? m[0] : ''; ++ tokens.push({t: 'sym', v: text}); ++ i += 1 + text.length; ++ } else if (c === ':' && /["']/.test(src[i + 1] ?? '')) { ++ tokens.push({t: 'bad', v: src.slice(i)}); // a quoted symbol + i = src.length; + } else { + const two = src.slice(i, i + 2); @@ -214,6 +342,9 @@ index 8fcf04b..6ed3f14 100644 + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); + } ++ if (a instanceof RubySymbol && b instanceof RubySymbol) { ++ return a.name === b.name; ++ } + return a === b; +} + @@ -222,9 +353,26 @@ index 8fcf04b..6ed3f14 100644 + if (typeof v === 'string') return v; + if (v == null) return ''; + if (typeof v === 'boolean' || typeof v === 'number') return String(v); ++ if (v instanceof RubySymbol) return v.name; + return new RubyUnresolved('an array or hash inside `#{...}`'); +} + ++// `File.read` reads only inside the podspec's own directory. ++function readInside(dir /*: mixed */, file /*: mixed */) /*: mixed */ { ++ if (typeof dir !== 'string' || typeof file !== 'string') { ++ return new RubyUnresolved('`File.read` of a path it cannot evaluate'); ++ } ++ const full = path.resolve(dir, file); ++ if (full !== dir && !full.startsWith(dir + path.sep)) { ++ return new RubyUnresolved(`\`File.read\` outside the podspec's directory (${file})`); ++ } ++ try { ++ return fs.readFileSync(full, 'utf8'); ++ } catch { ++ return new RubyUnresolved(`\`File.read\` of a file that cannot be read (${path.relative(dir, full)})`); ++ } ++} ++ +/** + * Evaluates one Ruby expression with the locals in `env`. Returns the value, + * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list @@ -257,6 +405,27 @@ index 8fcf04b..6ed3f14 100644 + if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; + } while (depth > 0); + }; ++ // `{k => v, k: v}` (already past `{`). A value it cannot evaluate stays in ++ // the hash as unresolved, so the other entries can still be read. ++ const parseHash = () => { ++ const h = new RubyHash(); ++ while (!peek('}')) { ++ if (tokens[pos] == null) return fail('a missing `}`'); ++ let key; ++ if (tokens[pos].t === 'id' && tokens[pos + 1]?.t === 'op' && tokens[pos + 1].v === ':') { ++ key = new RubySymbol(tokens[pos].v); ++ pos += 2; ++ } else { ++ key = parseTernary(); ++ if (!take('=>')) return fail('a hash entry without `=>`'); ++ } ++ const value = parseTernary(); ++ if (isUnresolved(key) || !h.set(key, value)) return fail('a hash key it cannot evaluate'); ++ if (!take(',')) break; ++ } ++ if (!take('}')) return fail('a missing `}`'); ++ return h; ++ }; + // Comma-separated expressions up to `close` (already past the opener). + const parseItems = (close /*: string */) => { + const items = []; @@ -266,26 +435,34 @@ index 8fcf04b..6ed3f14 100644 + if (!take(',')) break; + } + if (!take(close)) return fail(`a missing \`${close}\``); -+ return items.find(isUnresolved) ?? items; ++ // A partial string stays an element; anything else unknown fails it. ++ return items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; + }; + function parsePrimary() /*: mixed */ { + const tk = tokens[pos++]; + if (tk == null) return fail('an incomplete expression'); + if (tk.t === 'str') { + let out = ''; ++ let why = null; + for (const part of tk.parts) { + if (typeof part === 'string') { + out += part; + continue; + } + const inner = evalRubyExpr(part.expr, env); -+ if (isUnresolved(inner)) return inner; -+ const s = rubyToS(inner); -+ if (isUnresolved(s)) return s; -+ out += (s /*: any */); ++ const s = isUnresolved(inner) ? inner : rubyToS(inner); ++ if (typeof s === 'string') { ++ out += s; ++ continue; ++ } ++ // Kept as written, or as the partial text of a partial string. ++ const u /*: RubyUnresolved */ = (s /*: any */); ++ why ??= u.why; ++ out += u.partial ?? `#{${part.expr}}`; + } -+ return out; ++ return why != null ? new RubyUnresolved(why, out) : out; + } ++ if (tk.t === 'sym') return new RubySymbol(tk.v); + if (tk.t === 'words') return tk.v; + if (tk.t === 'num') return tk.v; + if (tk.t === 'bad') return fail(`\`${tk.v}\``); @@ -295,7 +472,7 @@ index 8fcf04b..6ed3f14 100644 + return take(')') ? v : fail('a missing `)`'); + } + if (tk.v === '[') return parseItems(']'); -+ if (tk.v === '{') return fail('a hash'); ++ if (tk.v === '{') return parseHash(); + return fail(`\`${tk.v}\``); + } + // An identifier. @@ -321,14 +498,50 @@ index 8fcf04b..6ed3f14 100644 + } + return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); + } ++ // The package.json load podspecs share: `JSON.parse(File.read(File.join( ++ // __dir__, "package.json")))`, also with `File.dirname(__FILE__)`. ++ if ((name === 'File' || name === 'JSON') && peek('.')) { ++ pos++; ++ const m = tokens[pos++]; ++ const method = m != null && m.t === 'id' ? m.v : '?'; ++ const call = `${name}.${method}`; ++ if (!take('(')) return fail(`the method \`${call}\``); ++ const args = parseItems(')'); ++ if (isUnresolved(args)) return args; ++ const a = (args /*: any */); ++ if (call === 'File.join' && a.every(x => typeof x === 'string')) { ++ return path.join(...a); ++ } ++ if (call === 'File.dirname' && typeof a[0] === 'string') { ++ return path.dirname(a[0]); ++ } ++ if (call === 'File.read' && a.length === 1) { ++ return readInside(env.get('__dir__'), a[0]); ++ } ++ if (call === 'JSON.parse' && typeof a[0] === 'string') { ++ try { ++ return fromJson(JSON.parse(a[0])); ++ } catch { ++ return fail('`JSON.parse` of text that is not JSON'); ++ } ++ } ++ return fail(`the method call \`${call}(...)\``); ++ } + if (peek('(')) { + skipGroup(); + return fail(`the method call \`${name}(...)\``); + } -+ if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); ++ if (!env.has(name)) { ++ return fail( ++ name.startsWith('$') ++ ? `the global \`${name}\`, which the podspec does not set` ++ : `the unknown identifier \`${name}\``, ++ ); ++ } + const v = env.get(name); + if (isUnresolved(v)) { -+ return fail(`\`${name}\`, which ${(v /*: any */).why}`); ++ const u /*: RubyUnresolved */ = (v /*: any */); ++ return new RubyUnresolved(`\`${name}\`, which ${u.why}`, u.partial); + } + return v; + } @@ -336,9 +549,13 @@ index 8fcf04b..6ed3f14 100644 + let v = parsePrimary(); + while (peek('.') || peek('[')) { + if (take('[')) { -+ pos--; -+ skipGroup(); -+ v = isUnresolved(v) ? v : fail('an index `[...]`'); ++ const key = parseTernary(); ++ if (!take(']')) return fail('a missing `]`'); ++ if (isUnresolved(v)) continue; ++ if (isUnresolved(key)) v = key; ++ else if (v instanceof RubyHash) v = v.get(key); ++ else if (Array.isArray(v) && typeof key === 'number') v = v[key] ?? null; ++ else v = fail('an index `[...]` on a value it cannot index'); + continue; + } + take('.'); @@ -360,10 +577,19 @@ index 8fcf04b..6ed3f14 100644 + } + if (method === 'join' && Array.isArray(v)) { + const sep = args.length > 0 ? args[0] : ''; -+ const parts = v.flat(Infinity).map(rubyToS); -+ const bad = parts.find(isUnresolved); -+ v = -+ bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); ++ const parts = v ++ .flat(Infinity) ++ .map(x => (isUnresolved(x) ? x : rubyToS(x))); ++ const texts = parts.map(rubyText); ++ const partial = parts.find(isUnresolved); ++ if (typeof sep !== 'string') v = fail('`join`'); ++ else if (texts.every(x => x != null)) { ++ const joined = texts.join(sep); ++ v = ++ partial != null ++ ? new RubyUnresolved((partial /*: any */).why, joined) ++ : joined; ++ } else v = partial; + continue; + } + v = fail(`the method call \`.${method}\``); @@ -381,6 +607,13 @@ index 8fcf04b..6ed3f14 100644 + let l = parseUnary(); + while (take('+')) { + const r = parseUnary(); ++ const lt = rubyText(l); ++ const rt = rubyText(r); ++ if (lt != null && rt != null && (isUnresolved(l) || isUnresolved(r))) { ++ const u /*: RubyUnresolved */ = (isUnresolved(l) ? l : r /*: any */); ++ l = new RubyUnresolved(u.why, lt + rt); ++ continue; ++ } + if (isUnresolved(l)) continue; + if (isUnresolved(r)) l = r; + else if (typeof l === 'string' && typeof r === 'string') l = l + r; @@ -439,7 +672,7 @@ index 8fcf04b..6ed3f14 100644 + if (list === true && peek(',')) { + const items = [value]; + while (take(',')) items.push(parseTernary()); -+ value = items.find(isUnresolved) ?? items; ++ value = items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; + } + if (pos < tokens.length && !isUnresolved(value)) { + const rest = tokens[pos]; @@ -462,15 +695,29 @@ index 8fcf04b..6ed3f14 100644 + ).test(rhs.trim()); +} + -+// The literal a field is rewritten to, or null when the value has none. ++// The literal a field is rewritten to, or null when the value has none. A ++// partial string is written with its `#{...}` as written; a hash entry whose ++// value has no literal is left out (the field regexes never read it). +function rubyLiteral(v /*: mixed */) /*: ?string */ { -+ if (typeof v === 'string') return JSON.stringify(v); ++ const text = rubyText(v); ++ if (text != null) return JSON.stringify(text); + if (typeof v === 'boolean') return String(v); + if (Array.isArray(v)) { -+ const flat = v.flat(Infinity); -+ if (!flat.every(x => typeof x === 'string')) return null; ++ const flat = v.flat(Infinity).map(rubyText); ++ if (!flat.every(x => x != null)) return null; + return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; + } ++ if (v instanceof RubyHash) { ++ const items = []; ++ for (const {key, value} of v.entries.values()) { ++ const lit = rubyLiteral(value); ++ if (lit == null) continue; ++ const k = ++ key instanceof RubySymbol ? `:${key.name}` : JSON.stringify(key); ++ items.push(`${k} => ${lit}`); ++ } ++ return `{ ${items.join(', ')} }`; ++ } + return null; +} + @@ -567,7 +814,11 @@ index 8fcf04b..6ed3f14 100644 + +/*:: +type Unresolved = {field: string, expr: string, why: string}; -+type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; ++type Activity = { ++ state: 'yes' | 'no' | 'maybe' | 'opaque', ++ why: string, ++ modifier?: boolean, ++}; +*/ + +// Why a local set under `act` is unknown from there on. @@ -600,12 +851,41 @@ index 8fcf04b..6ed3f14 100644 + */ +function evaluateRubyLocals( + content /*: string */, -+) /*: {text: string, unresolved: Array} */ { ++ podspecPath /*:: ?: string */, ++) /*: {text: string, unresolved: Array, dropped: Array} */ { + const lines = content.split('\n'); + const out = lines.slice(); + const env /*: Map */ = new Map(); ++ if (podspecPath != null) { ++ env.set('__dir__', path.dirname(path.resolve(podspecPath))); ++ env.set('__FILE__', path.resolve(podspecPath)); ++ } + const recvs /*: Set */ = new Set(); + const unresolved /*: Array */ = []; ++ // What was left out of an xcconfig value the scaffolder reads, as warnings. ++ const dropped /*: Array */ = []; ++ const noteXcconfig = (lhs /*: string */, text /*: string */) => { ++ for (const m of text.matchAll(XCCONFIG_READ_KEY_RE)) { ++ const start = (m.index ?? 0) + m[0].length; ++ XCCONFIG_ANY_KEY_RE.lastIndex = start; ++ const next = XCCONFIG_ANY_KEY_RE.exec(text); ++ const value = text.slice(start, next != null ? next.index : undefined); ++ const key = m[2] + (m[3] ?? ''); ++ for (const span of unresolvedInterpolations(value)) { ++ dropped.push( ++ `Left out of ${lhs} ${key}: \`${span}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, ++ ); ++ } ++ const bare = value.match(/^\s*([A-Za-z_$]\w*)\s*,?\s*\}?\s*$/); ++ if (bare != null && rubyText(env.get(bare[1])) == null) { ++ dropped.push( ++ `Left out of ${lhs} ${key}: \`${bare[1]}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, ++ ); ++ } ++ } ++ }; ++ const statementText = (st /*: {start: number, end: number} */) => ++ out.slice(st.start, st.end + 1).join('\n'); + // `if` blocks (which branch is being read) and other blocks. + const frames /*: Array */ = []; + const blank = (st /*: {start: number, end: number} */) => { @@ -636,10 +916,9 @@ index 8fcf04b..6ed3f14 100644 + st /*: {start: number, end: number} */, + hash /*: boolean */, + ) => { -+ const known = (id /*: string */) => { -+ const v = env.get(id); -+ return typeof v === 'string' ? v : null; -+ }; ++ // Spliced into a double-quoted literal, so its own quotes are escaped. ++ const known = (id /*: string */) => ++ rubyText(env.get(id))?.replace(/[\\"]/g, '\\$&'); + for (let k = st.start; k <= st.end; k++) { + out[k] = out[k].replace( + /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, @@ -662,12 +941,38 @@ index 8fcf04b..6ed3f14 100644 + } + } + }; ++ // A local set in a branch of a condition it cannot evaluate keeps its value ++ // for the rest of that branch (webview sets `folly_compiler_flags` and uses ++ // it in `compiler_flags` under `defined?(...)`), the next branch sees the ++ // value from before, and after `end` it is unknown. In any other block it ++ // does not run, or under a modifier, it is unknown at once. + const setLocal = ( + name /*: string */, + value /*: mixed */, + act /*: Activity */, + ) => { -+ env.set(name, act.state === 'yes' ? value : unknownUnder(act)); ++ if (act.state === 'yes') { ++ env.set(name, value); ++ return; ++ } ++ const frame = act.modifier ++ ? null ++ : [...frames].reverse().find(f => f.kind === 'if' && f.branch === 'maybe'); ++ if (frame == null) { ++ env.set(name, unknownUnder(act)); ++ return; ++ } ++ if (!frame.saved.has(name)) { ++ frame.saved.set(name, env.has(name) ? {value: env.get(name)} : null); ++ } ++ env.set(name, value); ++ }; ++ // The next branch of `frame` sees the locals as they were before it. ++ const restoreSaved = (frame /*: any */) => { ++ for (const [name, saved] of frame.saved) { ++ if (saved == null) env.delete(name); ++ else env.set(name, saved.value); ++ } + }; + + for (const st of rubyStatements(lines)) { @@ -689,14 +994,17 @@ index 8fcf04b..6ed3f14 100644 + branch, + prior: act.state === 'no' ? 'yes' : branch, + cond: m[2], ++ firstCond: m[2], + evaluated: branch !== 'maybe' && branch !== 'opaque', + ctrl: [st], ++ saved: new Map(), + }); + continue; + } + if (top?.kind === 'if') { + if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { + top.ctrl.push(st); ++ restoreSaved(top); + if (top.branch === 'opaque') continue; + const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); + if (cond === 'maybe') top.evaluated = false; @@ -705,6 +1013,7 @@ index 8fcf04b..6ed3f14 100644 + } + if (code === 'else') { + top.ctrl.push(st); ++ restoreSaved(top); + if (top.branch !== 'opaque') { + top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; + } @@ -713,6 +1022,9 @@ index 8fcf04b..6ed3f14 100644 + } + if (/^end\b/.test(code) && top != null) { + frames.pop(); ++ for (const name of top.saved?.keys() ?? []) { ++ env.set(name, unknownUnder({state: 'maybe', why: top.firstCond})); ++ } + // An evaluated condition leaves no control lines behind. + if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { + for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); @@ -760,7 +1072,7 @@ index 8fcf04b..6ed3f14 100644 + continue; + } + if (c === 'maybe' && act.state === 'yes') { -+ stAct = {state: 'maybe', why: cond}; ++ stAct = {state: 'maybe', why: cond, modifier: true}; + } + } + // `recv.field = expr` on the spec or a subspec. Under a condition it @@ -776,25 +1088,47 @@ index 8fcf04b..6ed3f14 100644 + (field[2] == null || PLATFORM_SCOPES.has(field[2])) + ) { + const [, recv, scope, name, rhs] = field; -+ // Only the spec's own and its `ios` scope count. ++ // Only the spec's own and its `ios` scope count. The identity fields ++ // keep fix 3's reading (literals only): evaluating `s.name = ++ // package['name']` would rename the scaffolded target. + if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; ++ if (IDENTITY_FIELDS.has(name)) { ++ interpolate(st, false); ++ continue; ++ } + const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; ++ const refuse = (why /*: string */) => ++ unresolved.push({field: lhs, expr: rhs.trim(), why}); ++ // A hash literal stays as written, its `#{local}` and `=> local` filled in. ++ if (/^\{/.test(rhs.trim())) { ++ interpolate(st, true); ++ if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, statementText(st)); ++ continue; ++ } + const v = evalRubyExpr(rhs, env, true); -+ const lit = isUnresolved(v) ? null : rubyLiteral(v); ++ const lit = rubyLiteral(v); ++ const u = unresolvedIn(v); ++ if (STRICT_FIELDS.has(name) && (lit == null || u != null)) { ++ refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); ++ } else if (WHOLE_FIELDS.has(name)) { ++ if (lit == null) { ++ refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); ++ } else if (u != null && unresolvedInterpolations(lit).length > 0) { ++ refuse(`it uses ${u.why}`); ++ } ++ } + if (lit != null) { + blank(st); + const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; + out[st.start] = `${indent}${lhs} = ${lit}`; -+ } else if (STRICT_FIELDS.has(name)) { -+ unresolved.push({ -+ field: lhs, -+ expr: rhs.trim(), -+ why: isUnresolved(v) -+ ? `it uses ${(v /*: any */).why}` -+ : 'its value is not a string or an array of strings', -+ }); ++ if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, lit); + } else { -+ interpolate(st, /^\{/.test(rhs.trim())); ++ interpolate(st, false); ++ if (XCCONFIG_FIELDS.has(name)) { ++ dropped.push( ++ `Left out ${lhs} = ${rhs.trim()}: the podspec reader cannot evaluate it${u != null ? ` (${u.why})` : ''}; CocoaPods passes its value.`, ++ ); ++ } + } + continue; + } @@ -816,6 +1150,7 @@ index 8fcf04b..6ed3f14 100644 + v = new RubyUnresolved( + `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + + `(${(v /*: any */).why})`, ++ (v /*: any */).partial, + ); + } + setLocal(name, v, stAct); @@ -851,7 +1186,7 @@ index 8fcf04b..6ed3f14 100644 + } + interpolate(st, false); + } -+ return {text: out.join('\n'), unresolved}; ++ return {text: out.join('\n'), unresolved, dropped: Array.from(new Set(dropped))}; +} + +// The library's own version. Podspecs load the package.json next to them @@ -896,7 +1231,7 @@ index 8fcf04b..6ed3f14 100644 // first non-whitespace character counts. +function readPodspecEvaluated( + podspecPath /*: string */, -+) /*: {text: string, unresolved: Array} */ { ++) /*: {text: string, unresolved: Array, dropped: Array} */ { + return evaluateRubyLocals( + resolvePackageVersion( + fs @@ -906,6 +1241,7 @@ index 8fcf04b..6ed3f14 100644 + .join('\n'), + path.dirname(podspecPath), + ), ++ podspecPath, + ); +} function readPodspecSource(podspecPath /*: string */) /*: string */ { @@ -1049,15 +1385,20 @@ index 8fcf04b..6ed3f14 100644 */ -function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { - const content = readPodspecSource(podspecPath); +- const warnings /*: Array */ = []; +function regexPodspec( + podspecPath /*: string */, + opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, +) /*: RawSpec */ { -+ const {text: content, unresolved} = readPodspecEvaluated(podspecPath); ++ const { ++ text: content, ++ unresolved, ++ dropped: leftOut, ++ } = readPodspecEvaluated(podspecPath); + const dropped = new Set(opts?.dropSubspecs ?? []); + const mainName = mainReceiverName(content); + const MAIN_RECV = mainRecvPattern(mainName); - const warnings /*: Array */ = []; ++ const warnings /*: Array */ = [...leftOut]; + // The main spec's own statements, and each subspec block apart. The readers + // below default to the main text and receiver; a subspec is read with the + // same readers anchored on its block variable, then merged like @@ -1122,7 +1463,7 @@ index 8fcf04b..6ed3f14 100644 } // The fields that identify the spec, and only when the receiver spelling -@@ -235,9 +1248,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -235,9 +1588,27 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: // s. = ["a", "b"] (array) // s. = "single" (single value treated as 1-element array) @@ -1153,7 +1494,7 @@ index 8fcf04b..6ed3f14 100644 if (mArr != null) { const inner = mArr[1]; const out /*: Array */ = []; -@@ -249,16 +1280,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -249,16 +1620,37 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { } return out; } @@ -1196,7 +1537,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; out.push(m[1]); } -@@ -269,21 +1321,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -269,21 +1661,25 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // s.framework "X" → ["X"] // s.framework = "X" → ["X"] // s.frameworks = ["X","Y"] → ["X","Y"] @@ -1227,7 +1568,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; const itemRe = /["']([^"']+)["']/g; while (true) { -@@ -298,12 +1354,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -298,12 +1694,14 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { // Matches: 'HEADER_SEARCH_PATHS' => '...' or => ["...","..."] // Returns the raw token strings (still containing $(PODS_TARGET_SRCROOT) // etc.); substitution happens at translation time. @@ -1244,7 +1585,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; const itemRe = /["']((?:[^"'\\]|\\.)+)["']/g; while (true) { -@@ -321,7 +1379,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -321,7 +1719,7 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { const strRe = /["']HEADER_SEARCH_PATHS["']\s*=>\s*["']((?:[^"'\\]|\\.)+)["']/g; while (true) { @@ -1253,7 +1594,7 @@ index 8fcf04b..6ed3f14 100644 if (m == null) break; for (const token of m[1].split(/\s+/)) { if (token.length > 0) { -@@ -332,15 +1390,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -332,15 +1730,53 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { return Array.from(new Set(out)); } @@ -1309,7 +1650,7 @@ index 8fcf04b..6ed3f14 100644 ); } if (/install_modules_dependencies/.test(content)) { -@@ -354,26 +1450,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { +@@ -354,26 +1790,103 @@ function regexPodspec(podspecPath /*: string */) /*: RawSpec */ { ); } @@ -1426,7 +1767,7 @@ index 8fcf04b..6ed3f14 100644 }; } -@@ -423,6 +1596,58 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -423,6 +1936,58 @@ function shellTokenize(value /*: string */) /*: Array */ { return tokens; } @@ -1485,7 +1826,7 @@ index 8fcf04b..6ed3f14 100644 // --------------------------------------------------------------------------- // Subspec flattening // --------------------------------------------------------------------------- -@@ -438,8 +1663,16 @@ function shellTokenize(value /*: string */) /*: Array */ { +@@ -438,8 +2003,16 @@ function shellTokenize(value /*: string */) /*: Array */ { * - String fields → top-level wins; if absent, take the first subspec's value * - pod_target_xcconfig HEADER_SEARCH_PATHS → array-union across all selected subspecs * - dependencies → array-union of name strings (version constraints dropped) @@ -1503,7 +1844,7 @@ index 8fcf04b..6ed3f14 100644 const warnings /*: Array */ = []; // $FlowFixMe[prop-missing] dynamic shape const partial /*: boolean */ = rawSpec.__regex_partial__ === true; -@@ -456,7 +1689,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -456,7 +2029,12 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // - `default_subspecs`: array of names (or undefined → use all subspecs) const subspecs = Array.isArray(rawSpec.subspecs) ? rawSpec.subspecs : []; let selected = subspecs; @@ -1517,7 +1858,7 @@ index 8fcf04b..6ed3f14 100644 const wanted = new Set(rawSpec.default_subspecs); selected = subspecs.filter(s => { // $FlowFixMe[prop-missing] dynamic shape -@@ -464,6 +1702,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -464,6 +2042,10 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return name != null && wanted.has(name); }); } @@ -1528,7 +1869,7 @@ index 8fcf04b..6ed3f14 100644 const layers = [rawSpec, ...selected]; function mergeArrayField(key /*: string */) /*: Array */ { -@@ -482,6 +1724,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -482,6 +2064,17 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return Array.from(new Set(out)); } @@ -1546,7 +1887,7 @@ index 8fcf04b..6ed3f14 100644 // Only the spec's own value: a subspec's `header_dir` names that subspec's // headers, and several subspecs can disagree. function specStringField(key /*: string */) /*: string | null */ { -@@ -544,6 +1797,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -544,6 +2137,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // `-D`s are safe to forward; arbitrary flags may be machine- or // example-app-specific. $(inherited), unresolved $(...) tokens, and invalid // C identifiers are skipped. @@ -1567,7 +1908,7 @@ index 8fcf04b..6ed3f14 100644 function mergePreprocessorDefines() /*: Array */ { const out /*: Array */ = []; const seen /*: Set */ = new Set(); -@@ -554,7 +1821,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -554,7 +2161,23 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { config /*: ?('debug' | 'release') */, ) => { if (!validName.test(name)) return; @@ -1592,7 +1933,7 @@ index 8fcf04b..6ed3f14 100644 return; // unresolved Xcode/Ruby token — don't emit a broken define } const key = `${name}|${config ?? ''}`; -@@ -571,6 +1854,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -571,6 +2194,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { 'xcconfig', 'user_target_xcconfig', ]; @@ -1613,7 +1954,7 @@ index 8fcf04b..6ed3f14 100644 for (const layer of layers) { if (layer == null || typeof layer !== 'object') continue; for (const xcKey of XCCONFIG_KEYS) { -@@ -627,44 +1924,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -627,44 +2264,119 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { return out; } @@ -1758,7 +2099,7 @@ index 8fcf04b..6ed3f14 100644 } } return out; -@@ -677,6 +2049,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -677,6 +2389,20 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { ? false : true; // RN ecosystem default @@ -1779,7 +2120,7 @@ index 8fcf04b..6ed3f14 100644 return { name: specStringField('name') ?? '', version: specStringField('version') ?? '', -@@ -693,23 +2079,81 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -693,23 +2419,82 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { // header_mappings_dir copy step, which SPM has no equivalent for. headerMappingsDirs: mergeArrayField('header_mappings_dir'), headerDir: specStringField('header_dir'), @@ -1853,17 +2194,18 @@ index 8fcf04b..6ed3f14 100644 + .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) + .join('; ') + + '. The podspec reader evaluates locals, string interpolation, arrays, ' + -+ "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + -+ 'the globs it could read would leave some of the library\'s files out of ' + -+ 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + -+ 'reads the podspec, or give the library a Package.swift of its own.' ++ "ENV['...'], package.json reads, comparisons, ternaries and if/unless " + ++ 'blocks; building from the part it could read would leave some of the ' + ++ "library's files or settings out of its target. Install CocoaPods (`gem " + ++ 'install cocoapods`) so `pod ipc spec` reads the podspec, or give the ' + ++ 'library a Package.swift of its own.' + ); +} + // --------------------------------------------------------------------------- // Top-level entry // --------------------------------------------------------------------------- -@@ -722,15 +2166,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { +@@ -722,15 +2507,18 @@ function flattenSubspecs(rawSpec /*: RawSpec */) /*: PodspecModel */ { * Throws when the file doesn't exist. Otherwise always returns a * PodspecModel — warnings on the model surface partial parses to the * caller, who can decide whether to proceed or abort scaffolding for that @@ -1886,7 +2228,7 @@ index 8fcf04b..6ed3f14 100644 // Record whether the podspec calls `install_modules_dependencies(s)`. We // strip that helper before `pod ipc` and the regex parser can't expand it, // so the React-Core family it injects never lands in `model.dependencies`. -@@ -746,21 +2193,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { +@@ -746,21 +2534,46 @@ function readPodspec(podspecPath /*: string */) /*: PodspecModel */ { return model; } @@ -1937,7 +2279,7 @@ index 8fcf04b..6ed3f14 100644 podspecModels.set(key, model); return model; } -@@ -794,12 +2266,13 @@ function readPodspecNames( +@@ -794,12 +2607,13 @@ function readPodspecNames( if (hasShadowingSubspec(source)) { return null; } @@ -1952,7 +2294,7 @@ index 8fcf04b..6ed3f14 100644 const name = field('name'); const moduleName = field('module_name'); -@@ -840,4 +2313,5 @@ module.exports = { +@@ -840,4 +2654,5 @@ module.exports = { runPodIpcSpec, regexPodspec, flattenSubspecs, diff --git a/tests/fixtures/podspecs/RNWorklets-0.8.3/Common/cpp/worklets/Tools/WorkletsVersion.cpp b/tests/fixtures/podspecs/RNWorklets-0.8.3/Common/cpp/worklets/Tools/WorkletsVersion.cpp new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures/podspecs/RNWorklets-0.8.3/scripts/worklets_utils.rb b/tests/fixtures/podspecs/RNWorklets-0.8.3/scripts/worklets_utils.rb new file mode 100644 index 0000000..ffc4b4a --- /dev/null +++ b/tests/fixtures/podspecs/RNWorklets-0.8.3/scripts/worklets_utils.rb @@ -0,0 +1,103 @@ +def worklets_try_to_parse_react_native_package_json(node_modules_dir) + react_native_package_json_path = File.join(node_modules_dir, 'react-native/package.json') + if !File.exist?(react_native_package_json_path) + return nil + end + return JSON.parse(File.read(react_native_package_json_path)) +end + +def worklets_find_config() + result = { + :feature_flags_flag => nil, + :fetch_preview_flag => nil, + :is_reanimated_example_app => nil, + :is_tvos_target => nil, + :react_native_version => nil, + :react_native_minor_version => nil, + :react_native_node_modules_dir => nil, + :react_native_common_dir => nil, + } + + react_native_node_modules_dir = File.join(File.dirname(`cd "#{Pod::Config.instance.installation_root.to_s}" && node --print "require.resolve('react-native/package.json')"`), '..') + react_native_json = worklets_try_to_parse_react_native_package_json(react_native_node_modules_dir) + + if react_native_json == nil + # user configuration, just in case + node_modules_dir = ENV["REACT_NATIVE_NODE_MODULES_DIR"] + react_native_json = worklets_try_to_parse_react_native_package_json(node_modules_dir) + end + + if react_native_json == nil + raise '[Worklets] Unable to recognize your `react-native` version. Please set environmental variable with `react-native` location: `export REACT_NATIVE_NODE_MODULES_DIR="" && pod install`.' + end + + result[:is_reanimated_example_app] = ENV["IS_REANIMATED_EXAMPLE_APP"] != nil + result[:is_tvos_target] = react_native_json['name'] == 'react-native-tvos' + result[:react_native_version] = react_native_json['version'] + result[:react_native_minor_version] = react_native_json['version'].split('.')[1].to_i + if result[:react_native_minor_version] == 0 # nightly + result[:react_native_minor_version] = 1000 + end + result[:react_native_node_modules_dir] = File.expand_path(react_native_node_modules_dir) + + pods_root = Pod::Config.instance.project_pods_root + react_native_common_dir_absolute = File.join(react_native_node_modules_dir, 'react-native', 'ReactCommon') + react_native_common_dir_relative = Pathname.new(react_native_common_dir_absolute).relative_path_from(pods_root).to_s + result[:react_native_common_dir] = react_native_common_dir_relative + + feature_flags = worklets_get_static_feature_flags() + result[:feature_flags_flag] = worklets_get_static_feature_flags_flag(feature_flags) + result[:fetch_preview_flag] = worklets_get_flag_from_feature_flags(feature_flags, 'FETCH_PREVIEW_ENABLED') + + return result +end + +def worklets_assert_minimal_react_native_version(config) + validate_react_native_version_script = File.expand_path(File.join(__dir__, 'validate-react-native-version.js')) + unless system("node \"#{validate_react_native_version_script}\" #{config[:react_native_version]}") + raise "[Worklets] Your installed version of React Native is not compatible with installed version of Worklets. See the documentation for the list of supported versions: https://docs.swmansion.com/react-native-worklets/docs/guides/compatibility/" + end +end + +def worklets_assert_new_architecture_enabled(new_arch_enabled) + if !new_arch_enabled + raise "[Worklets] Worklets require the New Architecture to be enabled. If you have `RCT_NEW_ARCH_ENABLED=0` set in your environment you should remove it." + end +end + +def worklets_get_flag_from_feature_flags(feature_flags, flag_name) + if feature_flags[flag_name] == 'true' + return "-DWORKLETS_#{flag_name}" + else + return '' + end +end + +def worklets_get_static_feature_flags() + feature_flags = {} + + static_feature_flags_path = File.path('./src/featureFlags/staticFlags.json') + if !File.exist?(static_feature_flags_path) + raise "[Worklets] Feature flags file not found at #{static_feature_flags_path}." + end + static_feature_flags_json = JSON.parse(File.read(static_feature_flags_path)) + static_feature_flags_json.each do |key, value| + feature_flags[key] = value.to_s + end + + package_json_path = File.join(Pod::Config.instance.installation_root.to_s, '..', 'package.json') + if File.exist?(package_json_path) + package_json = JSON.parse(File.read(package_json_path)) + if package_json['worklets'] && package_json['worklets']['staticFeatureFlags'] + feature_flags_json = package_json['worklets']['staticFeatureFlags'] + feature_flags_json.each do |key, value| + feature_flags[key] = value.to_s + end + end + end + return feature_flags +end + +def worklets_get_static_feature_flags_flag(feature_flags) + return "-DWORKLETS_FEATURE_FLAGS=\"#{feature_flags.map { |key, value| "[#{key}:#{value}]" }.join('')}\"" +end diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 1551a88..21734e2 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -1267,20 +1267,22 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { expect(defineOf(pkg, "FOO_VERSION")).toBe("1.2.3"); }); - it('15: also reads #{package["version"]}, and still drops any other interpolation', () => { + it('15: also reads #{package["version"]} and the other keys of the package.json (fix 28)', () => { const files = { "ios/Foo.h": "", "ios/Foo.m": "", "package.json": JSON.stringify({ name: "foo", version: "1.2.3" }) }; const root = lib( files, ' pkg = JSON.parse(File.read(File.join(File.dirname(__FILE__), "package.json")))\n' + ' s.source_files = "ios/**/*.{h,m}"\n' + - ' s.compiler_flags = "-DFOO_VERSION=#{pkg["version"]} -DFOO_NAME=#{pkg[\'name\']} -DBAR=#{other[\'version\']}"\n' + + ' s.compiler_flags = "-DFOO_VERSION=#{pkg["version"]} -DFOO_NAME=#{pkg[\'name\']}"\n' + " s.pod_target_xcconfig = { \"OTHER_CFLAGS\" => \"$(inherited) -DFOO_V2=#{pkg['version']}\" }\n" + " s.xcconfig = { 'OTHER_CFLAGS' => '-DFOO_SQ=#{pkg[\"version\"]}' }", ); const { pkg } = scaffoldOne(root); expect(defineOf(pkg, "FOO_VERSION")).toBe("1.2.3"); + expect(defineOf(pkg, "FOO_NAME")).toBe("foo"); expect(defineOf(pkg, "FOO_V2")).toBe("1.2.3"); - for (const name of ["FOO_NAME", "BAR", "FOO_SQ"]) expect(pkg).not.toContain(`.define("${name}"`); + // Single quotes do not interpolate, as in Ruby. + expect(pkg).not.toContain('.define("FOO_SQ"'); }); it("16: maps subspec header_mappings_dir under header_dir", () => { @@ -2499,8 +2501,10 @@ describe("scaffolder fix 28: podspec locals and conditions (vendor/rn-spm)", () ["a method call", ' s.source_files = Dir.glob("ios/*.m")', "source_files", 'Dir.glob("ios/*.m")'], ["an interpolated call", ' s.exclude_files = "ios/#{helper(1)}/**"', "exclude_files", '"ios/#{helper(1)}/**"'], ["a local built from a call", ' srcs = ["ios/*.m"] + extra_sources\n s.source_files = srcs', "source_files", "srcs"], + ["a method call in compiler_flags", ' s.source_files = "ios/*.m"\n s.compiler_flags = "-DFOO=#{helper(1)}"', "compiler_flags", "helper(...)"], + ["an unknown local as header_dir", ' s.source_files = "ios/*.m"\n s.header_dir = mystery_dir', "header_dir", "mystery_dir"], ["a local set under a condition it cannot evaluate", " if respond_to?(:foo)\n exts = '{h,m}'\n end\n s.source_files = \"ios/*.#{exts}\"", "source_files", "respond_to?(:foo)"], - ])("28: refuses %s in a source glob, naming the podspec, the field and the expression", (_, body, field, expr) => { + ])("28: refuses %s, naming the podspec, the field and the expression", (_, body, field, expr) => { const run = scaffoldPod(podLib(FILES, `Pod::Spec.new do |s|\n s.name = "Foo"\n${body}\nend\n`)); const res = run.results[0]!; expect(res.status).toBe("error"); @@ -2510,6 +2514,44 @@ describe("scaffolder fix 28: podspec locals and conditions (vendor/rn-spm)", () expect(run.files["react-native-foo/Package.swift"]).toBeUndefined(); }); + it("28: keeps worklets 0.8.3's version defines and names the flags it leaves out", () => { + // `version_flags = "-DWORKLETS_VERSION=#{package['version']} -DREACT_NATIVE_MINOR_VERSION=#{$worklets_config[...]}"` + // in OTHER_CFLAGS: the version comes from its package.json, the React Native minor from the installed React Native + // (fix 8; the harness installs 0.86.3). The first fix 28 lost both: WorkletsVersion.cpp did not compile. + const run = scaffoldLibraries(VENDORED_RN_SPM, { "react-native-worklets": fixture("RNWorklets-0.8.3") }); + expect(run.results[0]?.status, run.results[0]?.reason).toBe("written"); + const cxx = run.files["react-native-worklets/Package.swift"]!.split("\n").find((l) => l.trim().startsWith("cxxSettings:"))!; + expect(cxx).toContain('.define("WORKLETS_VERSION", to: "0.8.3")'); + expect(cxx).toContain('.define("REACT_NATIVE_MINOR_VERSION", to: "86")'); + expect(cxx).toContain('.define("HERMES_V1_ENABLED")'); + // Its static feature flags come from a Ruby helper the reader does not run: named, not dropped silently. + for (const span of ["#{feature_flags}", "#{fetch_preview_flag}"]) { + expect(run.results[0]?.warnings, span).toContain( + `Left out of s.pod_target_xcconfig OTHER_CFLAGS: \`${span}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, + ); + } + }); + + it("28: reads a hash held in a local, and package.json keys in any field", () => { + const podspec = + 'package = JSON.parse(File.read(File.join(__dir__, "package.json")))\n' + + "flags = []\n" + + 'flags << "-DFOO_DEBUG=1" if ENV["FOO_DEBUG"] == "1"\n' + + "config = { 'OTHER_CFLAGS' => \"$(inherited) -DFOO_NAME=#{package['name']} #{flags.join(' ')}\" }\n" + + "Pod::Spec.new do |s|\n" + + ' s.name = "Foo"\n' + + " s.version = package['version']\n" + + ' s.source_files = "ios/*.{h,mm}"\n' + + " s.pod_target_xcconfig = config\n" + + "end\n"; + const run = scaffoldPod(podLib(FILES, podspec)); + expect(run.results[0]?.status, run.results[0]?.reason).toBe("written"); + const pkg = run.files["react-native-foo/Package.swift"]!; + expect(pkg).toContain('.define("FOO_NAME", to: "foo")'); + expect(pkg).not.toContain("FOO_DEBUG"); + expect(run.results[0]?.warnings?.filter((w) => w.startsWith("Left out"))).toEqual([]); + }); + it("28: reads both branches of a condition it cannot evaluate, as before", () => { // The `respond_to?(:install_modules_dependencies, true)` idiom, and a literal glob under such a condition // (react-native-vision-camera's `if enableFrameProcessors` subspec, fix 20): both branches stay visible. diff --git a/vendor/rn-spm/rn-xtool-edits.patch b/vendor/rn-spm/rn-xtool-edits.patch index 3309c15..ba885c1 100644 --- a/vendor/rn-spm/rn-xtool-edits.patch +++ b/vendor/rn-spm/rn-xtool-edits.patch @@ -161,7 +161,7 @@ resolveLocalHermesCompilerVersion, --- a/spm/read-podspec.js +++ b/spm/read-podspec.js -@@ -2195,9 +2195,15 @@ +@@ -2536,9 +2536,15 @@ // The installed React Native's version as the macros libraries derive from it. function readRnVersionMacros() /*: {[string]: number} */ { diff --git a/vendor/rn-spm/spm/read-podspec.js b/vendor/rn-spm/spm/read-podspec.js index 5dfc1a5..5b93d34 100644 --- a/vendor/rn-spm/spm/read-podspec.js +++ b/vendor/rn-spm/spm/read-podspec.js @@ -232,21 +232,143 @@ const RN_POD_ENV /*: {[string]: string} */ = { RCT_HERMES_V1_ENABLED: '1', }; -// A value the evaluator could not compute, and why. +// A value the evaluator could not compute, and why. A string with an +// interpolation it could not compute keeps that `#{...}` as written in +// `partial`, as fix 3's pass did: fix 8 still reads +// `REACT_NATIVE_MINOR_VERSION=#{...}` from it, and what is left is reported. class RubyUnresolved { - /*:: why: string; */ - constructor(why /*: string */) { + /*:: why: string; partial: ?string; */ + constructor(why /*: string */, partial /*:: ?: ?string */) { this.why = why; + this.partial = partial ?? null; } } const isUnresolved = (v /*: mixed */) /*: boolean */ => v instanceof RubyUnresolved; +// A string value's text, also a partial one's; null for anything else. +function rubyText(v /*: mixed */) /*: ?string */ { + if (typeof v === 'string') return v; + return v instanceof RubyUnresolved ? v.partial : null; +} +// A Ruby symbol (`:name`). +class RubySymbol { + /*:: name: string; */ + constructor(name /*: string */) { + this.name = name; + } +} +// A Ruby hash: insertion-ordered, keyed by string or symbol. +class RubyHash { + /*:: entries: Map; */ + constructor() { + this.entries = new Map(); + } + static keyOf(k /*: mixed */) /*: ?string */ { + if (typeof k === 'string') return `s:${k}`; + if (k instanceof RubySymbol) return `y:${k.name}`; + return null; + } + get(k /*: mixed */) /*: mixed */ { + const key = RubyHash.keyOf(k); + return key != null ? (this.entries.get(key)?.value ?? null) : null; + } + set(k /*: mixed */, value /*: mixed */) /*: boolean */ { + const key = RubyHash.keyOf(k); + if (key == null) return false; + this.entries.set(key, {key: k, value}); + return true; + } +} +// JSON (a package.json) as Ruby values: objects become hashes with string keys. +function fromJson(v /*: mixed */) /*: mixed */ { + if (Array.isArray(v)) return v.map(fromJson); + if (v != null && typeof v === 'object') { + const h = new RubyHash(); + for (const [k, x] of Object.entries(v)) h.set(k, fromJson(x)); + return h; + } + return v; +} // The source-glob fields an unevaluated expression must not reach silently. const STRICT_FIELDS /*: Set */ = new Set([ 'source_files', 'exclude_files', ]); +// Fields that name the library: read as literals only, as before. +const IDENTITY_FIELDS /*: Set */ = new Set([ + 'name', + 'module_name', + 'version', +]); +// Fields whose whole value an unevaluated part changes: refused too. +const WHOLE_FIELDS /*: Set */ = new Set([ + 'compiler_flags', + 'header_dir', + 'header_mappings_dir', + 'frameworks', + 'framework', + 'weak_frameworks', + 'weak_framework', + 'libraries', + 'library', +]); +// The xcconfig hashes, and the keys of them the scaffolder reads. A part of +// those values it cannot evaluate is left out with a warning that names it: +// podspecs put optional, configuration-driven flags there (worklets' static +// feature flags, vision-camera's frame processor switch), which CocoaPods +// computes from the app and the Podfile. +const XCCONFIG_FIELDS /*: Set */ = new Set([ + 'pod_target_xcconfig', + 'user_target_xcconfig', + 'xcconfig', +]); +const XCCONFIG_READ_KEY_RE = + /(["'])(OTHER_CFLAGS|GCC_PREPROCESSOR_DEFINITIONS|HEADER_SEARCH_PATHS|SWIFT_ACTIVE_COMPILATION_CONDITIONS)(\[[^\]]*\])?\1\s*=>/g; +const XCCONFIG_ANY_KEY_RE = /(["'])[A-Z_]+(\[[^\]]*\])?\1\s*=>/g; + +// Each `#{...}` left in `text` that the scaffolder does not handle itself. +// Fix 8 gives `REACT_NATIVE_{MAJOR,MINOR,PATCH}_VERSION=#{...}` the installed +// React Native's number, and a token with an Xcode `$(...)` (`$(PODS_ROOT)/ +// #{...}`) is dropped for that already. +function unresolvedInterpolations(text /*: string */) /*: Array */ { + const out = []; + for (let i = text.indexOf('#{'); i >= 0; i = text.indexOf('#{', i + 2)) { + let depth = 0; + let end = -1; + for (let j = i + 1; j < text.length; j++) { + if (text[j] === '{') depth++; + else if (text[j] === '}' && --depth === 0) { + end = j; + break; + } + } + if (end < 0) break; + const before = text.slice(0, i).split(/[\s"']/).pop() ?? ''; + const after = text.slice(end + 1).split(/[\s"']/)[0] ?? ''; + const token = before + text.slice(i, end + 1) + after; + const rnVersion = /REACT_NATIVE_(?:MAJOR|MINOR|PATCH)_VERSION=$/.test(before); + if (!rnVersion && !/\$[({]/.test(token)) out.push(text.slice(i, end + 1)); + } + return out; +} +// The first value in `v` it could not evaluate (also inside arrays and hashes). +function unresolvedIn(v /*: mixed */) /*: ?RubyUnresolved */ { + if (v instanceof RubyUnresolved) return v; + if (Array.isArray(v)) { + for (const x of v) { + const u = unresolvedIn(x); + if (u != null) return u; + } + } + if (v instanceof RubyHash) { + for (const {value} of v.entries.values()) { + const u = unresolvedIn(value); + if (u != null) return u; + } + } + return null; +} const PLATFORM_SCOPES /*: Set */ = new Set([ 'ios', 'osx', @@ -329,13 +451,19 @@ function tokenizeRubyExpr(src /*: string */) /*: Array */ { const text = m != null ? m[0] : c; tokens.push({t: 'num', v: Number(text.replace(/_/g, ''))}); i += text.length; - } else if (/[A-Za-z_]/.test(c)) { - const m = src.slice(i).match(/^[A-Za-z_]\w*(?:[?!](?=\())?/); + } else if (/[A-Za-z_]/.test(c) || (c === '$' && /[A-Za-z_]/.test(src[i + 1] ?? ''))) { + // `$name` is a global. + const m = src.slice(i).match(/^\$?[A-Za-z_]\w*(?:[?!](?=\())?/); const text = m != null ? m[0] : c; tokens.push({t: 'id', v: text}); i += text.length; - } else if (c === ':' && /[A-Za-z_"']/.test(src[i + 1] ?? '')) { - tokens.push({t: 'bad', v: src.slice(i)}); // a symbol + } else if (c === ':' && /[A-Za-z_]/.test(src[i + 1] ?? '') && src[i - 1] !== ':') { + const m = src.slice(i + 1).match(/^[A-Za-z_]\w*[?!]?/); + const text = m != null ? m[0] : ''; + tokens.push({t: 'sym', v: text}); + i += 1 + text.length; + } else if (c === ':' && /["']/.test(src[i + 1] ?? '')) { + tokens.push({t: 'bad', v: src.slice(i)}); // a quoted symbol i = src.length; } else { const two = src.slice(i, i + 2); @@ -357,6 +485,9 @@ function rubyEqual(a /*: mixed */, b /*: mixed */) /*: boolean */ { if (Array.isArray(a) && Array.isArray(b)) { return a.length === b.length && a.every((x, k) => rubyEqual(x, b[k])); } + if (a instanceof RubySymbol && b instanceof RubySymbol) { + return a.name === b.name; + } return a === b; } @@ -365,9 +496,26 @@ function rubyToS(v /*: mixed */) /*: string | RubyUnresolved */ { if (typeof v === 'string') return v; if (v == null) return ''; if (typeof v === 'boolean' || typeof v === 'number') return String(v); + if (v instanceof RubySymbol) return v.name; return new RubyUnresolved('an array or hash inside `#{...}`'); } +// `File.read` reads only inside the podspec's own directory. +function readInside(dir /*: mixed */, file /*: mixed */) /*: mixed */ { + if (typeof dir !== 'string' || typeof file !== 'string') { + return new RubyUnresolved('`File.read` of a path it cannot evaluate'); + } + const full = path.resolve(dir, file); + if (full !== dir && !full.startsWith(dir + path.sep)) { + return new RubyUnresolved(`\`File.read\` outside the podspec's directory (${file})`); + } + try { + return fs.readFileSync(full, 'utf8'); + } catch { + return new RubyUnresolved(`\`File.read\` of a file that cannot be read (${path.relative(dir, full)})`); + } +} + /** * Evaluates one Ruby expression with the locals in `env`. Returns the value, * or a RubyUnresolved saying why it cannot. `list` reads a bare comma list @@ -400,6 +548,27 @@ function evalRubyExpr( if (tk.t === 'op' && ')]}'.includes(tk.v)) depth--; } while (depth > 0); }; + // `{k => v, k: v}` (already past `{`). A value it cannot evaluate stays in + // the hash as unresolved, so the other entries can still be read. + const parseHash = () => { + const h = new RubyHash(); + while (!peek('}')) { + if (tokens[pos] == null) return fail('a missing `}`'); + let key; + if (tokens[pos].t === 'id' && tokens[pos + 1]?.t === 'op' && tokens[pos + 1].v === ':') { + key = new RubySymbol(tokens[pos].v); + pos += 2; + } else { + key = parseTernary(); + if (!take('=>')) return fail('a hash entry without `=>`'); + } + const value = parseTernary(); + if (isUnresolved(key) || !h.set(key, value)) return fail('a hash key it cannot evaluate'); + if (!take(',')) break; + } + if (!take('}')) return fail('a missing `}`'); + return h; + }; // Comma-separated expressions up to `close` (already past the opener). const parseItems = (close /*: string */) => { const items = []; @@ -409,26 +578,34 @@ function evalRubyExpr( if (!take(',')) break; } if (!take(close)) return fail(`a missing \`${close}\``); - return items.find(isUnresolved) ?? items; + // A partial string stays an element; anything else unknown fails it. + return items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; }; function parsePrimary() /*: mixed */ { const tk = tokens[pos++]; if (tk == null) return fail('an incomplete expression'); if (tk.t === 'str') { let out = ''; + let why = null; for (const part of tk.parts) { if (typeof part === 'string') { out += part; continue; } const inner = evalRubyExpr(part.expr, env); - if (isUnresolved(inner)) return inner; - const s = rubyToS(inner); - if (isUnresolved(s)) return s; - out += (s /*: any */); + const s = isUnresolved(inner) ? inner : rubyToS(inner); + if (typeof s === 'string') { + out += s; + continue; + } + // Kept as written, or as the partial text of a partial string. + const u /*: RubyUnresolved */ = (s /*: any */); + why ??= u.why; + out += u.partial ?? `#{${part.expr}}`; } - return out; + return why != null ? new RubyUnresolved(why, out) : out; } + if (tk.t === 'sym') return new RubySymbol(tk.v); if (tk.t === 'words') return tk.v; if (tk.t === 'num') return tk.v; if (tk.t === 'bad') return fail(`\`${tk.v}\``); @@ -438,7 +615,7 @@ function evalRubyExpr( return take(')') ? v : fail('a missing `)`'); } if (tk.v === '[') return parseItems(']'); - if (tk.v === '{') return fail('a hash'); + if (tk.v === '{') return parseHash(); return fail(`\`${tk.v}\``); } // An identifier. @@ -464,14 +641,50 @@ function evalRubyExpr( } return fail('`ENV` used other than `ENV[...]` or `ENV.fetch(...)`'); } + // The package.json load podspecs share: `JSON.parse(File.read(File.join( + // __dir__, "package.json")))`, also with `File.dirname(__FILE__)`. + if ((name === 'File' || name === 'JSON') && peek('.')) { + pos++; + const m = tokens[pos++]; + const method = m != null && m.t === 'id' ? m.v : '?'; + const call = `${name}.${method}`; + if (!take('(')) return fail(`the method \`${call}\``); + const args = parseItems(')'); + if (isUnresolved(args)) return args; + const a = (args /*: any */); + if (call === 'File.join' && a.every(x => typeof x === 'string')) { + return path.join(...a); + } + if (call === 'File.dirname' && typeof a[0] === 'string') { + return path.dirname(a[0]); + } + if (call === 'File.read' && a.length === 1) { + return readInside(env.get('__dir__'), a[0]); + } + if (call === 'JSON.parse' && typeof a[0] === 'string') { + try { + return fromJson(JSON.parse(a[0])); + } catch { + return fail('`JSON.parse` of text that is not JSON'); + } + } + return fail(`the method call \`${call}(...)\``); + } if (peek('(')) { skipGroup(); return fail(`the method call \`${name}(...)\``); } - if (!env.has(name)) return fail(`the unknown identifier \`${name}\``); + if (!env.has(name)) { + return fail( + name.startsWith('$') + ? `the global \`${name}\`, which the podspec does not set` + : `the unknown identifier \`${name}\``, + ); + } const v = env.get(name); if (isUnresolved(v)) { - return fail(`\`${name}\`, which ${(v /*: any */).why}`); + const u /*: RubyUnresolved */ = (v /*: any */); + return new RubyUnresolved(`\`${name}\`, which ${u.why}`, u.partial); } return v; } @@ -479,9 +692,13 @@ function evalRubyExpr( let v = parsePrimary(); while (peek('.') || peek('[')) { if (take('[')) { - pos--; - skipGroup(); - v = isUnresolved(v) ? v : fail('an index `[...]`'); + const key = parseTernary(); + if (!take(']')) return fail('a missing `]`'); + if (isUnresolved(v)) continue; + if (isUnresolved(key)) v = key; + else if (v instanceof RubyHash) v = v.get(key); + else if (Array.isArray(v) && typeof key === 'number') v = v[key] ?? null; + else v = fail('an index `[...]` on a value it cannot index'); continue; } take('.'); @@ -503,10 +720,19 @@ function evalRubyExpr( } if (method === 'join' && Array.isArray(v)) { const sep = args.length > 0 ? args[0] : ''; - const parts = v.flat(Infinity).map(rubyToS); - const bad = parts.find(isUnresolved); - v = - bad ?? (typeof sep === 'string' ? parts.join(sep) : fail('`join`')); + const parts = v + .flat(Infinity) + .map(x => (isUnresolved(x) ? x : rubyToS(x))); + const texts = parts.map(rubyText); + const partial = parts.find(isUnresolved); + if (typeof sep !== 'string') v = fail('`join`'); + else if (texts.every(x => x != null)) { + const joined = texts.join(sep); + v = + partial != null + ? new RubyUnresolved((partial /*: any */).why, joined) + : joined; + } else v = partial; continue; } v = fail(`the method call \`.${method}\``); @@ -524,6 +750,13 @@ function evalRubyExpr( let l = parseUnary(); while (take('+')) { const r = parseUnary(); + const lt = rubyText(l); + const rt = rubyText(r); + if (lt != null && rt != null && (isUnresolved(l) || isUnresolved(r))) { + const u /*: RubyUnresolved */ = (isUnresolved(l) ? l : r /*: any */); + l = new RubyUnresolved(u.why, lt + rt); + continue; + } if (isUnresolved(l)) continue; if (isUnresolved(r)) l = r; else if (typeof l === 'string' && typeof r === 'string') l = l + r; @@ -582,7 +815,7 @@ function evalRubyExpr( if (list === true && peek(',')) { const items = [value]; while (take(',')) items.push(parseTernary()); - value = items.find(isUnresolved) ?? items; + value = items.find(x => isUnresolved(x) && rubyText(x) == null) ?? items; } if (pos < tokens.length && !isUnresolved(value)) { const rest = tokens[pos]; @@ -605,15 +838,29 @@ function isPlainLiteral(rhs /*: string */) /*: boolean */ { ).test(rhs.trim()); } -// The literal a field is rewritten to, or null when the value has none. +// The literal a field is rewritten to, or null when the value has none. A +// partial string is written with its `#{...}` as written; a hash entry whose +// value has no literal is left out (the field regexes never read it). function rubyLiteral(v /*: mixed */) /*: ?string */ { - if (typeof v === 'string') return JSON.stringify(v); + const text = rubyText(v); + if (text != null) return JSON.stringify(text); if (typeof v === 'boolean') return String(v); if (Array.isArray(v)) { - const flat = v.flat(Infinity); - if (!flat.every(x => typeof x === 'string')) return null; + const flat = v.flat(Infinity).map(rubyText); + if (!flat.every(x => x != null)) return null; return '[' + flat.map(x => JSON.stringify(x)).join(', ') + ']'; } + if (v instanceof RubyHash) { + const items = []; + for (const {key, value} of v.entries.values()) { + const lit = rubyLiteral(value); + if (lit == null) continue; + const k = + key instanceof RubySymbol ? `:${key.name}` : JSON.stringify(key); + items.push(`${k} => ${lit}`); + } + return `{ ${items.join(', ')} }`; + } return null; } @@ -710,7 +957,11 @@ function modifierIndex(code /*: string */) /*: ?{at: number, kw: string} */ { /*:: type Unresolved = {field: string, expr: string, why: string}; -type Activity = {state: 'yes' | 'no' | 'maybe' | 'opaque', why: string}; +type Activity = { + state: 'yes' | 'no' | 'maybe' | 'opaque', + why: string, + modifier?: boolean, +}; */ // Why a local set under `act` is unknown from there on. @@ -743,12 +994,41 @@ function elsifBranch( */ function evaluateRubyLocals( content /*: string */, -) /*: {text: string, unresolved: Array} */ { + podspecPath /*:: ?: string */, +) /*: {text: string, unresolved: Array, dropped: Array} */ { const lines = content.split('\n'); const out = lines.slice(); const env /*: Map */ = new Map(); + if (podspecPath != null) { + env.set('__dir__', path.dirname(path.resolve(podspecPath))); + env.set('__FILE__', path.resolve(podspecPath)); + } const recvs /*: Set */ = new Set(); const unresolved /*: Array */ = []; + // What was left out of an xcconfig value the scaffolder reads, as warnings. + const dropped /*: Array */ = []; + const noteXcconfig = (lhs /*: string */, text /*: string */) => { + for (const m of text.matchAll(XCCONFIG_READ_KEY_RE)) { + const start = (m.index ?? 0) + m[0].length; + XCCONFIG_ANY_KEY_RE.lastIndex = start; + const next = XCCONFIG_ANY_KEY_RE.exec(text); + const value = text.slice(start, next != null ? next.index : undefined); + const key = m[2] + (m[3] ?? ''); + for (const span of unresolvedInterpolations(value)) { + dropped.push( + `Left out of ${lhs} ${key}: \`${span}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, + ); + } + const bare = value.match(/^\s*([A-Za-z_$]\w*)\s*,?\s*\}?\s*$/); + if (bare != null && rubyText(env.get(bare[1])) == null) { + dropped.push( + `Left out of ${lhs} ${key}: \`${bare[1]}\`, which the podspec reader cannot evaluate; CocoaPods passes its value.`, + ); + } + } + }; + const statementText = (st /*: {start: number, end: number} */) => + out.slice(st.start, st.end + 1).join('\n'); // `if` blocks (which branch is being read) and other blocks. const frames /*: Array */ = []; const blank = (st /*: {start: number, end: number} */) => { @@ -779,10 +1059,9 @@ function evaluateRubyLocals( st /*: {start: number, end: number} */, hash /*: boolean */, ) => { - const known = (id /*: string */) => { - const v = env.get(id); - return typeof v === 'string' ? v : null; - }; + // Spliced into a double-quoted literal, so its own quotes are escaped. + const known = (id /*: string */) => + rubyText(env.get(id))?.replace(/[\\"]/g, '\\$&'); for (let k = st.start; k <= st.end; k++) { out[k] = out[k].replace( /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, @@ -805,12 +1084,38 @@ function evaluateRubyLocals( } } }; + // A local set in a branch of a condition it cannot evaluate keeps its value + // for the rest of that branch (webview sets `folly_compiler_flags` and uses + // it in `compiler_flags` under `defined?(...)`), the next branch sees the + // value from before, and after `end` it is unknown. In any other block it + // does not run, or under a modifier, it is unknown at once. const setLocal = ( name /*: string */, value /*: mixed */, act /*: Activity */, ) => { - env.set(name, act.state === 'yes' ? value : unknownUnder(act)); + if (act.state === 'yes') { + env.set(name, value); + return; + } + const frame = act.modifier + ? null + : [...frames].reverse().find(f => f.kind === 'if' && f.branch === 'maybe'); + if (frame == null) { + env.set(name, unknownUnder(act)); + return; + } + if (!frame.saved.has(name)) { + frame.saved.set(name, env.has(name) ? {value: env.get(name)} : null); + } + env.set(name, value); + }; + // The next branch of `frame` sees the locals as they were before it. + const restoreSaved = (frame /*: any */) => { + for (const [name, saved] of frame.saved) { + if (saved == null) env.delete(name); + else env.set(name, saved.value); + } }; for (const st of rubyStatements(lines)) { @@ -832,14 +1137,17 @@ function evaluateRubyLocals( branch, prior: act.state === 'no' ? 'yes' : branch, cond: m[2], + firstCond: m[2], evaluated: branch !== 'maybe' && branch !== 'opaque', ctrl: [st], + saved: new Map(), }); continue; } if (top?.kind === 'if') { if ((m = code.match(/^elsif\s+([\s\S]+?)(?:\s+then)?$/))) { top.ctrl.push(st); + restoreSaved(top); if (top.branch === 'opaque') continue; const cond = top.prior === 'yes' ? 'no' : condOf(m[1], false); if (cond === 'maybe') top.evaluated = false; @@ -848,6 +1156,7 @@ function evaluateRubyLocals( } if (code === 'else') { top.ctrl.push(st); + restoreSaved(top); if (top.branch !== 'opaque') { top.branch = {yes: 'no', no: 'yes', maybe: 'maybe'}[top.prior]; } @@ -856,6 +1165,9 @@ function evaluateRubyLocals( } if (/^end\b/.test(code) && top != null) { frames.pop(); + for (const name of top.saved?.keys() ?? []) { + env.set(name, unknownUnder({state: 'maybe', why: top.firstCond})); + } // An evaluated condition leaves no control lines behind. if (activity().state === 'no' || (top.kind === 'if' && top.evaluated)) { for (const c of top.kind === 'if' ? top.ctrl : []) blank(c); @@ -903,7 +1215,7 @@ function evaluateRubyLocals( continue; } if (c === 'maybe' && act.state === 'yes') { - stAct = {state: 'maybe', why: cond}; + stAct = {state: 'maybe', why: cond, modifier: true}; } } // `recv.field = expr` on the spec or a subspec. Under a condition it @@ -919,25 +1231,47 @@ function evaluateRubyLocals( (field[2] == null || PLATFORM_SCOPES.has(field[2])) ) { const [, recv, scope, name, rhs] = field; - // Only the spec's own and its `ios` scope count. + // Only the spec's own and its `ios` scope count. The identity fields + // keep fix 3's reading (literals only): evaluating `s.name = + // package['name']` would rename the scaffolded target. if ((scope != null && scope !== 'ios') || isPlainLiteral(rhs)) continue; + if (IDENTITY_FIELDS.has(name)) { + interpolate(st, false); + continue; + } const lhs = `${recv}${scope != null ? '.' + scope : ''}.${name}`; + const refuse = (why /*: string */) => + unresolved.push({field: lhs, expr: rhs.trim(), why}); + // A hash literal stays as written, its `#{local}` and `=> local` filled in. + if (/^\{/.test(rhs.trim())) { + interpolate(st, true); + if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, statementText(st)); + continue; + } const v = evalRubyExpr(rhs, env, true); - const lit = isUnresolved(v) ? null : rubyLiteral(v); + const lit = rubyLiteral(v); + const u = unresolvedIn(v); + if (STRICT_FIELDS.has(name) && (lit == null || u != null)) { + refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); + } else if (WHOLE_FIELDS.has(name)) { + if (lit == null) { + refuse(u != null ? `it uses ${u.why}` : 'its value is not a string or an array of strings'); + } else if (u != null && unresolvedInterpolations(lit).length > 0) { + refuse(`it uses ${u.why}`); + } + } if (lit != null) { blank(st); const indent = (lines[st.start].match(/^\s*/) ?? [''])[0]; out[st.start] = `${indent}${lhs} = ${lit}`; - } else if (STRICT_FIELDS.has(name)) { - unresolved.push({ - field: lhs, - expr: rhs.trim(), - why: isUnresolved(v) - ? `it uses ${(v /*: any */).why}` - : 'its value is not a string or an array of strings', - }); + if (XCCONFIG_FIELDS.has(name)) noteXcconfig(lhs, lit); } else { - interpolate(st, /^\{/.test(rhs.trim())); + interpolate(st, false); + if (XCCONFIG_FIELDS.has(name)) { + dropped.push( + `Left out ${lhs} = ${rhs.trim()}: the podspec reader cannot evaluate it${u != null ? ` (${u.why})` : ''}; CocoaPods passes its value.`, + ); + } } continue; } @@ -959,6 +1293,7 @@ function evaluateRubyLocals( v = new RubyUnresolved( `is assigned \`${rhs.trim()}\`, which the reader cannot evaluate ` + `(${(v /*: any */).why})`, + (v /*: any */).partial, ); } setLocal(name, v, stAct); @@ -994,7 +1329,7 @@ function evaluateRubyLocals( } interpolate(st, false); } - return {text: out.join('\n'), unresolved}; + return {text: out.join('\n'), unresolved, dropped: Array.from(new Set(dropped))}; } // The library's own version. Podspecs load the package.json next to them @@ -1039,7 +1374,7 @@ function resolvePackageVersion( // first non-whitespace character counts. function readPodspecEvaluated( podspecPath /*: string */, -) /*: {text: string, unresolved: Array} */ { +) /*: {text: string, unresolved: Array, dropped: Array} */ { return evaluateRubyLocals( resolvePackageVersion( fs @@ -1049,6 +1384,7 @@ function readPodspecEvaluated( .join('\n'), path.dirname(podspecPath), ), + podspecPath, ); } function readPodspecSource(podspecPath /*: string */) /*: string */ { @@ -1182,11 +1518,15 @@ function regexPodspec( podspecPath /*: string */, opts /*:: ?: {dropSubspecs?: ReadonlyArray} */, ) /*: RawSpec */ { - const {text: content, unresolved} = readPodspecEvaluated(podspecPath); + const { + text: content, + unresolved, + dropped: leftOut, + } = readPodspecEvaluated(podspecPath); const dropped = new Set(opts?.dropSubspecs ?? []); const mainName = mainReceiverName(content); const MAIN_RECV = mainRecvPattern(mainName); - const warnings /*: Array */ = []; + const warnings /*: Array */ = [...leftOut]; // The main spec's own statements, and each subspec block apart. The readers // below default to the main text and receiver; a subspec is read with the // same readers anchored on its block variable, then merged like @@ -2147,10 +2487,11 @@ function unresolvedSourcesReason( .map(u => `\`${u.field} = ${u.expr}\` cannot be evaluated: ${u.why}`) .join('; ') + '. The podspec reader evaluates locals, string interpolation, arrays, ' + - "ENV['...'], comparisons, ternaries and if/unless blocks; building from " + - 'the globs it could read would leave some of the library\'s files out of ' + - 'its target. Install CocoaPods (`gem install cocoapods`) so `pod ipc spec` ' + - 'reads the podspec, or give the library a Package.swift of its own.' + "ENV['...'], package.json reads, comparisons, ternaries and if/unless " + + 'blocks; building from the part it could read would leave some of the ' + + "library's files or settings out of its target. Install CocoaPods (`gem " + + 'install cocoapods`) so `pod ipc spec` reads the podspec, or give the ' + + 'library a Package.swift of its own.' ); } From 85ac9aae03837bef420ce4bfd4999e33924ec913 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Fri, 6 Nov 2026 07:09:32 -0600 Subject: [PATCH 15/16] docs: describe package.json reads and left-out flags --- CHANGELOG.md | 7 +++-- docs/how-it-works.md | 11 +++++--- docs/troubleshooting.md | 11 ++++++-- docs/upstream/react-native-scaffolder.md | 33 ++++++++++++++++++++---- 4 files changed, 49 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b44442..cf0bc6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,8 +43,11 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea scaffold at every build: the patch holds the files the scaffold wrote and those its existing patch held. - react-native-screens 4.24.0 scaffolds with its `ios/` sources, instead of a target with only its C++ and an app that crashed at start: the podspec reader evaluates Ruby locals, interpolation, `ENV` lookups, ternaries, `if`/`unless` - blocks and `push` on a local array, and leaves out the branches a condition rules out; a source glob it cannot - evaluate stops that library's scaffold with the podspec, the field and the expression. + blocks, `push` on a local array, hashes and the library's `package.json`, and leaves out the branches a condition + rules out; a source glob, `compiler_flags`, `header_dir` or `frameworks` value it cannot evaluate stops that + library's scaffold with the podspec, the field and the expression, and an xcconfig flag it cannot evaluate is left + out with a warning that names it. react-native-worklets 0.8.3 keeps its `WORKLETS_VERSION` and + `REACT_NATIVE_MINOR_VERSION` defines. - `build` and `install` stop, and remove the packed app, when a class React Native's codegen providers name is not in the app, naming the class, its component or module and its library, instead of installing an app that would crash at start in `+[RCTThirdPartyComponentsProvider thirdPartyFabricComponents]`. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 8f37b34..6d4b668 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -360,10 +360,13 @@ patch above is what makes that scaffolder work for real-world podspecs. `||`, ternaries, `+` on strings and arrays, `join`, `if`/`elsif`/`else`/`unless` blocks and `if`/`unless` modifiers, and `push`, `<<` and `concat` on a local array. A branch its condition rules out is left out, as CocoaPods leaves it out; both branches of a condition it cannot evaluate (a method call such as - `respond_to?(:install_modules_dependencies, true)`) are read. A `source_files` or `exclude_files` value that uses - anything else (a method call, a local it could not evaluate) fails that library's scaffold, with a reason that - names the podspec, the field and the expression, since a target built from the globs it could read would lack some - of the library's files + `respond_to?(:install_modules_dependencies, true)`) are read. It also reads the library's own `package.json` + (`JSON.parse(File.read(File.join(__dir__, "package.json")))`) and hashes. A `source_files`, `exclude_files`, + `compiler_flags`, `header_dir`, `header_mappings_dir`, `frameworks` or `libraries` value that uses anything else (a + method call, a local it could not evaluate) fails that library's scaffold, with a reason that names the podspec, + the field and the expression, since a target built from the part it could read would lack some of the library's + files or settings; an xcconfig value it cannot evaluate in part is left out with a `Left out of …` warning that + names it ([fix 28](upstream/react-native-scaffolder.md#28-scriptsspmread-podspecjs-source-globs-built-from-ruby-locals-and-conditions-are-read-in-part)). - After `xtool-build`, `build` checks that every class React Native's codegen providers name (`ios/build/generated/ios/ReactCodegen/RCTThirdPartyComponentsProvider.mm` and `RCTModuleProviders.mm`) is defined diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 91fc8a5..8245e06 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -1064,8 +1064,15 @@ module is unavailable.` failed: : `s.source_files = ` cannot be evaluated: it uses . …``. The reader evaluates locals, string interpolation, arrays, `ENV['…']`, comparisons, ternaries and `if`/`unless` blocks ([how it works](how-it-works.md#cocoapods-only-libraries)); a method call or a value it does not know in a source - glob is refused. Installing CocoaPods (`gem install cocoapods`) lets `pod ipc spec` read the podspec instead, or give - the library a `Package.swift` of its own. + glob, `compiler_flags`, `header_dir`, `header_mappings_dir`, `frameworks` or `libraries` is refused. Installing + CocoaPods (`gem install cocoapods`) lets `pod ipc spec` read the podspec instead, or give the library a + `Package.swift` of its own. +- **"! : Left out of s.pod_target_xcconfig OTHER_CFLAGS: `#{feature_flags}`, which the podspec reader cannot + evaluate; CocoaPods passes its value."** (also `GCC_PREPROCESSOR_DEFINITIONS`, `HEADER_SEARCH_PATHS`, + `SWIFT_ACTIVE_COMPILATION_CONDITIONS`): the scaffold left that part of the value out. CocoaPods computes it from the + app or the Podfile: react-native-worklets' and react-native-reanimated's static feature flags (their defaults + apply), react-native-vision-camera's frame processor and location switches (both off). To set such a value, edit + the library's `Package.swift` and persist it in `patches/`. - **A hand-edited `Package.swift`** that leaves out the files defining a class: put them back. - **"ℹ The packed app's binaries list no Objective-C class symbols, so rn-xtool could not check the classes React Native's codegen providers name.":** the binaries have no symbol table, so nothing is checked and the build goes on. diff --git a/docs/upstream/react-native-scaffolder.md b/docs/upstream/react-native-scaffolder.md index 3c3f9c7..081d8bc 100644 --- a/docs/upstream/react-native-scaffolder.md +++ b/docs/upstream/react-native-scaffolder.md @@ -834,11 +834,32 @@ hashes, symbols, `$config[...]`, blocks other than the spec's) is not evaluated: assigned from it or under a condition on it is unknown from there on, and both branches of such a condition stay visible, as before (react-native-vision-camera's `if enableFrameProcessors` subspec, fix 20). -A `source_files` or `exclude_files` value that uses something unknown no longer degrades silently: the model carries it -in `unresolvedSources`, and `scaffoldPackageSwiftForDep` returns `status: 'error'` with a reason naming the podspec, +The evaluator also models what fix 3 and fix 15 read: `JSON.parse(File.read(File.join(__dir__, "package.json")))` +(also with `File.dirname(__FILE__)`) is the library's own package.json as a hash, indexed with `pkg['key']`, and +`File.read` reads only inside the podspec's directory. Hashes (`{ 'K' => v }`, `{ k: v }`) and symbols are values, so a +local hash such as screens' `rnscreens_config` reaches `pod_target_xcconfig`. A double-quoted string with an +interpolation it cannot compute keeps that `#{...}` as written (fix 3's behaviour), so +`version_flags = "-DWORKLETS_VERSION=#{package['version']} -DREACT_NATIVE_MINOR_VERSION=#{$worklets_config[...]}"` +still gives worklets 0.8.3 `WORKLETS_VERSION=0.8.3`, and fix 8 the installed React Native's minor. A local set in a +branch of a condition it cannot evaluate keeps its value for the rest of that branch (react-native-webview sets +`folly_compiler_flags` and uses it in `compiler_flags` under `defined?(install_modules_dependencies())`); after `end` +it is unknown. `name`, `module_name` and `version` are read as literals only, as before: evaluating `s.name = +package['name']` would rename react-native-app-auth's and react-native-webview's targets. + +A value that uses something unknown no longer degrades silently. In `source_files`, `exclude_files`, +`compiler_flags`, `header_dir`, `header_mappings_dir`, `frameworks` and `libraries` the model carries it in +`unresolvedSources`, and `scaffoldPackageSwiftForDep` returns `status: 'error'` with a reason naming the podspec, the field and the expression, for example ``: `s.source_files = sources_for("ios")` cannot be evaluated: it uses the method call `sources_for(...)`.`` Name resolution and header search paths keep -reading the model as before. +reading the model as before. In the xcconfig values the scaffolder reads (`OTHER_CFLAGS`, +`GCC_PREPROCESSOR_DEFINITIONS`, `HEADER_SEARCH_PATHS`, `SWIFT_ACTIVE_COMPILATION_CONDITIONS` of `pod_target_xcconfig`, +`user_target_xcconfig` and `xcconfig`) each `#{...}` it cannot evaluate is left out with a warning that names it, +``Left out of s.pod_target_xcconfig OTHER_CFLAGS: `#{feature_flags}`, which the podspec reader cannot evaluate; +CocoaPods passes its value.``, except `REACT_NATIVE_{MAJOR,MINOR,PATCH}_VERSION=#{...}` (fix 8) and a token with an +Xcode `$(...)`, which the scaffolder drops anyway. They are not refused: podspecs put optional, +configuration-driven flags there that only CocoaPods computes from the app and its Podfile, and the libraries checked +(react-native-worklets 0.8.3 and 0.10.1, react-native-reanimated 4.3.4 and 4.5.1, react-native-vision-camera 4.7.3, +react-native-gesture-handler 3.3.0) built and ran with those values left out. Effect on the libraries checked: screens 4.24.0 scaffolds 195 sources (147 under `ios/`), gamma excluded, as one clang-only target (every Swift file is under `ios/gamma`), with `ios/bridging/Swift-Bridging.h` left out of its module @@ -846,8 +867,10 @@ map (fix 18, it imports the module's own `-Swift.h`). react-native-svg 15.16.0 n `apple/Utils/RNSVGFabricConversions.h` (excluded only in its old-architecture `else` branch), so the header is in its sources and its module map is no longer written. The other libraries of the reference app, of the bare 0.86 and 0.87 apps and of the Expo SDK 57 and 58 apps read the same sources as before; their dependencies and `exclude_files` lose -what only a dead `else` branch declared (`React-Core`, `React-jsc`, datetimepicker's `ios/fabric`). The scaffold -revision moves to 6. +what only a dead `else` branch declared (`React-Core`, `React-jsc`, datetimepicker's `ios/fabric`). Libraries that +set `compiler_flags` from `folly_compiler_flags` (react-native-webview, @react-native-async-storage/async-storage 1.x, +react-native-keychain, react-native-video, @aws-amplify/react-native) now get its `-Wno-comma -Wno-shorten-64-to-32`; +its `FOLLY_*` defines stay dropped, as for every library. The scaffold revision moves to 6. ## Known limitation (deferred): pure-Swift packages importing a mixed Expo module From a4a135168a340ef905d40f41d2c04fc209fd7980 Mon Sep 17 00:00:00 2001 From: Willy Antunez Date: Fri, 6 Nov 2026 07:11:02 -0600 Subject: [PATCH 16/16] chore: bump the scaffold revision to 7 --- CHANGELOG.md | 4 +- docs/troubleshooting.md | 18 +++-- docs/upstream/react-native-scaffolder.md | 3 +- patches/react-native+0.88.0.patch | 74 ++++++++++--------- patches/react-native+0.88.1.patch | 74 ++++++++++--------- src/pipeline/patches.ts | 2 +- tests/capabilities.test.ts | 2 +- .../datetimepicker/Package.swift | 2 +- .../Package.swift | 2 +- .../react-native-pager-view/Package.swift | 2 +- .../Package@swift-6.5.swift | 2 +- .../react-native-screens/Package.swift | 2 +- .../react-native-svg/Package.swift | 2 +- .../react-native-webview/Package.swift | 2 +- tests/patches.test.ts | 54 +++++++------- tests/rn-scaffolder.test.ts | 18 ++--- vendor/rn-spm/spm/scaffold-package-swift.js | 6 +- 17 files changed, 141 insertions(+), 128 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf0bc6d..15b8309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,8 @@ versions follow [Semantic Versioning](https://semver.org/) with `alpha` prerelea ## [Unreleased] ### Upgrading from 0.1.0-alpha.6 -- The scaffolder is now revision 6, so every scaffold patch rn-xtool persisted in your `patches/` before this release - gets a warning at each `build`: "⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 6); +- The scaffolder is now revision 7, so every scaffold patch rn-xtool persisted in your `patches/` before this release + gets a warning at each `build`: "⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, now 7); delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old Package.swift)". Do what it says. A scaffolded library without a persisted patch is scaffolded again by itself. - A `pods..forwardHeaders` entry in `rn-xtool.config.json` that lists modules is refused: list the pod's public diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8245e06..e8d0784 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -830,14 +830,16 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin `npm install`, and the next build applies the patch again. A nested package's patch (`+++.patch`) is named ` => `. A package installed at another version than its patch's is not skipped: patch-package applies the patch with its own version warning. -- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 6); delete it so rn-xtool +- **"⚠ patches/ was written by an older rn-xtool scaffolder (revision , now 7); delete it so rn-xtool regenerates it (also remove node_modules/ and reinstall: that copy still has the old Package.swift)":** the `patches` step found a persisted scaffold patch from an older scaffolder. Revision 1 patches lack the Swift importer paths of mixed libraries, revision 2 patches lack those of clang-only libraries and their module map, revision 3 patches lack fixes 20–22 and 24 (fixes 17 to 24 in [the scaffolder fixes](upstream/react-native-scaffolder.md)), revision 4 patches hold pod header forwarders that `@import` modules (fix 13), and revision 5 patches may lack the sources of a podspec that builds its globs from Ruby locals and conditions (fix 28: react-native-screens 4.24.0 got no - `ios/` sources). Without those fixes, Swift code that + `ios/` sources), and revision 6 patches may lack defines a podspec builds from its package.json (react-native-worklets + 0.8.3's `WORKLETS_VERSION`, whose `WorkletsVersion.cpp` then stops with `use of undeclared identifier + 'WORKLETS_VERSION_STRING'`). Without those fixes, Swift code that imports a scaffolded library (the app, or expo-router importing react-native-screens) can fail with `'RNSReactBaseView.h' file not found` (a mixed library, such as react-native-screens 4.26) or `'RNSDefines.h' file not found` (a clang-only one, such as react-native-screens 4.30), and an Objective-C++ file that imports @@ -845,9 +847,9 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin 4.24.0 stops at `build` with [the codegen classes check](#rctthirdpartycomponentsprovider-thirdpartyfabriccomponents). Do what the warning says: delete the patch, remove the library from `node_modules` and reinstall it, then build; rn-xtool scaffolds it again and persists - the new patch. This release's scaffolder is revision 6, so each scaffold patch persisted before it gets the line at + the new patch. This release's scaffolder is revision 7, so each scaffold patch persisted before it gets the line at every build until it is regenerated, for example `⚠ patches/react-native-screens+4.30.0.patch was written by an - older rn-xtool scaffolder (revision 4, now 6); delete it so rn-xtool regenerates it (also remove + older rn-xtool scaffolder (revision 4, now 7); delete it so rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)`. Until then the build goes on with the older manifest. - **"⚠ patches/ was scaffolded for React Native ; delete it so rn-xtool regenerates it for @@ -856,21 +858,21 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin Do the same as for the revision warning above. Both warnings also read patches with the marker's name before the rename, `expo-xtool-scaffold-revision` (apps scaffolded before 0.1.0-alpha.1). - **"ℹ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 6, React Native ): rn-xtool replaced it with the persisted one":** a teammate + patches/ (revision 7, React Native ): rn-xtool replaced it with the persisted one":** a teammate committed a regenerated scaffold patch, and your `node_modules` still had the copy an older patch wrote (patch-package does not replace a file that exists). rn-xtool owns these generated files, so the `patches` step removes the files the current patch creates and patch-package writes them again; the line is printed once patch-package has done so. Nothing to do; files the older scaffold wrote and the current one does not stay in place. This happens only when the patch holds nothing but scaffolded new files. - **"⚠ node_modules//Package.swift was scaffolded with revision for React Native , older than - patches/ (revision 6, React Native ), and that patch also changes the library's own files, so + patches/ (revision 7, React Native ), and that patch also changes the library's own files, so rn-xtool does not replace it: run rm -rf node_modules/ && npm install, then build again":** the same case, but the persisted patch also holds your own fix to the library. rn-xtool persists a scaffold with `patch-package `, which writes everything that differs from the published package into one patch. Removing only the scaffold files would leave a patch that patch-package can apply neither forward nor backward, so rn-xtool changes nothing and the build goes on with the older manifest. Run the command: the reinstall gives the published package, and the next build applies the whole patch. -- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 6)" (or +- **"ℹ node_modules//Package.swift was scaffolded by an older rn-xtool scaffolder (revision , now 7)" (or "was scaffolded for React Native , not "), followed by "rn-xtool removed it so the rn-spm step scaffolds it again":** a library has no persisted patch, and the manifest rn-xtool generated for it is out of date, for example after you deleted a stale patch but kept the package installed. The `rn-spm` step scaffolds it again @@ -921,7 +923,7 @@ an `ios/build/pod-binaries` from an earlier build stays on disk, unused ([Leavin `#import` per public header of the pod, which compiles in `.m` and `.mm` files alike, and their scaffolder revision (5 and later) replaces an older scaffold: a copy in `node_modules` without a persisted patch is scaffolded again by itself, and a persisted patch gets the `⚠ patches/ was written by an older rn-xtool scaffolder (revision 4, - now 6)` line + now 7)` line above, whose steps regenerate it. A `forwardHeaders` entry of your config that still lists modules is refused with `… lists the module ; list the pod's public headers instead`: list the headers, as in [Libraries that depend on CocoaPods pods](#libraries-that-depend-on-cocoapods-pods). diff --git a/docs/upstream/react-native-scaffolder.md b/docs/upstream/react-native-scaffolder.md index 081d8bc..1867244 100644 --- a/docs/upstream/react-native-scaffolder.md +++ b/docs/upstream/react-native-scaffolder.md @@ -870,7 +870,8 @@ apps and of the Expo SDK 57 and 58 apps read the same sources as before; their d what only a dead `else` branch declared (`React-Core`, `React-jsc`, datetimepicker's `ios/fabric`). Libraries that set `compiler_flags` from `folly_compiler_flags` (react-native-webview, @react-native-async-storage/async-storage 1.x, react-native-keychain, react-native-video, @aws-amplify/react-native) now get its `-Wno-comma -Wno-shorten-64-to-32`; -its `FOLLY_*` defines stay dropped, as for every library. The scaffold revision moves to 6. +its `FOLLY_*` defines stay dropped, as for every library. The scaffold revision moves to 6, then to 7 for the +package.json defines revision 6 lost. ## Known limitation (deferred): pure-Swift packages importing a mixed Expo module diff --git a/patches/react-native+0.88.0.patch b/patches/react-native+0.88.0.patch index ac862f2..6062e3f 100644 --- a/patches/react-native+0.88.0.patch +++ b/patches/react-native+0.88.0.patch @@ -2301,7 +2301,7 @@ index 8fcf04b..6897fdb 100644 + unresolvedSourcesReason, }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..c19356d 100644 +index cf7e587..f105e49 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -45,7 +45,11 @@ const { @@ -2325,7 +2325,7 @@ index cf7e587..c19356d 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +118,279 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,281 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -2344,8 +2344,10 @@ index cf7e587..c19356d 100644 +// its modules, which stopped every Objective-C++ file that included them. +// Revision 6 (fix 28): source globs built from Ruby locals and conditions +// (react-native-screens 4.24.0 had no ios/ sources), and the branches a -+// condition rules out left out of the target. -+const RN_XTOOL_SCAFFOLD_REVISION = 6; ++// condition rules out left out of the target. Revision 7: the defines a ++// podspec builds from its package.json and partly evaluated strings ++// (react-native-worklets 0.8.3's WORKLETS_VERSION), which revision 6 lost. ++const RN_XTOOL_SCAFFOLD_REVISION = 7; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -2605,7 +2607,7 @@ index cf7e587..c19356d 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +423,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +425,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -2979,7 +2981,7 @@ index cf7e587..c19356d 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +812,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +814,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -3008,7 +3010,7 @@ index cf7e587..c19356d 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +910,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +912,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -3021,7 +3023,7 @@ index cf7e587..c19356d 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +990,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +992,92 @@ function translatePodspecToSpmTarget( } } @@ -3142,7 +3144,7 @@ index cf7e587..c19356d 100644 } } -@@ -427,15 +1141,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1143,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -3200,7 +3202,7 @@ index cf7e587..c19356d 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1251,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1253,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -3252,7 +3254,7 @@ index cf7e587..c19356d 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1317,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1319,101 @@ function translatePodspecToSpmTarget( ); } @@ -3354,7 +3356,7 @@ index cf7e587..c19356d 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1420,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1422,201 @@ function translatePodspecToSpmTarget( } } @@ -3558,7 +3560,7 @@ index cf7e587..c19356d 100644 warnings, }; } -@@ -565,6 +1639,9 @@ type EmitContext = { +@@ -565,6 +1641,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -3568,7 +3570,7 @@ index cf7e587..c19356d 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1706,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1708,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -3595,7 +3597,7 @@ index cf7e587..c19356d 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1815,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1817,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -3628,7 +3630,7 @@ index cf7e587..c19356d 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1858,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1860,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -3640,7 +3642,7 @@ index cf7e587..c19356d 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1878,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1880,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -3714,7 +3716,7 @@ index cf7e587..c19356d 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1953,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1955,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -3723,7 +3725,7 @@ index cf7e587..c19356d 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1963,13 @@ let package = Package( +@@ -778,13 +1965,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -3740,7 +3742,7 @@ index cf7e587..c19356d 100644 ) `; } -@@ -844,6 +2029,61 @@ function reportSwiftName( +@@ -844,6 +2031,61 @@ function reportSwiftName( } } @@ -3802,7 +3804,7 @@ index cf7e587..c19356d 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2193,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2195,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -3815,7 +3817,7 @@ index cf7e587..c19356d 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2214,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2216,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -3824,7 +3826,7 @@ index cf7e587..c19356d 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2242,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2244,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -3869,7 +3871,7 @@ index cf7e587..c19356d 100644 } catch (e) { return { depName, -@@ -1008,39 +2287,27 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2289,27 @@ function scaffoldPackageSwiftForDep( reason: `Podspec read failed: ${e.message}`, }; } @@ -3924,7 +3926,7 @@ index cf7e587..c19356d 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2339,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2341,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -3932,7 +3934,7 @@ index cf7e587..c19356d 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2349,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2351,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -3972,7 +3974,7 @@ index cf7e587..c19356d 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2388,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2390,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -4073,7 +4075,7 @@ index cf7e587..c19356d 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2487,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2489,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -4086,7 +4088,7 @@ index cf7e587..c19356d 100644 return { depName, -@@ -1128,6 +2501,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2503,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -4094,7 +4096,7 @@ index cf7e587..c19356d 100644 }; } -@@ -1141,7 +2515,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2517,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -4103,7 +4105,7 @@ index cf7e587..c19356d 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2536,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2538,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -4112,7 +4114,7 @@ index cf7e587..c19356d 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2668,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2670,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -4124,7 +4126,7 @@ index cf7e587..c19356d 100644 }; */ -@@ -1323,6 +2702,17 @@ function scaffoldAll( +@@ -1323,6 +2704,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -4142,7 +4144,7 @@ index cf7e587..c19356d 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2720,23 @@ function scaffoldAll( +@@ -1330,24 +2722,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -4178,7 +4180,7 @@ index cf7e587..c19356d 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2775,9 @@ function scaffoldAll( +@@ -1386,6 +2777,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -4188,7 +4190,7 @@ index cf7e587..c19356d 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2796,9 @@ function scaffoldAll( +@@ -1404,6 +2798,9 @@ function scaffoldAll( } module.exports = { diff --git a/patches/react-native+0.88.1.patch b/patches/react-native+0.88.1.patch index ac862f2..6062e3f 100644 --- a/patches/react-native+0.88.1.patch +++ b/patches/react-native+0.88.1.patch @@ -2301,7 +2301,7 @@ index 8fcf04b..6897fdb 100644 + unresolvedSourcesReason, }; diff --git a/node_modules/react-native/scripts/spm/scaffold-package-swift.js b/node_modules/react-native/scripts/spm/scaffold-package-swift.js -index cf7e587..c19356d 100644 +index cf7e587..f105e49 100644 --- a/node_modules/react-native/scripts/spm/scaffold-package-swift.js +++ b/node_modules/react-native/scripts/spm/scaffold-package-swift.js @@ -45,7 +45,11 @@ const { @@ -2325,7 +2325,7 @@ index cf7e587..c19356d 100644 } = require('./spm-utils'); const {readSwiftpmConfig, writeSwiftpmName} = require('./swiftpm-config'); const fs = require('node:fs'); -@@ -113,6 +118,279 @@ const {log, warn} = makeLogger('scaffold-package-swift'); +@@ -113,6 +118,281 @@ const {log, warn} = makeLogger('scaffold-package-swift'); const SCAFFOLDER_VERSION = 20; const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; @@ -2344,8 +2344,10 @@ index cf7e587..c19356d 100644 +// its modules, which stopped every Objective-C++ file that included them. +// Revision 6 (fix 28): source globs built from Ruby locals and conditions +// (react-native-screens 4.24.0 had no ios/ sources), and the branches a -+// condition rules out left out of the target. -+const RN_XTOOL_SCAFFOLD_REVISION = 6; ++// condition rules out left out of the target. Revision 7: the defines a ++// podspec builds from its package.json and partly evaluated strings ++// (react-native-worklets 0.8.3's WORKLETS_VERSION), which revision 6 lost. ++const RN_XTOOL_SCAFFOLD_REVISION = 7; +const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; + +// An importer (Swift, or a Clang module) builds the target's module from its @@ -2605,7 +2607,7 @@ index cf7e587..c19356d 100644 const AUTOGEN_MARKER = '// AUTO-GENERATED by scripts/generate-spm-autolinking.js'; -@@ -145,6 +423,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm +@@ -145,6 +425,373 @@ const SCAFFOLD_PREFIX_HEADER_CONTENTS = `// AUTO-SCAFFOLDED by react-native spm #endif `; @@ -2979,7 +2981,7 @@ index cf7e587..c19356d 100644 // Names of deps the scaffolder always refuses to touch — `react-native` // itself is handled by the xcframework subpackage, never as an autolinked // target. -@@ -167,10 +812,27 @@ const REACT_CORE_DEP_PREFIXES = [ +@@ -167,10 +814,27 @@ const REACT_CORE_DEP_PREFIXES = [ 'DoubleConversion', 'Yoga', 'hermes-engine', @@ -3008,7 +3010,7 @@ index cf7e587..c19356d 100644 } // True when the dep ships a `codegenConfig` in package.json — RN's standard -@@ -248,6 +910,12 @@ function translatePodspecToSpmTarget( +@@ -248,6 +912,12 @@ function translatePodspecToSpmTarget( // npm name → resolved Swift name for every autolinked dep, so a sibling // reference honors that sibling's `spm.name` instead of re-deriving it. swiftNameByNpm /*: Map */ = new Map(), @@ -3021,7 +3023,7 @@ index cf7e587..c19356d 100644 ) /*: SpmScaffoldSpec */ { const warnings = [...model.warnings]; -@@ -322,46 +990,92 @@ function translatePodspecToSpmTarget( +@@ -322,46 +992,92 @@ function translatePodspecToSpmTarget( } } @@ -3142,7 +3144,7 @@ index cf7e587..c19356d 100644 } } -@@ -427,15 +1141,55 @@ function translatePodspecToSpmTarget( +@@ -427,15 +1143,55 @@ function translatePodspecToSpmTarget( f => f !== SCAFFOLD_PREFIX_HEADER && f !== 'Package.swift' && @@ -3200,7 +3202,7 @@ index cf7e587..c19356d 100644 try { for (const f of expandSpmSourceGlobs(dep.root, model.publicHeaderFiles)) { if (/\.(h|hh|hpp)$/i.test(f)) headerFiles.push(f); -@@ -497,6 +1251,51 @@ function translatePodspecToSpmTarget( +@@ -497,6 +1253,51 @@ function translatePodspecToSpmTarget( } } let namespacedShimHeaders /*: Array */ = []; @@ -3252,7 +3254,7 @@ index cf7e587..c19356d 100644 if (publicHeadersPath == null) { // Root-level podspecs (`s.source_files = "*.{h,m,mm}"`) keep their // headers in the package root. CocoaPods exposes them to dependents as -@@ -518,6 +1317,101 @@ function translatePodspecToSpmTarget( +@@ -518,6 +1319,101 @@ function translatePodspecToSpmTarget( ); } @@ -3354,7 +3356,7 @@ index cf7e587..c19356d 100644 const siblingSwiftNames /*: {[npmName: string]: string} */ = {}; for (const npmName of siblingNames) { const resolved = swiftNameByNpm.get(npmName); -@@ -526,21 +1420,201 @@ function translatePodspecToSpmTarget( +@@ -526,21 +1422,201 @@ function translatePodspecToSpmTarget( } } @@ -3558,7 +3560,7 @@ index cf7e587..c19356d 100644 warnings, }; } -@@ -565,6 +1639,9 @@ type EmitContext = { +@@ -565,6 +1641,9 @@ type EmitContext = { // Relative path to the app's local xcframeworks package // (/build/xcframeworks). Only referenced when remote == null. localXcfwPackageDir?: ?string, @@ -3568,7 +3570,7 @@ index cf7e587..c19356d 100644 iosDeploymentTarget?: ?string, }; */ -@@ -629,10 +1706,25 @@ function emitScaffoldedPackageSwift( +@@ -629,10 +1708,25 @@ function emitScaffoldedPackageSwift( const prefixFlag = spec.needsObjCPrefix ? `.unsafeFlags(["-include", "${SCAFFOLD_PREFIX_HEADER}"])` : ''; @@ -3595,7 +3597,7 @@ index cf7e587..c19356d 100644 ...(customFlagsCxx.length > 0 ? [`.unsafeFlags([${customFlagsCxx.join(', ')}])`] : []), -@@ -723,6 +1815,32 @@ function emitScaffoldedPackageSwift( +@@ -723,6 +1817,32 @@ function emitScaffoldedPackageSwift( `.product(name: "${swiftSibling}", package: "${swiftSibling}")`, ); } @@ -3628,7 +3630,7 @@ index cf7e587..c19356d 100644 // sources: emit only when the podspec declared them. If empty (regex-fallback // podspec), no `sources:`/`exclude:` is emitted and SPM auto-scans the target -@@ -740,6 +1858,11 @@ function emitScaffoldedPackageSwift( +@@ -740,6 +1860,11 @@ function emitScaffoldedPackageSwift( ? `\n publicHeadersPath: "${spec.publicHeadersPath}",` : ''; @@ -3640,7 +3642,7 @@ index cf7e587..c19356d 100644 const resourcesLine = spec.resources.length > 0 ? `\n resources: [${spec.resources.map(r => `.copy("${r}")`).join(', ')}],` -@@ -755,9 +1878,71 @@ function emitScaffoldedPackageSwift( +@@ -755,9 +1880,71 @@ function emitScaffoldedPackageSwift( ? `\n dependencies: [${targetDeps.join(', ')}],` : ''; @@ -3714,7 +3716,7 @@ index cf7e587..c19356d 100644 // Edit the contents below if needed and re-run \`npx patch-package \` // to persist across \`npm install\`. To regenerate from the podspec, remove // this file (or just this marker) and re-run \`npx react-native spm scaffold\`. -@@ -768,7 +1953,7 @@ ${SCAFFOLDER_MARKER} +@@ -768,7 +1955,7 @@ ${SCAFFOLDER_MARKER} // (dropping the file) anyway. import PackageDescription @@ -3723,7 +3725,7 @@ index cf7e587..c19356d 100644 let package = Package( name: "${spec.swiftName}", platforms: [.iOS("${iosDeploymentTarget}")], -@@ -778,13 +1963,13 @@ let package = Package( +@@ -778,13 +1965,13 @@ let package = Package( ${packageDepsBlock} targets: [ .target( name: "${spec.swiftName}",${targetDepsLine} @@ -3740,7 +3742,7 @@ index cf7e587..c19356d 100644 ) `; } -@@ -844,6 +2029,61 @@ function reportSwiftName( +@@ -844,6 +2031,61 @@ function reportSwiftName( } } @@ -3802,7 +3804,7 @@ index cf7e587..c19356d 100644 // --------------------------------------------------------------------------- // Per-dep orchestrator // --------------------------------------------------------------------------- -@@ -953,7 +2193,11 @@ function scaffoldPackageSwiftForDep( +@@ -953,7 +2195,11 @@ function scaffoldPackageSwiftForDep( // regenerating existing files; --force is not needed here. const vMatch = existing.match(SCAFFOLDER_VERSION_LINE_RE); const existingVersion = vMatch != null ? parseInt(vMatch[1], 10) : 1; @@ -3815,7 +3817,7 @@ index cf7e587..c19356d 100644 if (!ctx.force && !versionStale) { // Slot label change is the other auto-regen trigger — bumps SPM's // manifest hash so the cache-slot path gets re-resolved. -@@ -970,7 +2214,7 @@ function scaffoldPackageSwiftForDep( +@@ -970,7 +2216,7 @@ function scaffoldPackageSwiftForDep( } if (versionStale) { log( @@ -3824,7 +3826,7 @@ index cf7e587..c19356d 100644 ); } // Fall through: regenerate (force, slot changed, or version bumped). -@@ -998,9 +2242,44 @@ function scaffoldPackageSwiftForDep( +@@ -998,9 +2244,44 @@ function scaffoldPackageSwiftForDep( }; } @@ -3869,7 +3871,7 @@ index cf7e587..c19356d 100644 } catch (e) { return { depName, -@@ -1008,39 +2287,27 @@ function scaffoldPackageSwiftForDep( +@@ -1008,39 +2289,27 @@ function scaffoldPackageSwiftForDep( reason: `Podspec read failed: ${e.message}`, }; } @@ -3924,7 +3926,7 @@ index cf7e587..c19356d 100644 // Relative paths into the app, embedded in the scaffolded Package.swift. // -@@ -1072,6 +2339,7 @@ function scaffoldPackageSwiftForDep( +@@ -1072,6 +2341,7 @@ function scaffoldPackageSwiftForDep( iosDeploymentTarget: ctx.iosDeploymentTarget, codegenPackageDir: relFromManifest('build', 'generated', 'ios'), localXcfwPackageDir: relFromManifest('build', 'xcframeworks'), @@ -3932,7 +3934,7 @@ index cf7e587..c19356d 100644 }); // Distinguish "first-time scaffold" (no file at all) from "regenerate" -@@ -1081,15 +2349,36 @@ function scaffoldPackageSwiftForDep( +@@ -1081,15 +2351,36 @@ function scaffoldPackageSwiftForDep( // regens are silent because we're maintaining a file we already own. const previouslyExisted = fs.existsSync(pkgSwiftPath); @@ -3972,7 +3974,7 @@ index cf7e587..c19356d 100644 ); } // Mirror root-level headers into the generated include// shim -@@ -1099,18 +2388,96 @@ function scaffoldPackageSwiftForDep( +@@ -1099,18 +2390,96 @@ function scaffoldPackageSwiftForDep( const shimDir = path.join(dep.root, 'include', spec.swiftName); fs.mkdirSync(shimDir, {recursive: true}); for (const header of spec.namespacedShimHeaders) { @@ -4073,7 +4075,7 @@ index cf7e587..c19356d 100644 reportSwiftName(dep, spec.swiftName, model); // Migration: record a name we derived from the podspec, so the library can -@@ -1120,6 +2487,12 @@ function scaffoldPackageSwiftForDep( +@@ -1120,6 +2489,12 @@ function scaffoldPackageSwiftForDep( dep.swiftNameSource === 'podspec' ? writeSwiftpmName(dep.root, spec.swiftName, {dryRun: ctx.dryRun}) : undefined; @@ -4086,7 +4088,7 @@ index cf7e587..c19356d 100644 return { depName, -@@ -1128,6 +2501,7 @@ function scaffoldPackageSwiftForDep( +@@ -1128,6 +2503,7 @@ function scaffoldPackageSwiftForDep( warnings: spec.warnings, previouslyExisted, swiftpmName, @@ -4094,7 +4096,7 @@ index cf7e587..c19356d 100644 }; } -@@ -1141,7 +2515,7 @@ function collectAutolinkedDeps( +@@ -1141,7 +2517,7 @@ function collectAutolinkedDeps( opts /*: { autolinkingJsonPath: string, remote: ?{url: string, version: string, identity: string}, @@ -4103,7 +4105,7 @@ index cf7e587..c19356d 100644 } */, ) /*: ?Array */ { const {autolinkingJsonPath, remote, onSkipped} = opts; -@@ -1162,7 +2536,7 @@ function collectAutolinkedDeps( +@@ -1162,7 +2538,7 @@ function collectAutolinkedDeps( const root = raw.root; const ios = raw.platforms?.ios; if (typeof root !== 'string' || ios == null) { @@ -4112,7 +4114,7 @@ index cf7e587..c19356d 100644 continue; } // $FlowFixMe[incompatible-type] `ios` shape is runtime-validated above -@@ -1294,6 +2668,11 @@ type ScaffoldAllOptions = { +@@ -1294,6 +2670,11 @@ type ScaffoldAllOptions = { // confirmation prompt for first-time scaffolds. Skipped deps still // appear in the returned results array with status='skipped-opt-out'. skipDeps?: ReadonlyArray, @@ -4124,7 +4126,7 @@ index cf7e587..c19356d 100644 }; */ -@@ -1323,6 +2702,17 @@ function scaffoldAll( +@@ -1323,6 +2704,17 @@ function scaffoldAll( // scaffolded here — leaving `react-native spm scaffold` unable to clear the // autolinker's missing-manifest error. const results /*: Array */ = []; @@ -4142,7 +4144,7 @@ index cf7e587..c19356d 100644 // Outside collectAutolinkedDeps' own try: a malformed remote config // (RemoteVersionError) is a misconfiguration to surface, not an expansion // failure to degrade past. -@@ -1330,24 +2720,23 @@ function scaffoldAll( +@@ -1330,24 +2722,23 @@ function scaffoldAll( const allDeps = collectAutolinkedDeps({ autolinkingJsonPath, remote, @@ -4178,7 +4180,7 @@ index cf7e587..c19356d 100644 for (const dep of allDeps) { const podspecPath = dep.platforms?.ios?.podspecPath; if (typeof podspecPath === 'string' && podspecPath.length > 0) { -@@ -1386,6 +2775,9 @@ function scaffoldAll( +@@ -1386,6 +2777,9 @@ function scaffoldAll( const skipSet /*: Set */ = new Set(opts.skipDeps ?? []); for (const dep of allDeps) { @@ -4188,7 +4190,7 @@ index cf7e587..c19356d 100644 if (skipSet.has(dep.name)) { results.push({ depName: dep.name, -@@ -1404,6 +2796,9 @@ function scaffoldAll( +@@ -1404,6 +2798,9 @@ function scaffoldAll( } module.exports = { diff --git a/src/pipeline/patches.ts b/src/pipeline/patches.ts index adeba7c..07ff7bd 100644 --- a/src/pipeline/patches.ts +++ b/src/pipeline/patches.ts @@ -359,7 +359,7 @@ const SLOT_LABEL_RE = /^\+\/\/ Cache slot: (\S+)\/dual-flavor\s*$/m; const REVISION_RE = /^\+\/\/ (?:rn|expo)-xtool-scaffold-revision: (\d+)\s*$/m; /** The scaffolder's RN_XTOOL_SCAFFOLD_REVISION (patches/react-native+0.88.{0,1}.patch and vendor/rn-spm). */ -export const SCAFFOLD_REVISION = 6; +export const SCAFFOLD_REVISION = 7; const PATCH_PODS_RE = /^\+\/\/ rn-xtool-pods: (.*?)\s*$/m; const MANIFEST_PODS_RE = /^\/\/ rn-xtool-pods: (.*?)\s*$/m; diff --git a/tests/capabilities.test.ts b/tests/capabilities.test.ts index a2db48b..9e04963 100644 --- a/tests/capabilities.test.ts +++ b/tests/capabilities.test.ts @@ -605,7 +605,7 @@ describe("detectCapabilities", () => { }); const lines = [ "// AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package.", - "// rn-xtool-scaffold-revision: 6", + "// rn-xtool-scaffold-revision: 7", "// rn-xtool-pods: AppAuth=3.0.0", "// Cache slot: 0.88.1/dual-flavor", ]; diff --git a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift index 480f6f3..b1c6028 100644 --- a/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift +++ b/tests/fixtures/scaffold-golden/@react-native-community/datetimepicker/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["ios","ios/fabric","ios/fabric/cpp/react/renderer/components/RNDateTimePicker","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift index bac444b..08d0812 100644 --- a/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-gesture-handler/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["apple/Handlers","apple","shared/runtime","shared/shadowNodes/react/renderer/components/rngesturehandler_codegen","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift index 2db17bd..ea3c025 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.4;(experimentalMultiLang) // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift index e03f505..83bee0e 100644 --- a/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift +++ b/tests/fixtures/scaffold-golden/react-native-pager-view/Package@swift-6.5.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.5 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["ios",".","rn-spm-swift"] // rn-xtool-pods: SwiftUIIntrospect=1.5.0 // Cache slot: 0.86.3/dual-flavor diff --git a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift index ed24bb1..9798423 100644 --- a/tests/fixtures/scaffold-golden/react-native-screens/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-screens/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["common/cpp","common/cpp/react/renderer/components/rnscreens","common/cpp/react/renderer/components/rnscreens/utils","cpp","ios","ios/bridging","ios/conversion","ios/events","ios/helpers/container","ios/helpers/image","ios/helpers/scroll-view","ios/integrations","ios/safe-area","ios/stubs","ios/tabs","ios/tabs/bottom-accessory","ios/tabs/extensions","ios/tabs/host","ios/tabs/screen","ios/utils","ios/utils/extensions",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift index b817f81..bcc1fd1 100644 --- a/tests/fixtures/scaffold-golden/react-native-svg/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-svg/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["common/cpp","apple/Brushes","apple/Elements","apple/Filters/MetalCI","apple/Filters","apple","apple/Shapes","apple/Text","apple/Utils","apple/ViewManagers","common/cpp/react/renderer/components/rnsvg",".","include"] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift index 6907046..ce80066 100644 --- a/tests/fixtures/scaffold-golden/react-native-webview/Package.swift +++ b/tests/fixtures/scaffold-golden/react-native-webview/Package.swift @@ -1,7 +1,7 @@ // swift-tools-version: 6.0 // AUTO-SCAFFOLDED by react-native spm scaffold — safe to edit & commit via patch-package. // AUTO-SCAFFOLDED-VERSION: 20 -// rn-xtool-scaffold-revision: 6 +// rn-xtool-scaffold-revision: 7 // rn-xtool-swift-importer-paths: ["apple","."] // Cache slot: 0.86.3/dual-flavor // Edit the contents below if needed and re-run `npx patch-package ` diff --git a/tests/patches.test.ts b/tests/patches.test.ts index 7028350..31f387c 100644 --- a/tests/patches.test.ts +++ b/tests/patches.test.ts @@ -916,7 +916,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "@scope+lib+1.0.0.patch"), scaffoldPatch(null, 1)); // Revision 2 wrote no importer paths for a clang-only target. await writeFile(path.join(root, "patches", "react-native-screens+4.30.1.patch"), scaffoldPatch("0.87.1", 2)); - await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 6)); + await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.87.1", 7)); // Both stale: the slot warning wins, one line per patch. await writeFile(path.join(root, "patches", "react-native-safe-area-context+5.6.0.patch"), scaffoldPatch("0.86.3", 1)); await installPkg(root, "react-native-screens"); @@ -924,15 +924,15 @@ describe("scaffold patches from another React Native version", () => { await installPkg(root, "react-native-svg"); await installPkg(root, "react-native-safe-area-context"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it so rn-xtool " + + "⚠ patches/@scope+lib+1.0.0.patch was written by an older rn-xtool scaffolder (revision 1, now 7); delete it so rn-xtool " + "regenerates it (also remove node_modules/@scope/lib and reinstall: that copy still has the old Package.swift)", "⚠ patches/react-native-safe-area-context+5.6.0.patch was scaffolded for React Native 0.86.3; delete it so rn-xtool " + "regenerates it for 0.87.1 (also remove node_modules/react-native-safe-area-context and reinstall: that copy still has " + "the old Package.swift)", - "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it so " + + "⚠ patches/react-native-screens+4.30.0.patch was written by an older rn-xtool scaffolder (revision 1, now 7); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", - "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 6); delete it so " + + "⚠ patches/react-native-screens+4.30.1.patch was written by an older rn-xtool scaffolder (revision 2, now 7); delete it so " + "rn-xtool regenerates it (also remove node_modules/react-native-screens and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -945,7 +945,7 @@ describe("scaffold patches from another React Native version", () => { await writeFile(path.join(root, "patches", "react-native-svg+15.16.0.patch"), scaffoldPatch("0.88.1", 3)); await installPkg(root, "react-native-svg"); expect(scaffoldPatchWarnings(root)).toEqual([ - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 6); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 3, now 7); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -963,7 +963,7 @@ describe("scaffold patches from another React Native version", () => { expect(scaffoldPatchWarnings(root)).toEqual([ "⚠ patches/react-native-screens+4.30.0.patch was scaffolded for React Native 0.88.0; delete it so rn-xtool regenerates " + "it for 0.88.1 (also remove node_modules/react-native-screens and reinstall: that copy still has the old Package.swift)", - "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 6); delete it " + + "⚠ patches/react-native-svg+15.16.0.patch was written by an older rn-xtool scaffolder (revision 1, now 7); delete it " + "so rn-xtool regenerates it (also remove node_modules/react-native-svg and reinstall: that copy still has the old " + "Package.swift)", ]); @@ -1038,7 +1038,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("replaces an older node_modules copy of a current persisted patch (a teammate's pull)", async () => { const root = await project(); await installPkg(root, "react-native-screens", "4.30.0"); - const current = { "Package.swift": manifest(6, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; + const current = { "Package.swift": manifest(7, "0.87.1"), "include/rnscreens/RNSDefines.h": stub("RNSDefines.h") }; await put(root, "patches/react-native-screens+4.30.0.patch", newFilesPatch("react-native-screens", current)); // What the old patch left in node_modules: revision 1, slot 0.86.3, a stub the new scaffold no longer writes. await put(root, "node_modules/react-native-screens/Package.swift", manifest(1, "0.86.3")); @@ -1051,7 +1051,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(existsSync(path.join(root, "node_modules/react-native-screens/include/rnscreens/Gone.h"))).toBe(true); expect(lines).toEqual([ "ℹ node_modules/react-native-screens/Package.swift was scaffolded with revision 1 for React Native 0.86.3, " + - "older than patches/react-native-screens+4.30.0.patch (revision 6, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-screens+4.30.0.patch (revision 7, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); // Idempotent: the next build changes nothing. @@ -1067,7 +1067,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the const forwarder = "// AUTO-SCAFFOLDED by react-native spm scaffold — forwards to the public headers of the pod AppAuth.\n" + "#import \n#import \n"; - const current = { "Package.swift": manifest(6, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; + const current = { "Package.swift": manifest(7, "0.87.1"), "rn-spm-pod-headers/AppAuth/AppAuth.h": forwarder }; await put(root, "patches/react-native-app-auth+8.5.1.patch", newFilesPatch("react-native-app-auth", current)); await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(3, "0.87.1")); await put(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h", forwarder); @@ -1077,7 +1077,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/react-native-app-auth/rn-spm-pod-headers/AppAuth/AppAuth.h")).toBe(forwarder); expect(lines).toEqual([ "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded with revision 3 for React Native 0.87.1, " + - "older than patches/react-native-app-auth+8.5.1.patch (revision 6, React Native 0.87.1): rn-xtool replaced it " + + "older than patches/react-native-app-auth+8.5.1.patch (revision 7, React Native 0.87.1): rn-xtool replaced it " + "with the persisted one", ]); }, 30_000); @@ -1100,7 +1100,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the " line 3", "", ].join("\n"); - await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(6, "0.87.1") }) + fix); + await put(root, "patches/lib+1.0.0.patch", newFilesPatch("lib", { "Package.swift": manifest(7, "0.87.1") }) + fix); await put(root, "node_modules/lib/Package.swift", manifest(1, "0.86.3")); await put(root, "node_modules/lib/ios/Foo.m", "line 1\nnew\nline 3\n"); for (const run of [1, 2]) { @@ -1109,7 +1109,7 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the expect(read(root, "node_modules/lib/Package.swift"), `run ${run}`).toBe(manifest(1, "0.86.3")); expect(lines, `run ${run}`).toEqual([ "⚠ node_modules/lib/Package.swift was scaffolded with revision 1 for React Native 0.86.3, older than " + - "patches/lib+1.0.0.patch (revision 6, React Native 0.87.1), and that patch also changes the library's own " + + "patches/lib+1.0.0.patch (revision 7, React Native 0.87.1), and that patch also changes the library's own " + "files, so rn-xtool does not replace it: run rm -rf node_modules/lib && npm install, then build again", ]); } @@ -1118,14 +1118,14 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("treats the pre-rename marker in node_modules as an older revision", async () => { const root = await project(); await installPkg(root, "react-native-svg", "15.16.0"); - await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(6, "0.87.1") })); + await put(root, "patches/react-native-svg+15.16.0.patch", newFilesPatch("react-native-svg", { "Package.swift": manifest(7, "0.87.1") })); await put(root, "node_modules/react-native-svg/Package.swift", manifest(1, "0.87.1", "expo-xtool-scaffold-revision")); const lines: string[] = []; await applyPatches(root, undefined, { ...noBundled, log: (l) => lines.push(l) }); - expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(6, "0.87.1")); + expect(read(root, "node_modules/react-native-svg/Package.swift")).toBe(manifest(7, "0.87.1")); expect(lines).toEqual([ "ℹ node_modules/react-native-svg/Package.swift was scaffolded with revision 1 for React Native 0.87.1, older than " + - "patches/react-native-svg+15.16.0.patch (revision 6, React Native 0.87.1): rn-xtool replaced it with the " + + "patches/react-native-svg+15.16.0.patch (revision 7, React Native 0.87.1): rn-xtool replaced it with the " + "persisted one", ]); }, 30_000); @@ -1133,36 +1133,40 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the it("removes a stale scaffold with no persisted patch, so the rn-spm step scaffolds it again", async () => { const root = await project(); await put(root, "node_modules/react-native-webview/Package.swift", manifest(2, "0.87.1")); - await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(6, "0.86.3")); + await put(root, "node_modules/@react-native-community/datetimepicker/Package.swift", manifest(7, "0.86.3")); await put(root, "node_modules/legacy-lib/Package.swift", manifest(1, null, "expo-xtool-scaffold-revision")); // Revision 4 (0.1.0-alpha.6) wrote pod header forwarders with @import, which Objective-C++ cannot compile. await put(root, "node_modules/react-native-app-auth/Package.swift", manifest(4, "0.87.1")); // Revision 5 read the source globs react-native-screens 4.24.0 builds from Ruby locals as empty. await put(root, "node_modules/react-native-screens/Package.swift", manifest(5, "0.87.1")); + // Revision 6 lost the defines react-native-worklets 0.8.3 builds from its package.json. + await put(root, "node_modules/react-native-worklets/Package.swift", manifest(6, "0.87.1")); const lines: string[] = []; await applyPatches(root, async () => ({ exitCode: 0 }), { ...noBundled, log: (l) => lines.push(l) }); - for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib", "react-native-app-auth", "react-native-screens"]) { + for (const pkg of ["react-native-webview", "@react-native-community/datetimepicker", "legacy-lib", "react-native-app-auth", "react-native-screens", "react-native-worklets"]) { expect(existsSync(path.join(root, "node_modules", pkg, "Package.swift")), pkg).toBe(false); } expect(lines).toEqual([ "ℹ node_modules/@react-native-community/datetimepicker/Package.swift was scaffolded for React Native 0.86.3, not " + "0.87.1: rn-xtool removed it so the rn-spm step scaffolds it again", - "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 6): " + + "ℹ node_modules/legacy-lib/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 1, now 7): " + "rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-app-auth/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 4, now " + - "6): rn-xtool removed it so the rn-spm step scaffolds it again", + "7): rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-screens/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 5, now " + - "6): rn-xtool removed it so the rn-spm step scaffolds it again", + "7): rn-xtool removed it so the rn-spm step scaffolds it again", "ℹ node_modules/react-native-webview/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 2, now " + - "6): rn-xtool removed it so the rn-spm step scaffolds it again", + "7): rn-xtool removed it so the rn-spm step scaffolds it again", + "ℹ node_modules/react-native-worklets/Package.swift was scaffolded by an older rn-xtool scaffolder (revision 6, now " + + "7): rn-xtool removed it so the rn-spm step scaffolds it again", ]); }); it("leaves current, foreign and stale-patch manifests alone", async () => { const root = await project(); const files: Record = { - // Current: revision 6 on the installed React Native. - "node_modules/current-lib/Package.swift": manifest(6, "0.87.1"), + // Current: revision 7 on the installed React Native. + "node_modules/current-lib/Package.swift": manifest(7, "0.87.1"), // Not rn-xtool's: the upstream scaffolder without rn-xtool's marker (a library may ship it), or hand-written. "node_modules/upstream-lib/Package.swift": manifest(0, null, null), "node_modules/own-lib/Package.swift": "// swift-tools-version: 6.0\nimport PackageDescription\n", @@ -1170,8 +1174,8 @@ describe("scaffolded manifests in node_modules older than the scaffolder or the "node_modules/react-native-screens/Package.swift": manifest(1, "0.86.3"), "patches/react-native-screens+4.30.0.patch": newFilesPatch("react-native-screens", { "Package.swift": manifest(1, "0.86.3") }), // A current patch over a current copy. - "node_modules/react-native-svg/Package.swift": manifest(6, "0.87.1"), - "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(6, "0.87.1") }), + "node_modules/react-native-svg/Package.swift": manifest(7, "0.87.1"), + "patches/react-native-svg+15.16.0.patch": newFilesPatch("react-native-svg", { "Package.swift": manifest(7, "0.87.1") }), }; for (const [rel, text] of Object.entries(files)) await put(root, rel, text); for (const pkg of ["react-native-screens", "react-native-svg"]) await installPkg(root, pkg); diff --git a/tests/rn-scaffolder.test.ts b/tests/rn-scaffolder.test.ts index 21734e2..a4a9ded 100644 --- a/tests/rn-scaffolder.test.ts +++ b/tests/rn-scaffolder.test.ts @@ -157,7 +157,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () expect(src("read-podspec.js")).toContain("const RN_POD_ENV"); expect(src("read-podspec.js")).toContain("env: {...process.env, ...RN_POD_ENV}"); const f = src("scaffold-package-swift.js"); - expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 6"); + expect(f).toContain("RN_XTOOL_SCAFFOLD_REVISION = 7"); expect(f).toContain("rn-xtool-swift-importer-paths"); expect(f).toContain("function importsOwnSwiftHeader"); expect(f).toContain("function clangModuleExcludes"); @@ -1109,7 +1109,7 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () it("emits the rn-xtool-scaffold-revision marker next to AUTO-SCAFFOLDED-VERSION", () => { const pkg = readFileSync(path.join(fresh(), "Package.swift"), "utf8"); - expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 6$/m); + expect(pkg).toMatch(/^\/\/ AUTO-SCAFFOLDED-VERSION: \d+\n\/\/ rn-xtool-scaffold-revision: 7$/m); }); it("keeps a scaffold that carries the current marker", () => { @@ -1122,14 +1122,14 @@ describe.skipIf(NEEDS_RN !== "")(`patched RN SwiftPM scaffolder${NEEDS_RN}`, () writeFileSync(file, readFileSync(file, "utf8").replace(/^\/\/ rn-xtool-scaffold-revision: \d+\n/m, "").replace("exact:", "from:")); expect(scaffoldAgain(root)).toBe("written"); const pkg = readFileSync(file, "utf8"); - expect(pkg).toContain("rn-xtool-scaffold-revision: 6"); + expect(pkg).toContain("rn-xtool-scaffold-revision: 7"); expect(pkg).toContain('exact: "1.5.0"'); }); it("regenerates a scaffold whose marker is lower than the current revision", () => { const root = fresh(); const file = path.join(root, "Package.swift"); - writeFileSync(file, readFileSync(file, "utf8").replace("revision: 6", "revision: 5")); + writeFileSync(file, readFileSync(file, "utf8").replace("revision: 7", "revision: 6")); expect(scaffoldAgain(root)).toBe("written"); }); }); @@ -1214,7 +1214,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { // Mixed (pager-view) or clang-only, each of these targets searches beyond its public headers path, so each // manifest records its importer paths right after the revision line. for (const k of manifests) { - expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); + expect(now.files[k], k).toMatch(/^\/\/ rn-xtool-scaffold-revision: 7\n\/\/ rn-xtool-swift-importer-paths: \[.+\]$/m); } expect(now.files).toEqual(golden.files); }, @@ -1317,7 +1317,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { it("17: records the Swift importer paths", () => { for (const manifest of ["Package.swift", "Package@swift-6.5.swift"]) { const pkg = file(`react-native-screens/${manifest}`); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 7\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("."); expect(paths).toContain("ios/bridging"); @@ -1332,7 +1332,7 @@ describe("scaffolder fixes 14–19 (vendor/rn-spm)", () => { expect(pkg.split("\n")[0]).toBe("// swift-tools-version: 6.0"); expect(files["react-native-screens/Package@swift-6.5.swift"]).toBeUndefined(); expect(pkg).toContain('publicHeadersPath: "ios",'); - expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); + expect(pkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 7\n\/\/ rn-xtool-swift-importer-paths: \[.*\]$/m); const paths = JSON.parse(pkg.match(IMPORTER)![1]!) as string[]; expect(paths).toContain("ios/utils"); expect(paths).toEqual(searchPaths(pkg)); @@ -2151,7 +2151,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { const pkg = manifest(scaffold(`${APPAUTH_DEP}\n s.dependency "SwiftUIIntrospect", '~> 1.0'`, table)); // Clang-only, searching beyond its public headers: after the importer-paths line. expect(pkg).toMatch( - /^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, + /^\/\/ rn-xtool-scaffold-revision: 7\n\/\/ rn-xtool-swift-importer-paths: \[.*\]\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0, SwiftUIIntrospect=1\.5\.0\n\/\/ Cache slot: /m, ); // Pure Swift (no importer-paths line): after the revision line. const swift = tempDir(); @@ -2163,7 +2163,7 @@ describe("scaffolder fix 13: the pod table (vendor/rn-spm)", () => { `Pod::Spec.new do |s|\n s.name = "Foo"\n s.source_files = "ios/**/*.swift"\n${APPAUTH_DEP}\nend\n`, ); const swiftPkg = manifest(withTable(table, () => scaffoldLibraries(VENDORED_RN_SPM, { foo: swift }))); - expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 6\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); + expect(swiftPkg).toMatch(/^\/\/ rn-xtool-scaffold-revision: 7\n\/\/ rn-xtool-pods: AppAuth=3\.0\.0\n/m); // No pinned pod, no line. expect(manifest(scaffold("", table))).not.toContain("rn-xtool-pods"); }); diff --git a/vendor/rn-spm/spm/scaffold-package-swift.js b/vendor/rn-spm/spm/scaffold-package-swift.js index c19356d..f105e49 100644 --- a/vendor/rn-spm/spm/scaffold-package-swift.js +++ b/vendor/rn-spm/spm/scaffold-package-swift.js @@ -133,8 +133,10 @@ const SCAFFOLDER_VERSION_LINE_RE = /^\/\/ AUTO-SCAFFOLDED-VERSION: (\d+)$/m; // its modules, which stopped every Objective-C++ file that included them. // Revision 6 (fix 28): source globs built from Ruby locals and conditions // (react-native-screens 4.24.0 had no ios/ sources), and the branches a -// condition rules out left out of the target. -const RN_XTOOL_SCAFFOLD_REVISION = 6; +// condition rules out left out of the target. Revision 7: the defines a +// podspec builds from its package.json and partly evaluated strings +// (react-native-worklets 0.8.3's WORKLETS_VERSION), which revision 6 lost. +const RN_XTOOL_SCAFFOLD_REVISION = 7; const RN_XTOOL_SCAFFOLD_REVISION_RE = /^\/\/ rn-xtool-scaffold-revision: (\d+)$/m; // An importer (Swift, or a Clang module) builds the target's module from its