From 67e82859cd3316ecd4fba4316b46463f48bd1566 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 13:12:14 +0000 Subject: [PATCH 1/3] feat(react-native): add xcode command Port `react-native xcode` from the legacy CLI. Uploads React Native sourcemaps from an Xcode build phase, in three modes: - release build: wraps the RN build script (this CLI stands in for NODE_BINARY / HERMES_CLI_PATH via __SENTRY_RN_WRAP_XCODE_CALL, dispatched in bin.ts) to capture the produced bundle + sourcemap (incl. the Hermes combined sourcemap), then injects a debug ID and uploads. - simulator build with --allow-fetch: downloads bundle + sourcemap from the packager, then uploads. - debug build: just runs the build script. Release/dist come from SENTRY_RELEASE/SENTRY_DIST or the app Info.plist (@+), unless --no-auto-release. New: src/commands/react-native/xcode.ts, src/lib/react-native/{wrap-call,xcode-env}.ts; bin.ts wrap dispatch. Tests: xcode-env (plist/expand/release), wrap-call (bundle/ hermes/compose parsing + debug-id copy), command modes. Limitations vs legacy (documented): Info.plist C preprocessing and xcodebuild-outside-Xcode discovery are unsupported (set SENTRY_RELEASE/DIST); indexed RAM bundles unsupported. --- docs/src/content/docs/contributing.md | 2 +- docs/src/fragments/commands/react-native.md | 24 + plugins/sentry-cli/skills/sentry-cli/SKILL.md | 1 + .../sentry-cli/references/react-native.md | 17 + src/bin.ts | 9 + src/commands/react-native/index.ts | 2 + src/commands/react-native/xcode.ts | 428 ++++++++++++++++++ src/lib/react-native/wrap-call.ts | 192 ++++++++ src/lib/react-native/xcode-env.ts | 212 +++++++++ test/commands/react-native/xcode.test.ts | 168 +++++++ test/lib/react-native/wrap-call.test.ts | 130 ++++++ test/lib/react-native/xcode-env.test.ts | 156 +++++++ 12 files changed, 1340 insertions(+), 1 deletion(-) create mode 100644 src/commands/react-native/xcode.ts create mode 100644 src/lib/react-native/wrap-call.ts create mode 100644 src/lib/react-native/xcode-env.ts create mode 100644 test/commands/react-native/xcode.test.ts create mode 100644 test/lib/react-native/wrap-call.test.ts create mode 100644 test/lib/react-native/xcode-env.test.ts diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index ea79a91610..313ce00799 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -68,7 +68,7 @@ cli/ │ │ ├── org/ # list, view │ │ ├── proguard/ # upload, uuid │ │ ├── project/ # create, delete, list, view -│ │ ├── react-native/# gradle +│ │ ├── react-native/# gradle, xcode │ │ ├── release/ # archive, create, delete, deploy, deploys, finalize, list, propose-version, restore, set-commits, view │ │ ├── replay/ # list, view │ │ ├── repo/ # list diff --git a/docs/src/fragments/commands/react-native.md b/docs/src/fragments/commands/react-native.md index e616ca86e9..6a18720da8 100644 --- a/docs/src/fragments/commands/react-native.md +++ b/docs/src/fragments/commands/react-native.md @@ -12,8 +12,32 @@ sentry react-native gradle \ --sourcemap index.android.bundle.map \ --release com.example.app@1.0.0 \ --dist 1000 + +# Xcode build phase (usually added automatically to your build script) +../node_modules/.bin/sentry-cli react-native xcode ``` +## Xcode build step (`react-native xcode`) + +`react-native xcode` runs inside an Xcode "Bundle React Native code and images" +build phase. It has three modes: + +- **release build** — wraps the RN build script (standing in for + `NODE_BINARY`/`HERMES_CLI_PATH`) to capture the produced bundle + sourcemap + (including the Hermes combined sourcemap), then uploads them. +- **simulator build with `--allow-fetch`** — downloads the bundle + sourcemap + from the running packager, then uploads. +- **debug build** — just runs the build script. + +Release/distribution come from `SENTRY_RELEASE`/`SENTRY_DIST` or the app's +`Info.plist` (`@+`), +unless `--no-auto-release` is set. Pass extra build-script arguments after the +flags. + +Limitations vs. the legacy CLI: `Info.plist` C preprocessing +(`INFOPLIST_PREPROCESS`) and `xcodebuild`-based discovery outside an Xcode build +are not supported — set `SENTRY_RELEASE`/`SENTRY_DIST` in those cases. + ## Important Notes - `react-native gradle` is normally invoked automatically by the diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 7aa538f803..620acb853b 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -457,6 +457,7 @@ Work with ProGuard/R8 mapping files Upload React Native sourcemaps from build steps - `sentry react-native gradle` — Upload a React Native bundle + sourcemap (Gradle build step) +- `sentry react-native xcode ` — Upload React Native sourcemaps (Xcode build step) → Full flags and examples: `references/react-native.md` diff --git a/plugins/sentry-cli/skills/sentry-cli/references/react-native.md b/plugins/sentry-cli/skills/sentry-cli/references/react-native.md index ccddd335f2..51f8a0eced 100644 --- a/plugins/sentry-cli/skills/sentry-cli/references/react-native.md +++ b/plugins/sentry-cli/skills/sentry-cli/references/react-native.md @@ -23,6 +23,20 @@ Upload a React Native bundle + sourcemap (Gradle build step) - `--wait - Accepted for compatibility (the CLI always waits for assembly)` - `--wait-for - Accepted for compatibility (the CLI always waits for assembly)` +### `sentry react-native xcode ` + +Upload React Native sourcemaps (Xcode build step) + +**Flags:** +- `-f, --force - Run even in a debug configuration` +- `--allow-fetch - Fetch sourcemaps from the packager on simulator builds` +- `--fetch-from - Packager URL to fetch from (default: http://127.0.0.1:8081/)` +- `--build-script - Path to the react-native-xcode.sh build script` +- `--dist ... - Distribution(s) to publish (repeatable)` +- `--wait - Accepted for compatibility (the CLI always waits for assembly)` +- `--wait-for - Accepted for compatibility (the CLI always waits for assembly)` +- `--no-auto-release - Don't read the release from Xcode project files` + **Examples:** ```bash @@ -37,6 +51,9 @@ sentry react-native gradle \ --sourcemap index.android.bundle.map \ --release com.example.app@1.0.0 \ --dist 1000 + +# Xcode build phase (usually added automatically to your build script) +../node_modules/.bin/sentry-cli react-native xcode ``` All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/src/bin.ts b/src/bin.ts index 99b5ec707d..e7821f6ec1 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -22,6 +22,15 @@ process.emit = ((event: string, ...args: unknown[]) => { }) as typeof process.emit; import { startCli } from "./cli.js"; +import { wrapCall } from "./lib/react-native/wrap-call.js"; + +// React Native Xcode build wrapper: when the RN build script invokes us in +// place of NODE_BINARY/HERMES_CLI_PATH (see `react-native xcode`), forward to +// the real Node/Hermes tool instead of running the CLI. Must run before any +// command parsing. +if (process.env.__SENTRY_RN_WRAP_XCODE_CALL === "1") { + process.exit(wrapCall()); +} // Handle non-recoverable stream I/O errors gracefully instead of crashing. // - EPIPE (errno -32): downstream pipe consumer closed (e.g., `sentry issue list | head`). diff --git a/src/commands/react-native/index.ts b/src/commands/react-native/index.ts index 075ced7074..96def32335 100644 --- a/src/commands/react-native/index.ts +++ b/src/commands/react-native/index.ts @@ -6,10 +6,12 @@ import { buildRouteMap } from "../../lib/route-map.js"; import { gradleCommand } from "./gradle.js"; +import { xcodeCommand } from "./xcode.js"; export const reactNativeRoute = buildRouteMap({ routes: { gradle: gradleCommand, + xcode: xcodeCommand, }, docs: { brief: "Upload React Native sourcemaps from build steps", diff --git a/src/commands/react-native/xcode.ts b/src/commands/react-native/xcode.ts new file mode 100644 index 0000000000..1b82367525 --- /dev/null +++ b/src/commands/react-native/xcode.ts @@ -0,0 +1,428 @@ +/** + * sentry react-native xcode + * + * Upload React Native sourcemaps from an Xcode build phase. Runs in three modes: + * + * - **debug** — a non-release build with no packager fetch: just run the RN + * build script and exit. + * - **fetch** — a simulator build with `--allow-fetch`: download the bundle + + * sourcemap from the running packager, then upload. + * - **wrap** — a release build: run the RN build script with this CLI standing + * in for `NODE_BINARY`/`HERMES_CLI_PATH` (see `wrap-call.ts`), read back the + * produced bundle + sourcemap from a JSON report, then upload. + * + * Mirrors the legacy `sentry-cli react-native xcode`. + */ + +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join, resolve } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import type { SentryContext } from "../../context.js"; +import type { ArtifactFile } from "../../lib/api/sourcemaps.js"; +import { uploadSourcemaps } from "../../lib/api/sourcemaps.js"; +import { buildCommand } from "../../lib/command.js"; +import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { logger } from "../../lib/logger.js"; +import type { SourceMapReport } from "../../lib/react-native/wrap-call.js"; +import { + findHermesc, + findNode, + resolveReleaseAndDist, +} from "../../lib/react-native/xcode-env.js"; +import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { injectDebugId } from "../../lib/sourcemap/debug-id.js"; + +const log = logger.withTag("react-native.xcode"); + +const USAGE_HINT = "sentry react-native xcode"; +const DEFAULT_PACKAGER_URL = "http://127.0.0.1:8081/"; +const DEFAULT_BUILD_SCRIPT = + "../node_modules/react-native/scripts/react-native-xcode.sh"; + +/** Matches one or more trailing slashes. */ +const TRAILING_SLASHES = /\/+$/; + +/** Flags accepted by `react-native xcode`. */ +type XcodeFlags = { + force?: boolean; + "allow-fetch"?: boolean; + "fetch-from"?: string; + "build-script"?: string; + dist?: string[]; + wait?: boolean; + "wait-for"?: number; + "no-auto-release"?: boolean; +}; + +/** Structured result for the xcode command. */ +type XcodeResult = { + mode: "debug" | "fetch" | "wrap"; + bundle?: string; + sourcemap?: string; + debugId?: string; + release?: string; + dist?: string[]; + uploads: number; +}; + +/** A resolved bundle + sourcemap pair to upload. */ +type BundlePair = { bundle: string; sourcemap: string }; + +function formatResult(data: XcodeResult): string { + const rows: [string, string][] = [["Mode", data.mode]]; + if (data.bundle) { + rows.push(["Bundle", data.bundle]); + } + if (data.sourcemap) { + rows.push(["Sourcemap", data.sourcemap]); + } + if (data.debugId) { + rows.push(["Debug ID", data.debugId]); + } + if (data.release) { + rows.push(["Release", data.release]); + } + if (data.dist && data.dist.length > 0) { + rows.push(["Distributions", data.dist.join(", ")]); + } + return renderMarkdown(mdKvTable(rows)); +} + +/** Whether the build script should be wrapped (release build or forced). */ +function shouldWrap(flags: XcodeFlags, env: NodeJS.ProcessEnv): boolean { + if (flags.force) { + return true; + } + const configuration = env.CONFIGURATION; + if (configuration === undefined) { + throw new ValidationError( + "Need to run this from Xcode (CONFIGURATION is not set).", + "CONFIGURATION" + ); + } + return !configuration.includes("Debug"); +} + +/** Resolve the RN build script path (canonicalized). */ +function resolveScript(flags: XcodeFlags, cwd: string): string { + const script = resolve(cwd, flags["build-script"] ?? DEFAULT_BUILD_SCRIPT); + if (!existsSync(script)) { + throw new ValidationError( + `React Native build script not found: ${script}`, + "build-script" + ); + } + return script; +} + +/** Run the build script directly, propagating its exit status. */ +function runScript( + script: string, + args: string[], + env: NodeJS.ProcessEnv +): number { + const rv = spawnSync(script, args, { stdio: "inherit", env }); + return rv.status ?? (rv.error ? 1 : 0); +} + +/** Poll a URL until it responds or the timeout elapses. */ +async function waitUntilAvailable( + url: string, + timeoutMs: number +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const res = await fetch(url, { method: "GET" }); + if (res.status < 500) { + return true; + } + } catch (err) { + log.debug("Packager not up yet", err); + } + await sleep(500); + } + return false; +} + +/** Fetch the bundle + sourcemap from the running RN packager. */ +async function fetchFromPackager( + fetchUrl: string, + tempDir: string +): Promise { + const url = fetchUrl.replace(TRAILING_SLASHES, ""); + if (!(await waitUntilAvailable(url, 10_000))) { + throw new ValidationError( + "React Native packager did not respond in time.", + "fetch-from" + ); + } + const bundle = join(tempDir, "index.ios.bundle"); + const sourcemap = join(tempDir, "index.ios.map"); + const bundleRes = await fetch( + `${url}/index.ios.bundle?platform=ios&dev=true` + ); + writeFileSync(bundle, Buffer.from(await bundleRes.arrayBuffer())); + const mapRes = await fetch(`${url}/index.ios.map?platform=ios&dev=true`); + writeFileSync(sourcemap, Buffer.from(await mapRes.arrayBuffer())); + return { bundle, sourcemap }; +} + +/** Run the wrapped build and read the produced bundle/sourcemap paths. */ +function runWrappedBuild( + script: string, + scriptArgs: string[], + ctx: SentryContext, + tempDir: string +): { status: number; pair: BundlePair | null } { + const reportPath = join(tempDir, "sourcemap-report.json"); + writeFileSync(reportPath, "{}"); + const node = findNode(ctx.env); + const hermesc = findHermesc(ctx.env); + const self = ctx.process.execPath; + + const env: NodeJS.ProcessEnv = { + ...ctx.env, + NODE_BINARY: self, + SENTRY_RN_REAL_NODE_BINARY: node, + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + __SENTRY_RN_WRAP_XCODE_CALL: "1", + }; + if (existsSync(hermesc)) { + env.HERMES_CLI_PATH = self; + env.SENTRY_RN_REAL_HERMES_CLI_PATH = hermesc; + } + + const status = runScript(script, scriptArgs, env); + + const report = JSON.parse( + readFileSync(reportPath, "utf-8") + ) as SourceMapReport; + if (!(report.packager_bundle_path && report.packager_sourcemap_path)) { + return { status, pair: null }; + } + // Prefer the Hermes bundle + combined sourcemap when present. + if (report.hermes_bundle_path && report.hermes_sourcemap_path) { + log.info("Using Hermes bundle and combined source map."); + return { + status, + pair: { + bundle: report.hermes_bundle_path, + sourcemap: report.hermes_sourcemap_path, + }, + }; + } + log.info("Using React Native Packager bundle and source map."); + return { + status, + pair: { + bundle: report.packager_bundle_path, + sourcemap: report.packager_sourcemap_path, + }, + }; +} + +/** Inject a debug id and upload the bundle/sourcemap pair. */ +async function uploadPair( + pair: BundlePair, + ctx: SentryContext, + flags: XcodeFlags +): Promise<{ + debugId: string; + release?: string; + dist: string[]; + uploads: number; +}> { + const resolved = await resolveOrgAndProject({ + cwd: ctx.cwd, + usageHint: USAGE_HINT, + }); + if (!resolved) { + throw new ContextError("Organization and project", USAGE_HINT); + } + const { org, project } = resolved; + + const { debugId } = await injectDebugId(pair.bundle, pair.sourcemap); + const files: ArtifactFile[] = [ + { + path: pair.bundle, + debugId, + type: "minified_source", + url: `~/${basename(pair.bundle)}`, + sourcemapFilename: basename(pair.sourcemap), + }, + { + path: pair.sourcemap, + debugId, + type: "source_map", + url: `~/${basename(pair.sourcemap)}`, + }, + ]; + + const { release, dist } = await resolveReleaseAndDist( + ctx.env, + ctx.cwd, + flags["no-auto-release"] ?? false + ); + // Explicit --dist overrides the environment/plist-derived distribution. + let dists: string[] = []; + if (flags.dist && flags.dist.length > 0) { + dists = flags.dist; + } else if (dist) { + dists = [dist]; + } + + let uploads = 0; + if (dists.length > 0) { + for (const d of dists) { + await uploadSourcemaps({ org, project, release, dist: d, files }); + uploads += 1; + } + } else { + await uploadSourcemaps({ org, project, release, files }); + uploads = 1; + } + return { debugId, release, dist: dists, uploads }; +} + +export const xcodeCommand = buildCommand({ + docs: { + brief: "Upload React Native sourcemaps (Xcode build step)", + fullDescription: + "Upload React Native sourcemaps from an Xcode build phase. In a release " + + "build the RN build script is wrapped so the produced bundle and " + + "sourcemap are captured and uploaded; in a simulator build with " + + "`--allow-fetch` they are fetched from the packager; in a debug build " + + "the script simply runs.\n\n" + + "Release/distribution come from `SENTRY_RELEASE`/`SENTRY_DIST` or the " + + "app Info.plist (unless `--no-auto-release`). The CLI always waits for " + + "server-side assembly; `--wait`/`--wait-for` are accepted for " + + "compatibility.", + }, + auth: false, + output: { + human: formatResult, + }, + parameters: { + flags: { + force: { + kind: "boolean", + brief: "Run even in a debug configuration", + optional: true, + }, + "allow-fetch": { + kind: "boolean", + brief: "Fetch sourcemaps from the packager on simulator builds", + optional: true, + }, + "fetch-from": { + kind: "parsed", + parse: String, + brief: `Packager URL to fetch from (default: ${DEFAULT_PACKAGER_URL})`, + optional: true, + }, + "build-script": { + kind: "parsed", + parse: String, + brief: "Path to the react-native-xcode.sh build script", + optional: true, + }, + dist: { + kind: "parsed", + parse: String, + variadic: true, + brief: "Distribution(s) to publish (repeatable)", + optional: true, + }, + wait: { + kind: "boolean", + brief: "Accepted for compatibility (the CLI always waits for assembly)", + optional: true, + }, + "wait-for": { + kind: "parsed", + parse: Number, + brief: "Accepted for compatibility (the CLI always waits for assembly)", + optional: true, + }, + "no-auto-release": { + kind: "boolean", + brief: "Don't read the release from Xcode project files", + optional: true, + }, + }, + aliases: { f: "force" }, + positional: { + kind: "array", + parameter: { + placeholder: "script-arg", + brief: "Extra arguments passed to the build script", + parse: String, + }, + }, + }, + async *func(this: SentryContext, flags: XcodeFlags, ...scriptArgs: string[]) { + const wrap = shouldWrap(flags, this.env); + const script = resolveScript(flags, this.cwd); + + const simulator = this.env.PLATFORM_NAME?.endsWith("simulator") ?? false; + const fetchUrl = + flags["allow-fetch"] && simulator + ? (flags["fetch-from"] ?? DEFAULT_PACKAGER_URL) + : undefined; + + // Debug build with no fetch: just run the script and exit. + if (!(wrap || fetchUrl)) { + log.info("Running in debug mode, skipping script wrapping."); + const status = runScript(script, scriptArgs, this.env); + if (status !== 0) { + this.process.exitCode = status; + } + yield new CommandOutput({ mode: "debug", uploads: 0 }); + return { hint: "Ran the React Native build script (debug mode)." }; + } + + const tempDir = mkdtempSync(join(tmpdir(), "sentry-rn-xcode-")); + let mode: "fetch" | "wrap"; + let pair: BundlePair | null; + if (fetchUrl) { + mode = "fetch"; + log.info(`Fetching sourcemaps from ${fetchUrl}`); + pair = await fetchFromPackager(fetchUrl, tempDir); + } else { + mode = "wrap"; + const result = runWrappedBuild(script, scriptArgs, this, tempDir); + if (result.status !== 0) { + this.process.exitCode = result.status; + } + pair = result.pair; + if (!pair) { + log.warn("Build produced no packager sourcemaps."); + yield new CommandOutput({ mode, uploads: 0 }); + return { hint: "No sourcemaps were produced by the build." }; + } + } + + log.info("Processing React Native sourcemaps for Sentry upload."); + const { debugId, release, dist, uploads } = await uploadPair( + pair, + this, + flags + ); + + yield new CommandOutput({ + mode, + bundle: pair.bundle, + sourcemap: pair.sourcemap, + debugId, + release, + dist: dist.length > 0 ? dist : undefined, + uploads, + }); + return { hint: `Uploaded sourcemaps with debug ID ${debugId}.` }; + }, +}); diff --git a/src/lib/react-native/wrap-call.ts b/src/lib/react-native/wrap-call.ts new file mode 100644 index 0000000000..0c383cf0fa --- /dev/null +++ b/src/lib/react-native/wrap-call.ts @@ -0,0 +1,192 @@ +/** + * React Native Xcode build wrapper (`wrap_call`). + * + * When `react-native xcode` runs a release build it re-points `NODE_BINARY` + * (and `HERMES_CLI_PATH`) at this CLI and sets `__SENTRY_RN_WRAP_XCODE_CALL=1`. + * The RN build script then invokes us in place of Node/Hermes; we parse the + * bundle/sourcemap paths out of the arguments, forward the call to the real + * tool, record what we learned in a JSON report, and (for Hermes) copy the + * packager debug ID into the combined sourcemap. + * + * Mirrors the legacy `sentry-cli react-native xcode`'s `wrap_call`. + */ + +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +import { logger } from "../logger.js"; + +const log = logger.withTag("react-native.wrap"); + +/** Paths discovered while wrapping the RN build tools. */ +export type SourceMapReport = { + packager_bundle_path?: string; + packager_sourcemap_path?: string; + hermes_bundle_path?: string; + hermes_sourcemap_path?: string; +}; + +/** Whether this process is a Node Single Executable Application. */ +function isSea(): boolean { + try { + const req = createRequire(import.meta.url); + const sea = req("node:sea") as { isSea?: () => boolean }; + return sea.isSea?.() === true; + } catch { + return false; + } +} + +/** + * The arguments the RN build script passed to us (i.e. everything after the + * program). In a SEA binary `argv[0]` is the binary; under `node script …` + * `argv[1]` is the script. + */ +function getWrapArgs(): string[] { + return isSea() ? process.argv.slice(1) : process.argv.slice(2); +} + +/** Read the JSON report file if present, else start fresh. */ +function loadReport(path: string): SourceMapReport { + if (!existsSync(path)) { + return {}; + } + try { + return JSON.parse(readFileSync(path, "utf-8")) as SourceMapReport; + } catch { + return {}; + } +} + +/** Extract the value following `flag` (supports `--flag value` and `--flag=value`). */ +function extractArg(args: string[], flag: string): string | undefined { + const prefix = `${flag}=`; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === undefined) { + continue; + } + if (arg === flag) { + return args[i + 1]; + } + if (arg.startsWith(prefix)) { + return arg.slice(prefix.length); + } + } + return; +} + +/** Whether the invocation is an RN packager bundle command. */ +function isBundleCommand(args: string[], bundleCommand?: string): boolean { + const sub = args[1]; + if (sub === undefined) { + return false; + } + if (bundleCommand) { + return sub === bundleCommand; + } + return sub === "bundle" || sub === "ram-bundle" || sub === "export:embed"; +} + +/** Parse packager bundle output, adding a `--sourcemap-output` if missing. */ +function handleBundle(args: string[], report: SourceMapReport): void { + const bundle = extractArg(args, "--bundle-output"); + let sourcemap = extractArg(args, "--sourcemap-output"); + + if (!sourcemap && bundle) { + const mapName = `${basename(bundle, ".jsbundle")}.jsbundle.map`; + sourcemap = join(tmpdir(), mapName); + args.push("--sourcemap-output", sourcemap); + } + report.packager_sourcemap_path = sourcemap; + report.packager_bundle_path = bundle; +} + +/** Copy the packager sourcemap's debug ID into the Hermes combined sourcemap. */ +function copyDebugId(report: SourceMapReport): void { + const { + packager_sourcemap_path: pkgPath, + hermes_sourcemap_path: hermesPath, + } = report; + if (!(pkgPath && hermesPath)) { + log.debug("Missing packager/Hermes sourcemap path; skipping debug id copy"); + return; + } + let pkg: Record; + let hermes: Record; + try { + pkg = JSON.parse(readFileSync(pkgPath, "utf-8")) as Record; + hermes = JSON.parse(readFileSync(hermesPath, "utf-8")) as Record< + string, + unknown + >; + } catch (err) { + log.debug("Could not read sourcemaps for debug id copy", err); + return; + } + if ("debugId" in hermes || "debug_id" in hermes) { + return; + } + const debugId = pkg.debugId ?? pkg.debug_id; + if (debugId === undefined) { + return; + } + hermes.debugId = debugId; + hermes.debug_id = debugId; + writeFileSync(hermesPath, JSON.stringify(hermes)); +} + +/** + * Run the wrapped Node/Hermes invocation, updating the sourcemap report. + * + * @returns The exit code of the wrapped process. + */ +export function wrapCall(env: NodeJS.ProcessEnv = process.env): number { + const reportPath = env.SENTRY_RN_SOURCEMAP_REPORT; + if (!reportPath) { + throw new Error("SENTRY_RN_SOURCEMAP_REPORT is not set"); + } + const report = loadReport(reportPath); + const args = getWrapArgs(); + const noDebugId = env.SENTRY_RN_NO_DEBUG_ID === "1"; + + let executeHermes = false; + let shouldCopyDebugId = false; + + const first = args[0]; + const isCompose = + first !== undefined && + (first.endsWith("compose-source-maps.js") || + (Boolean(env.COMPOSE_SOURCEMAP_PATH) && + first === env.COMPOSE_SOURCEMAP_PATH)); + if (isBundleCommand(args, env.SENTRY_RN_BUNDLE_COMMAND)) { + handleBundle(args, report); + } else if (args.length > 1 && first === "-emit-binary") { + executeHermes = true; + report.hermes_bundle_path = extractArg(args, "-out"); + } else if (args.length > 1 && isCompose) { + report.hermes_sourcemap_path = extractArg(args, "-o"); + shouldCopyDebugId = true; + } + + const executable = executeHermes + ? env.SENTRY_RN_REAL_HERMES_CLI_PATH + : env.SENTRY_RN_REAL_NODE_BINARY; + if (!executable) { + throw new Error( + "Missing SENTRY_RN_REAL_NODE_BINARY / SENTRY_RN_REAL_HERMES_CLI_PATH" + ); + } + + const rv = spawnSync(executable, args, { stdio: "inherit" }); + const status = rv.status ?? (rv.error ? 1 : 0); + + if (!noDebugId && shouldCopyDebugId) { + copyDebugId(report); + } + + writeFileSync(reportPath, JSON.stringify(report)); + return status; +} diff --git a/src/lib/react-native/xcode-env.ts b/src/lib/react-native/xcode-env.ts new file mode 100644 index 0000000000..5f748c3228 --- /dev/null +++ b/src/lib/react-native/xcode-env.ts @@ -0,0 +1,212 @@ +/** + * Xcode build-environment helpers for `react-native xcode`. + * + * Ports the pieces of the legacy `utils/xcode` needed to (a) locate the Node and + * Hermes compilers the way the React Native build script does, and (b) derive a + * release/distribution from the build environment or the project `Info.plist`. + */ + +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +/** Bundle identity extracted from an `Info.plist` or the build environment. */ +export type InfoPlist = { + /** `CFBundleName` / `PRODUCT_NAME`. */ + name: string; + /** `CFBundleIdentifier` / `PRODUCT_BUNDLE_IDENTIFIER`. */ + bundleId: string; + /** `CFBundleShortVersionString` / `MARKETING_VERSION`. */ + version: string; + /** `CFBundleVersion` / `CURRENT_PROJECT_VERSION`. */ + build: string; +}; + +/** A read-only view of the process environment. */ +type Env = Record; + +/** + * Resolve the Node binary the RN build script should call, matching the legacy + * `find_node`: `NODE_BINARY` if set and non-empty, else `node`. + */ +export function findNode(env: Env): string { + const fromEnv = env.NODE_BINARY; + return fromEnv && fromEnv.length > 0 ? fromEnv : "node"; +} + +/** + * Resolve the Hermes compiler path, matching the legacy `find_hermesc`: + * `HERMES_CLI_PATH` if set, else `$PODS_ROOT/hermes-engine/destroot/bin/hermesc`. + */ +export function findHermesc(env: Env): string { + const fromEnv = env.HERMES_CLI_PATH; + if (fromEnv && fromEnv.length > 0) { + return fromEnv; + } + const podsRoot = env.PODS_ROOT ?? ""; + return `${podsRoot}/hermes-engine/destroot/bin/hermesc`; +} + +/** + * Expand Xcode-style variable references (`$(VAR)`, `${VAR}`) in a string, + * supporting the `:rfc1034identifier` and `:identifier` modifiers. + * + * @param input - The string possibly containing variable references. + * @param vars - The variable table (typically the process environment). + */ +export function expandXcodeVars(input: string, vars: Env): string { + return input.replace(/\$[({]([^)}]*)[)}]/g, (_match, key: string) => { + if (!key) { + return ""; + } + const colon = key.indexOf(":"); + const name = colon < 0 ? key : key.slice(0, colon); + const modifier = colon < 0 ? undefined : key.slice(colon + 1); + const value = vars[name] ?? ""; + if (modifier === "rfc1034identifier") { + return value.replace(/[\s/]+/g, "-"); + } + if (modifier === "identifier") { + return value.replace(/[\s/]+/g, "_"); + } + return value; + }); +} + +/** Decode the handful of XML entities that appear in plist string values. */ +function decodeXmlEntities(value: string): string { + return value + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, "&"); +} + +/** + * Extract `……` pairs from an XML `Info.plist`. + * + * This is a deliberately small parser: it only reads top-level string entries, + * which is all the CFBundle* metadata the command needs. Binary plists are not + * supported (the source `Info.plist` referenced by `INFOPLIST_FILE` is XML). + */ +export function parseInfoPlistStrings(xml: string): Record { + const result: Record = {}; + const re = /([^<]+)<\/key>\s*([^<]*)<\/string>/g; + let match: RegExpExecArray | null = re.exec(xml); + while (match !== null) { + const key = match[1]; + const value = match[2]; + if (key !== undefined && value !== undefined) { + result[decodeXmlEntities(key.trim())] = decodeXmlEntities(value); + } + match = re.exec(xml); + } + return result; +} + +/** Build an {@link InfoPlist} purely from Xcode build-setting env vars. */ +function fromEnvVars(vars: Env): InfoPlist | null { + const name = vars.PRODUCT_NAME; + const bundleId = vars.PRODUCT_BUNDLE_IDENTIFIER; + const version = vars.MARKETING_VERSION; + const build = vars.CURRENT_PROJECT_VERSION; + if (!(name && bundleId && version && build)) { + return null; + } + return { name, bundleId, version, build }; +} + +/** Whether a parsed plist carries the fields we require. */ +function plistComplete(p: Partial): p is InfoPlist { + return Boolean(p.name && p.bundleId && p.version && p.build); +} + +/** + * Discover the app's bundle identity from the Xcode build environment. + * + * Handles the common case of running inside an Xcode build phase + * (`XCODE_VERSION_ACTUAL` set): reads `INFOPLIST_FILE` (expanding `$(VAR)` + * references from the environment) and falls back to build-setting env vars. + * Returns `null` when the identity cannot be determined. + * + * Not supported (returns `null` / falls back): `INFOPLIST_PREPROCESS` C + * preprocessing, and discovery via `xcodebuild` when run outside Xcode. + */ +export async function discoverInfoPlist( + env: Env, + cwd: string +): Promise { + if (!env.XCODE_VERSION_ACTUAL) { + return null; + } + const filename = env.INFOPLIST_FILE; + if (!filename) { + return fromEnvVars(env); + } + const path = join(cwd, env.PROJECT_DIR ?? ".", filename); + let raw: Record; + try { + raw = parseInfoPlistStrings(await readFile(path, "utf-8")); + } catch { + return fromEnvVars(env); + } + const parsed: Partial = { + name: raw.CFBundleName, + bundleId: raw.CFBundleIdentifier, + version: raw.CFBundleShortVersionString, + build: raw.CFBundleVersion, + }; + if (!plistComplete(parsed)) { + return fromEnvVars(env); + } + return { + name: expandXcodeVars(parsed.name, env), + bundleId: expandXcodeVars(parsed.bundleId, env), + version: expandXcodeVars(parsed.version, env), + build: expandXcodeVars(parsed.build, env), + }; +} + +/** A resolved release + distribution for the sourcemap upload. */ +export type ReleaseAndDist = { + release?: string; + dist?: string; +}; + +/** + * Resolve the release name and distribution to upload under. + * + * Priority mirrors the legacy CLI: `SENTRY_RELEASE`/`SENTRY_DIST` env vars win; + * otherwise the app `Info.plist` yields `release = @+` + * and `dist = `. + * + * @throws When neither env vars nor the Info.plist provide the identity and + * auto-release was not disabled. + */ +export async function resolveReleaseAndDist( + env: Env, + cwd: string, + noAutoRelease: boolean +): Promise { + const distEnv = env.SENTRY_DIST; + const releaseEnv = env.SENTRY_RELEASE; + + if (!(distEnv || releaseEnv) && noAutoRelease) { + return {}; + } + if (distEnv || releaseEnv) { + return { release: releaseEnv, dist: distEnv }; + } + + const plist = await discoverInfoPlist(env, cwd); + if (!plist) { + throw new Error( + "Could not determine release: set SENTRY_RELEASE/SENTRY_DIST, run from " + + "Xcode, or pass --no-auto-release." + ); + } + return { + dist: plist.build, + release: `${plist.bundleId}@${plist.version}+${plist.build}`, + }; +} diff --git a/test/commands/react-native/xcode.test.ts b/test/commands/react-native/xcode.test.ts new file mode 100644 index 0000000000..6e10accd7f --- /dev/null +++ b/test/commands/react-native/xcode.test.ts @@ -0,0 +1,168 @@ +/** + * Tests for `sentry react-native xcode` mode selection. + * + * The build-script spawn, sourcemap upload, org/project resolution, and debug-id + * injection are mocked so the three modes (need-Xcode error, debug passthrough, + * release wrap+upload) can be exercised off-device. + */ + +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { xcodeCommand } from "../../../src/commands/react-native/xcode.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as sourcemaps from "../../../src/lib/api/sourcemaps.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as resolveTarget from "../../../src/lib/resolve-target.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as debugId from "../../../src/lib/sourcemap/debug-id.js"; + +vi.mock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + spawnSync: vi.fn(() => ({ + status: 0, + stdout: "", + stderr: "", + pid: 1, + output: [], + signal: null, + })), + }; +}); + +const spawnMock = vi.mocked(spawnSync); + +let dir: string; +let script: string; + +function createContext(env: NodeJS.ProcessEnv) { + return { + stdout: { write: () => true }, + stderr: { write: () => true }, + cwd: dir, + env, + process: { ...process, execPath: "/usr/bin/sentry", exitCode: undefined }, + } as unknown as Parameters< + Awaited> + >[0]; +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "rn-xcode-")); + script = join(dir, "react-native-xcode.sh"); + writeFileSync(script, "#!/bin/sh\ntrue\n"); + spawnMock.mockClear(); + vi.spyOn(resolveTarget, "resolveOrgAndProject").mockResolvedValue({ + org: "acme", + project: "mobile", + }); + vi.spyOn(debugId, "injectDebugId").mockResolvedValue({ + debugId: "dead-beef", + wasInjected: true, + }); + vi.spyOn(sourcemaps, "uploadSourcemaps").mockResolvedValue(undefined); +}); +afterEach(() => { + vi.restoreAllMocks(); + rmSync(dir, { recursive: true, force: true }); +}); + +async function runXcode(env: NodeJS.ProcessEnv, flags = {}): Promise { + const func = await xcodeCommand.loader(); + await func.call(createContext(env), { "build-script": script, ...flags }); +} + +describe("react-native xcode", () => { + test("errors when not run from Xcode", async () => { + await expect(runXcode({})).rejects.toThrow(/from Xcode/); + }); + + test("debug build just runs the script (no upload)", async () => { + await runXcode({ CONFIGURATION: "Debug" }); + expect(spawnMock).toHaveBeenCalledTimes(1); + expect(spawnMock.mock.calls[0][0]).toBe(script); + expect(sourcemaps.uploadSourcemaps).not.toHaveBeenCalled(); + }); + + test("release build wraps, reads the report, and uploads", async () => { + const bundle = join(dir, "main.jsbundle"); + const map = join(dir, "main.jsbundle.map"); + // The wrapped build "produces" a report pointing at the bundle + sourcemap. + spawnMock.mockImplementation( + ( + _cmd: string, + _args: readonly string[] | undefined, + spawnOpts?: { env?: NodeJS.ProcessEnv } + ) => { + const reportPath = spawnOpts?.env?.SENTRY_RN_SOURCEMAP_REPORT; + if (reportPath) { + writeFileSync( + reportPath, + JSON.stringify({ + packager_bundle_path: bundle, + packager_sourcemap_path: map, + }) + ); + } + return { + status: 0, + stdout: "", + stderr: "", + pid: 1, + output: [], + signal: null, + }; + } + ); + + await runXcode({ + CONFIGURATION: "Release", + SENTRY_RELEASE: "app@1.0.0", + SENTRY_DIST: "42", + }); + + expect(debugId.injectDebugId).toHaveBeenCalledWith(bundle, map); + expect(sourcemaps.uploadSourcemaps).toHaveBeenCalledTimes(1); + const opts = vi.mocked(sourcemaps.uploadSourcemaps).mock + .calls[0][0] as sourcemaps.UploadOptions; + expect(opts).toMatchObject({ + org: "acme", + project: "mobile", + release: "app@1.0.0", + dist: "42", + }); + expect(opts.files.map((f) => f.url)).toEqual([ + "~/main.jsbundle", + "~/main.jsbundle.map", + ]); + }); + + test("warns and skips upload when the build produced no sourcemaps", async () => { + spawnMock.mockImplementation( + ( + _cmd: string, + _args: readonly string[] | undefined, + spawnOpts?: { env?: NodeJS.ProcessEnv } + ) => { + const reportPath = spawnOpts?.env?.SENTRY_RN_SOURCEMAP_REPORT; + if (reportPath) { + writeFileSync(reportPath, "{}"); + } + return { + status: 0, + stdout: "", + stderr: "", + pid: 1, + output: [], + signal: null, + }; + } + ); + await runXcode({ CONFIGURATION: "Release" }); + expect(sourcemaps.uploadSourcemaps).not.toHaveBeenCalled(); + }); +}); diff --git a/test/lib/react-native/wrap-call.test.ts b/test/lib/react-native/wrap-call.test.ts new file mode 100644 index 0000000000..4ef6ef98eb --- /dev/null +++ b/test/lib/react-native/wrap-call.test.ts @@ -0,0 +1,130 @@ +/** + * Tests for the React Native Xcode build wrapper (`wrap_call`). + * + * The wrapped Node/Hermes spawn is mocked; the tests assert argument parsing, + * the JSON report contents, and the Hermes debug-id copy. + */ + +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import type { SourceMapReport } from "../../../src/lib/react-native/wrap-call.js"; +import { wrapCall } from "../../../src/lib/react-native/wrap-call.js"; + +vi.mock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + spawnSync: vi.fn(() => ({ + status: 0, + stdout: "", + stderr: "", + pid: 1, + output: [], + signal: null, + })), + }; +}); + +const spawnMock = vi.mocked(spawnSync); + +let dir: string; +let reportPath: string; +const origArgv = process.argv; + +/** Simulate the RN build script invoking us with these args (non-SEA layout). */ +function setArgs(args: string[]): void { + process.argv = ["node", "bin.js", ...args]; +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "rn-wrap-")); + reportPath = join(dir, "report.json"); + spawnMock.mockClear(); +}); +afterEach(() => { + process.argv = origArgv; + rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); +}); + +function readReport(): SourceMapReport { + return JSON.parse(readFileSync(reportPath, "utf-8")) as SourceMapReport; +} + +describe("wrapCall", () => { + test("parses a bundle command and adds a --sourcemap-output", () => { + setArgs(["cli.js", "bundle", "--bundle-output", "/build/app.jsbundle"]); + const status = wrapCall({ + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + SENTRY_RN_REAL_NODE_BINARY: "node", + }); + + expect(status).toBe(0); + const report = readReport(); + expect(report.packager_bundle_path).toBe("/build/app.jsbundle"); + expect(report.packager_sourcemap_path).toContain("app.jsbundle.map"); + // The real node was invoked with the injected --sourcemap-output. + const [exe, args] = spawnMock.mock.calls[0]; + expect(exe).toBe("node"); + expect(args).toContain("--sourcemap-output"); + }); + + test("records the Hermes bundle path from -emit-binary", () => { + setArgs(["-emit-binary", "-out", "/build/app.hbc", "/build/app.js"]); + wrapCall({ + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + SENTRY_RN_REAL_NODE_BINARY: "node", + SENTRY_RN_REAL_HERMES_CLI_PATH: "/hermesc", + }); + expect(spawnMock.mock.calls[0][0]).toBe("/hermesc"); + expect(readReport().hermes_bundle_path).toBe("/build/app.hbc"); + }); + + test("copies the debug id into the Hermes combined sourcemap", () => { + const pkgMap = join(dir, "packager.map"); + const hermesMap = join(dir, "hermes.map"); + writeFileSync(pkgMap, JSON.stringify({ version: 3, debugId: "abc-123" })); + writeFileSync(hermesMap, JSON.stringify({ version: 3 })); + // Seed the report with the packager sourcemap path (from a prior bundle call). + writeFileSync( + reportPath, + JSON.stringify({ packager_sourcemap_path: pkgMap }) + ); + + setArgs(["/tools/compose-source-maps.js", "-o", hermesMap]); + wrapCall({ + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + SENTRY_RN_REAL_NODE_BINARY: "node", + }); + + const hermes = JSON.parse(readFileSync(hermesMap, "utf-8")); + expect(hermes.debugId).toBe("abc-123"); + expect(hermes.debug_id).toBe("abc-123"); + expect(readReport().hermes_sourcemap_path).toBe(hermesMap); + }); + + test("respects SENTRY_RN_NO_DEBUG_ID", () => { + const pkgMap = join(dir, "packager.map"); + const hermesMap = join(dir, "hermes.map"); + writeFileSync(pkgMap, JSON.stringify({ debugId: "abc-123" })); + writeFileSync(hermesMap, JSON.stringify({ version: 3 })); + writeFileSync( + reportPath, + JSON.stringify({ packager_sourcemap_path: pkgMap }) + ); + + setArgs(["/tools/compose-source-maps.js", "-o", hermesMap]); + wrapCall({ + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + SENTRY_RN_REAL_NODE_BINARY: "node", + SENTRY_RN_NO_DEBUG_ID: "1", + }); + + expect( + JSON.parse(readFileSync(hermesMap, "utf-8")).debugId + ).toBeUndefined(); + }); +}); diff --git a/test/lib/react-native/xcode-env.test.ts b/test/lib/react-native/xcode-env.test.ts new file mode 100644 index 0000000000..4b48e9ea5f --- /dev/null +++ b/test/lib/react-native/xcode-env.test.ts @@ -0,0 +1,156 @@ +/** + * Tests for Xcode build-environment helpers. + */ + +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { + discoverInfoPlist, + expandXcodeVars, + findHermesc, + findNode, + parseInfoPlistStrings, + resolveReleaseAndDist, +} from "../../../src/lib/react-native/xcode-env.js"; + +const dirs: string[] = []; +afterEach(() => { + while (dirs.length > 0) { + const d = dirs.pop(); + if (d) { + rmSync(d, { recursive: true, force: true }); + } + } +}); + +describe("findNode / findHermesc", () => { + test("prefer env overrides", () => { + expect(findNode({ NODE_BINARY: "/usr/bin/node" })).toBe("/usr/bin/node"); + expect(findNode({})).toBe("node"); + expect(findHermesc({ HERMES_CLI_PATH: "/h" })).toBe("/h"); + expect(findHermesc({ PODS_ROOT: "/pods" })).toBe( + "/pods/hermes-engine/destroot/bin/hermesc" + ); + }); +}); + +describe("expandXcodeVars", () => { + test("expands parenthesized and braced references", () => { + const vars = { FOO: "hello world" }; + expect(expandXcodeVars("A$(FOO)B", vars)).toBe("Ahello worldB"); + // biome-ignore lint/suspicious/noTemplateCurlyInString: literal Xcode ${VAR} syntax under test + expect(expandXcodeVars("A${FOO}B", vars)).toBe("Ahello worldB"); + expect(expandXcodeVars("$(MISSING)", vars)).toBe(""); + }); + + test("applies rfc1034identifier and identifier modifiers", () => { + const vars = { FOO_BAR: "a b/c" }; + expect(expandXcodeVars("$(FOO_BAR:rfc1034identifier)", vars)).toBe("a-b-c"); + expect(expandXcodeVars("$(FOO_BAR:identifier)", vars)).toBe("a_b_c"); + }); +}); + +describe("parseInfoPlistStrings", () => { + test("extracts key/string pairs and decodes entities", () => { + const xml = ` + + CFBundleIdentifiercom.example.app + CFBundleShortVersionString + 1.2.3 + CFBundleNameA & B +`; + const parsed = parseInfoPlistStrings(xml); + expect(parsed.CFBundleIdentifier).toBe("com.example.app"); + expect(parsed.CFBundleShortVersionString).toBe("1.2.3"); + expect(parsed.CFBundleName).toBe("A & B"); + }); +}); + +describe("discoverInfoPlist", () => { + test("returns null when not running inside Xcode", async () => { + expect(await discoverInfoPlist({}, "/tmp")).toBeNull(); + }); + + test("reads and expands the Info.plist file", async () => { + const dir = mkdtempSync(join(tmpdir(), "rn-plist-")); + dirs.push(dir); + writeFileSync( + join(dir, "Info.plist"), + ` + CFBundleNameMyApp + CFBundleIdentifiercom.example.$(SUFFIX) + CFBundleShortVersionString2.0.0 + CFBundleVersion42 + ` + ); + const plist = await discoverInfoPlist( + { + XCODE_VERSION_ACTUAL: "1500", + INFOPLIST_FILE: "Info.plist", + SUFFIX: "app", + }, + dir + ); + expect(plist).toEqual({ + name: "MyApp", + bundleId: "com.example.app", + version: "2.0.0", + build: "42", + }); + }); + + test("falls back to build-setting env vars", async () => { + const plist = await discoverInfoPlist( + { + XCODE_VERSION_ACTUAL: "1500", + PRODUCT_NAME: "MyApp", + PRODUCT_BUNDLE_IDENTIFIER: "com.example.app", + MARKETING_VERSION: "1.0.0", + CURRENT_PROJECT_VERSION: "7", + }, + "/tmp" + ); + expect(plist).toMatchObject({ bundleId: "com.example.app", build: "7" }); + }); +}); + +describe("resolveReleaseAndDist", () => { + test("prefers SENTRY_RELEASE/SENTRY_DIST env vars", async () => { + const result = await resolveReleaseAndDist( + { SENTRY_RELEASE: "app@1.0", SENTRY_DIST: "100" }, + "/tmp", + false + ); + expect(result).toEqual({ release: "app@1.0", dist: "100" }); + }); + + test("returns empty when no-auto-release and no env vars", async () => { + expect(await resolveReleaseAndDist({}, "/tmp", true)).toEqual({}); + }); + + test("derives release from Info.plist", async () => { + const result = await resolveReleaseAndDist( + { + XCODE_VERSION_ACTUAL: "1500", + PRODUCT_NAME: "MyApp", + PRODUCT_BUNDLE_IDENTIFIER: "com.example.app", + MARKETING_VERSION: "3.1.0", + CURRENT_PROJECT_VERSION: "55", + }, + "/tmp", + false + ); + expect(result).toEqual({ + dist: "55", + release: "com.example.app@3.1.0+55", + }); + }); + + test("throws when the identity cannot be determined", async () => { + await expect(resolveReleaseAndDist({}, "/tmp", false)).rejects.toThrow( + /Could not determine release/ + ); + }); +}); From df1d6b3be3f5f78ec888359e88f9b21e2e9411bf Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 13:41:19 +0000 Subject: [PATCH 2/3] fix(react-native): xcode review fixes (bytecode, exit codes, fetch) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Cursor (High): do NOT re-inject a debug id into the xcode bundle — a release build's bundle may be Hermes bytecode, which a JS snippet corrupts. Read the existing debug id from the sourcemap (put there by the Metro/Sentry plugin and copied into the Hermes sourcemap by the wrapper) instead. - Cursor (Medium): a failed wrapped build no longer publishes artifacts (matches the legacy CLI's exit-on-nonzero before upload). - Cursor (Medium): packager fetch now checks HTTP status; a 404/500 body is not saved + uploaded. - Warden: a signal-killed wrapped process now reports a non-zero status (was 0) in both wrap-call and the build-script runner. Tests: sourcemap-derived debug id (bundle never mutated), no-upload on build failure, signal-kill status. Extracted preparePair/classifyInvocation helpers to stay under the complexity limit. --- src/commands/react-native/xcode.ts | 133 ++++++++++++++++++----- src/lib/react-native/wrap-call.ts | 60 ++++++---- test/commands/react-native/xcode.test.ts | 25 +++-- test/lib/react-native/wrap-call.test.ts | 18 +++ 4 files changed, 184 insertions(+), 52 deletions(-) diff --git a/src/commands/react-native/xcode.ts b/src/commands/react-native/xcode.ts index 1b82367525..70f22a0926 100644 --- a/src/commands/react-native/xcode.ts +++ b/src/commands/react-native/xcode.ts @@ -16,6 +16,7 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { readFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; @@ -34,7 +35,6 @@ import { resolveReleaseAndDist, } from "../../lib/react-native/xcode-env.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; -import { injectDebugId } from "../../lib/sourcemap/debug-id.js"; const log = logger.withTag("react-native.xcode"); @@ -126,7 +126,8 @@ function runScript( env: NodeJS.ProcessEnv ): number { const rv = spawnSync(script, args, { stdio: "inherit", env }); - return rv.status ?? (rv.error ? 1 : 0); + // A signal-killed child has `status === null`; treat that as a failure. + return rv.status ?? (rv.signal !== null || rv.error ? 1 : 0); } /** Poll a URL until it responds or the timeout elapses. */ @@ -166,8 +167,20 @@ async function fetchFromPackager( const bundleRes = await fetch( `${url}/index.ios.bundle?platform=ios&dev=true` ); + if (!bundleRes.ok) { + throw new ValidationError( + `Packager returned ${bundleRes.status} for the bundle.`, + "fetch-from" + ); + } writeFileSync(bundle, Buffer.from(await bundleRes.arrayBuffer())); const mapRes = await fetch(`${url}/index.ios.map?platform=ios&dev=true`); + if (!mapRes.ok) { + throw new ValidationError( + `Packager returned ${mapRes.status} for the sourcemap.`, + "fetch-from" + ); + } writeFileSync(sourcemap, Buffer.from(await mapRes.arrayBuffer())); return { bundle, sourcemap }; } @@ -226,13 +239,29 @@ function runWrappedBuild( }; } -/** Inject a debug id and upload the bundle/sourcemap pair. */ +/** Read the debug id already present in a sourcemap (from the Metro plugin). */ +async function readSourcemapDebugId( + mapPath: string +): Promise { + try { + const map = JSON.parse(await readFile(mapPath, "utf-8")) as { + debugId?: string; + debug_id?: string; + }; + return map.debugId ?? map.debug_id; + } catch (err) { + log.debug("Could not read debug id from sourcemap", err); + return; + } +} + +/** Upload the bundle/sourcemap pair using the sourcemap's existing debug id. */ async function uploadPair( pair: BundlePair, ctx: SentryContext, flags: XcodeFlags ): Promise<{ - debugId: string; + debugId?: string; release?: string; dist: string[]; uploads: number; @@ -246,18 +275,29 @@ async function uploadPair( } const { org, project } = resolved; - const { debugId } = await injectDebugId(pair.bundle, pair.sourcemap); + // The RN Metro/Sentry plugin injects the debug id into the bundle + sourcemap + // at build time, and the wrapper copies it into the Hermes sourcemap. We must + // NOT re-inject: a release bundle may be Hermes bytecode, which a JS snippet + // would corrupt. Read the existing debug id from the sourcemap instead. + const debugId = await readSourcemapDebugId(pair.sourcemap); + if (!debugId) { + log.warn( + "No debug id found in the sourcemap; uploading without one. Ensure the " + + "Sentry React Native Metro plugin is configured." + ); + } + const debugIdField = debugId ? { debugId } : {}; const files: ArtifactFile[] = [ { path: pair.bundle, - debugId, + ...debugIdField, type: "minified_source", url: `~/${basename(pair.bundle)}`, sourcemapFilename: basename(pair.sourcemap), }, { path: pair.sourcemap, - debugId, + ...debugIdField, type: "source_map", url: `~/${basename(pair.sourcemap)}`, }, @@ -289,6 +329,54 @@ async function uploadPair( return { debugId, release, dist: dists, uploads }; } +/** Either a resolved pair to upload, or a terminal (no-upload) outcome. */ +type PrepareResult = + | { + kind: "terminal"; + result: XcodeResult; + hint: string; + exitCode?: number; + } + | { kind: "pair"; mode: "fetch" | "wrap"; pair: BundlePair }; + +/** Resolve the bundle/sourcemap pair via the packager (fetch) or a wrapped build. */ +async function preparePair( + ctx: SentryContext, + script: string, + scriptArgs: string[], + fetchUrl: string | undefined +): Promise { + const tempDir = mkdtempSync(join(tmpdir(), "sentry-rn-xcode-")); + if (fetchUrl) { + log.info(`Fetching sourcemaps from ${fetchUrl}`); + return { + kind: "pair", + mode: "fetch", + pair: await fetchFromPackager(fetchUrl, tempDir), + }; + } + const result = runWrappedBuild(script, scriptArgs, ctx, tempDir); + // A failed build must not publish artifacts (matches the legacy CLI, which + // exits on a non-zero build status before uploading). + if (result.status !== 0) { + return { + kind: "terminal", + result: { mode: "wrap", uploads: 0 }, + hint: "React Native build failed; skipped upload.", + exitCode: result.status, + }; + } + if (!result.pair) { + log.warn("Build produced no packager sourcemaps."); + return { + kind: "terminal", + result: { mode: "wrap", uploads: 0 }, + hint: "No sourcemaps were produced by the build.", + }; + } + return { kind: "pair", mode: "wrap", pair: result.pair }; +} + export const xcodeCommand = buildCommand({ docs: { brief: "Upload React Native sourcemaps (Xcode build step)", @@ -386,28 +474,17 @@ export const xcodeCommand = buildCommand({ return { hint: "Ran the React Native build script (debug mode)." }; } - const tempDir = mkdtempSync(join(tmpdir(), "sentry-rn-xcode-")); - let mode: "fetch" | "wrap"; - let pair: BundlePair | null; - if (fetchUrl) { - mode = "fetch"; - log.info(`Fetching sourcemaps from ${fetchUrl}`); - pair = await fetchFromPackager(fetchUrl, tempDir); - } else { - mode = "wrap"; - const result = runWrappedBuild(script, scriptArgs, this, tempDir); - if (result.status !== 0) { - this.process.exitCode = result.status; - } - pair = result.pair; - if (!pair) { - log.warn("Build produced no packager sourcemaps."); - yield new CommandOutput({ mode, uploads: 0 }); - return { hint: "No sourcemaps were produced by the build." }; + const prep = await preparePair(this, script, scriptArgs, fetchUrl); + if (prep.kind === "terminal") { + if (prep.exitCode !== undefined) { + this.process.exitCode = prep.exitCode; } + yield new CommandOutput(prep.result); + return { hint: prep.hint }; } log.info("Processing React Native sourcemaps for Sentry upload."); + const { pair, mode } = prep; const { debugId, release, dist, uploads } = await uploadPair( pair, this, @@ -423,6 +500,10 @@ export const xcodeCommand = buildCommand({ dist: dist.length > 0 ? dist : undefined, uploads, }); - return { hint: `Uploaded sourcemaps with debug ID ${debugId}.` }; + return { + hint: debugId + ? `Uploaded sourcemaps with debug ID ${debugId}.` + : "Uploaded sourcemaps.", + }; }, }); diff --git a/src/lib/react-native/wrap-call.ts b/src/lib/react-native/wrap-call.ts index 0c383cf0fa..7921b4d44a 100644 --- a/src/lib/react-native/wrap-call.ts +++ b/src/lib/react-native/wrap-call.ts @@ -143,6 +143,40 @@ function copyDebugId(report: SourceMapReport): void { * * @returns The exit code of the wrapped process. */ +/** Whether the invocation is the Hermes combine-source-maps script. */ +function isComposeCommand(args: string[], env: NodeJS.ProcessEnv): boolean { + const first = args[0]; + if (first === undefined || args.length <= 1) { + return false; + } + return ( + first.endsWith("compose-source-maps.js") || + (Boolean(env.COMPOSE_SOURCEMAP_PATH) && + first === env.COMPOSE_SOURCEMAP_PATH) + ); +} + +/** Classify the wrapped invocation, recording paths into `report`. */ +function classifyInvocation( + args: string[], + env: NodeJS.ProcessEnv, + report: SourceMapReport +): { executeHermes: boolean; shouldCopyDebugId: boolean } { + if (isBundleCommand(args, env.SENTRY_RN_BUNDLE_COMMAND)) { + handleBundle(args, report); + return { executeHermes: false, shouldCopyDebugId: false }; + } + if (args.length > 1 && args[0] === "-emit-binary") { + report.hermes_bundle_path = extractArg(args, "-out"); + return { executeHermes: true, shouldCopyDebugId: false }; + } + if (isComposeCommand(args, env)) { + report.hermes_sourcemap_path = extractArg(args, "-o"); + return { executeHermes: false, shouldCopyDebugId: true }; + } + return { executeHermes: false, shouldCopyDebugId: false }; +} + export function wrapCall(env: NodeJS.ProcessEnv = process.env): number { const reportPath = env.SENTRY_RN_SOURCEMAP_REPORT; if (!reportPath) { @@ -152,24 +186,11 @@ export function wrapCall(env: NodeJS.ProcessEnv = process.env): number { const args = getWrapArgs(); const noDebugId = env.SENTRY_RN_NO_DEBUG_ID === "1"; - let executeHermes = false; - let shouldCopyDebugId = false; - - const first = args[0]; - const isCompose = - first !== undefined && - (first.endsWith("compose-source-maps.js") || - (Boolean(env.COMPOSE_SOURCEMAP_PATH) && - first === env.COMPOSE_SOURCEMAP_PATH)); - if (isBundleCommand(args, env.SENTRY_RN_BUNDLE_COMMAND)) { - handleBundle(args, report); - } else if (args.length > 1 && first === "-emit-binary") { - executeHermes = true; - report.hermes_bundle_path = extractArg(args, "-out"); - } else if (args.length > 1 && isCompose) { - report.hermes_sourcemap_path = extractArg(args, "-o"); - shouldCopyDebugId = true; - } + const { executeHermes, shouldCopyDebugId } = classifyInvocation( + args, + env, + report + ); const executable = executeHermes ? env.SENTRY_RN_REAL_HERMES_CLI_PATH @@ -181,7 +202,8 @@ export function wrapCall(env: NodeJS.ProcessEnv = process.env): number { } const rv = spawnSync(executable, args, { stdio: "inherit" }); - const status = rv.status ?? (rv.error ? 1 : 0); + // A signal-killed child has `status === null`; treat that as a failure. + const status = rv.status ?? (rv.signal !== null || rv.error ? 1 : 0); if (!noDebugId && shouldCopyDebugId) { copyDebugId(report); diff --git a/test/commands/react-native/xcode.test.ts b/test/commands/react-native/xcode.test.ts index 6e10accd7f..1b6c73d677 100644 --- a/test/commands/react-native/xcode.test.ts +++ b/test/commands/react-native/xcode.test.ts @@ -16,8 +16,6 @@ import { xcodeCommand } from "../../../src/commands/react-native/xcode.js"; import * as sourcemaps from "../../../src/lib/api/sourcemaps.js"; // biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking import * as resolveTarget from "../../../src/lib/resolve-target.js"; -// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking -import * as debugId from "../../../src/lib/sourcemap/debug-id.js"; vi.mock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); @@ -60,10 +58,6 @@ beforeEach(() => { org: "acme", project: "mobile", }); - vi.spyOn(debugId, "injectDebugId").mockResolvedValue({ - debugId: "dead-beef", - wasInjected: true, - }); vi.spyOn(sourcemaps, "uploadSourcemaps").mockResolvedValue(undefined); }); afterEach(() => { @@ -119,13 +113,15 @@ describe("react-native xcode", () => { } ); + // The sourcemap already carries a debug id (from the Metro plugin). + writeFileSync(map, JSON.stringify({ version: 3, debugId: "dead-beef" })); + await runXcode({ CONFIGURATION: "Release", SENTRY_RELEASE: "app@1.0.0", SENTRY_DIST: "42", }); - expect(debugId.injectDebugId).toHaveBeenCalledWith(bundle, map); expect(sourcemaps.uploadSourcemaps).toHaveBeenCalledTimes(1); const opts = vi.mocked(sourcemaps.uploadSourcemaps).mock .calls[0][0] as sourcemaps.UploadOptions; @@ -139,6 +135,21 @@ describe("react-native xcode", () => { "~/main.jsbundle", "~/main.jsbundle.map", ]); + // The debug id comes from the sourcemap — the bundle is never mutated. + expect(opts.files.every((f) => f.debugId === "dead-beef")).toBe(true); + }); + + test("does not upload when the wrapped build fails", async () => { + spawnMock.mockReturnValue({ + status: 1, + stdout: "", + stderr: "", + pid: 1, + output: [], + signal: null, + }); + await runXcode({ CONFIGURATION: "Release" }); + expect(sourcemaps.uploadSourcemaps).not.toHaveBeenCalled(); }); test("warns and skips upload when the build produced no sourcemaps", async () => { diff --git a/test/lib/react-native/wrap-call.test.ts b/test/lib/react-native/wrap-call.test.ts index 4ef6ef98eb..fe2eb95b22 100644 --- a/test/lib/react-native/wrap-call.test.ts +++ b/test/lib/react-native/wrap-call.test.ts @@ -106,6 +106,24 @@ describe("wrapCall", () => { expect(readReport().hermes_sourcemap_path).toBe(hermesMap); }); + test("reports a non-zero status when the child is killed by a signal", () => { + spawnMock.mockReturnValueOnce({ + status: null, + signal: "SIGTERM", + stdout: "", + stderr: "", + pid: 1, + output: [], + // biome-ignore lint/suspicious/noExplicitAny: partial SpawnSyncReturns for the test + } as any); + setArgs(["cli.js", "bundle", "--bundle-output", "/build/app.jsbundle"]); + const status = wrapCall({ + SENTRY_RN_SOURCEMAP_REPORT: reportPath, + SENTRY_RN_REAL_NODE_BINARY: "node", + }); + expect(status).not.toBe(0); + }); + test("respects SENTRY_RN_NO_DEBUG_ID", () => { const pkgMap = join(dir, "packager.map"); const hermesMap = join(dir, "hermes.map"); From c174d105bb186a840bfc30cc9715ec2326bdf441 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 14:25:15 +0000 Subject: [PATCH 3/3] fix(react-native): re-invoke the CLI correctly under npm (xcode wrap) Cursor (High): in wrap mode, NODE_BINARY/HERMES_CLI_PATH were set to process.execPath. That's the CLI only for the SEA binary; under an npm install execPath is Node, so RN would run plain node (never re-entering the wrapper) and HERMES_CLI_PATH=node would break Hermes. Fix: SEA still uses execPath directly; npm generates a small shim (`exec "" "" "$@"`) so `$NODE_BINARY ` re-enters the CLI with __SENTRY_RN_WRAP_XCODE_CALL. Exported isSea() from wrap-call for detection. Test asserts NODE_BINARY points at the shim in a non-SEA run. --- src/commands/react-native/xcode.ts | 28 ++++++++++++++++++++++-- src/lib/react-native/wrap-call.ts | 2 +- test/commands/react-native/xcode.test.ts | 6 +++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/commands/react-native/xcode.ts b/src/commands/react-native/xcode.ts index 70f22a0926..fc3be0f77c 100644 --- a/src/commands/react-native/xcode.ts +++ b/src/commands/react-native/xcode.ts @@ -28,7 +28,10 @@ import { ContextError, ValidationError } from "../../lib/errors.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { logger } from "../../lib/logger.js"; -import type { SourceMapReport } from "../../lib/react-native/wrap-call.js"; +import { + isSea, + type SourceMapReport, +} from "../../lib/react-native/wrap-call.js"; import { findHermesc, findNode, @@ -185,6 +188,27 @@ async function fetchFromPackager( return { bundle, sourcemap }; } +/** + * Resolve the command RN should invoke in place of `NODE_BINARY`/`HERMES_CLI_PATH`. + * + * A SEA binary's `process.execPath` is the CLI itself. Under an npm install + * `process.execPath` is Node and `argv[1]` is the CLI script, so RN's + * `$NODE_BINARY ` would run plain Node and never re-enter the wrapper; + * generate a small shim that re-invokes the CLI instead. (macOS/Xcode only.) + */ +function resolveSelfInvocation(ctx: SentryContext, tempDir: string): string { + const execPath = ctx.process.execPath; + if (isSea()) { + return execPath; + } + const script = ctx.process.argv[1] ?? ""; + const shim = join(tempDir, "sentry-rn-node.sh"); + writeFileSync(shim, `#!/bin/sh\nexec "${execPath}" "${script}" "$@"\n`, { + mode: 0o755, + }); + return shim; +} + /** Run the wrapped build and read the produced bundle/sourcemap paths. */ function runWrappedBuild( script: string, @@ -196,7 +220,7 @@ function runWrappedBuild( writeFileSync(reportPath, "{}"); const node = findNode(ctx.env); const hermesc = findHermesc(ctx.env); - const self = ctx.process.execPath; + const self = resolveSelfInvocation(ctx, tempDir); const env: NodeJS.ProcessEnv = { ...ctx.env, diff --git a/src/lib/react-native/wrap-call.ts b/src/lib/react-native/wrap-call.ts index 7921b4d44a..270fbf60a6 100644 --- a/src/lib/react-native/wrap-call.ts +++ b/src/lib/react-native/wrap-call.ts @@ -29,7 +29,7 @@ export type SourceMapReport = { }; /** Whether this process is a Node Single Executable Application. */ -function isSea(): boolean { +export function isSea(): boolean { try { const req = createRequire(import.meta.url); const sea = req("node:sea") as { isSea?: () => boolean }; diff --git a/test/commands/react-native/xcode.test.ts b/test/commands/react-native/xcode.test.ts index 1b6c73d677..9937e859dd 100644 --- a/test/commands/react-native/xcode.test.ts +++ b/test/commands/react-native/xcode.test.ts @@ -122,6 +122,12 @@ describe("react-native xcode", () => { SENTRY_DIST: "42", }); + // Non-SEA (npm) run: NODE_BINARY must re-invoke the CLI via a shim, not + // plain node, so RN re-enters the wrapper. + const wrapEnv = spawnMock.mock.calls[0][2]?.env; + expect(wrapEnv?.NODE_BINARY).toMatch(/sentry-rn-node\.sh$/); + expect(wrapEnv?.__SENTRY_RN_WRAP_XCODE_CALL).toBe("1"); + expect(sourcemaps.uploadSourcemaps).toHaveBeenCalledTimes(1); const opts = vi.mocked(sourcemaps.uploadSourcemaps).mock .calls[0][0] as sourcemaps.UploadOptions;