diff --git a/packages/cli/package.json b/packages/cli/package.json index e9aaa2f66..8f256c11d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -154,6 +154,7 @@ "valibot": "^1.4.2", "vitest": "catalog:", "wrap-ansi": "^10.0.0", + "xcode": "3.0.1", "yauzl": "3.4.0" } } diff --git a/packages/cli/script/tsconfig.json b/packages/cli/script/tsconfig.json index cbfaca819..5af9a34c8 100644 --- a/packages/cli/script/tsconfig.json +++ b/packages/cli/script/tsconfig.json @@ -3,6 +3,7 @@ "include": [ "**/*.ts", "../src/global.d.ts", + "../src/lib/wizard/xcode.d.ts", "../grammar/**/*.ts", "../vitest.config.ts" ] diff --git a/packages/cli/src/lib/wizard/apple/apple-wizard.ts b/packages/cli/src/lib/wizard/apple/apple-wizard.ts new file mode 100644 index 000000000..327f8118d --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/apple-wizard.ts @@ -0,0 +1,132 @@ +/** + * The iOS wizard (`sentry wizard ios`): adds the Sentry Cocoa SDK through + * Swift Package Manager, a debug-symbol upload build phase, the SDK init + * snippet, and an optional Fastlane upload step to an Xcode project. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; + +import { withTelemetry } from "../telemetry.js"; +import { + confirmContinueIfNoOrDirtyGitRepo, + featureSelectionPrompt, + getOrAskForProjectData, + printWelcome, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { Sentry } from "../telemetry.js"; + +import { checkInstalledCLI } from "./check-installed-cli.js"; +import { configureFastlane } from "./configure-fastlane.js"; +import { configureSentryCLI } from "./configure-sentry-cli.js"; +import { configureXcodeProject } from "./configure-xcode-project.js"; +import { injectCodeSnippet } from "./inject-code-snippet.js"; +import { + lookupXcodeProject, + selectXcodeTarget, +} from "./lookup-xcode-project.js"; +import { type AppleWizardOptions } from "./options.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; + +export async function runAppleWizard( + options: AppleWizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "ios", + wizardOptions: options, + }, + () => runAppleWizardWithTelementry(options), + ); +} + +async function runAppleWizardWithTelementry( + options: AppleWizardOptions, +): Promise { + // Define options with defaults + const projectDir = options.projectDir ?? process.cwd(); + + // Step - Welcome Message + printWelcome({ + wizardName: "Sentry Apple Wizard", + }); + + // Step - Git Status Check + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: projectDir, + }); + + // Step - Sentry CLI Check + checkInstalledCLI(); + + // Step - Xcode Project Lookup + // This step should be run before the Sentry Project and API Key step + // because it can abort the wizard if no Xcode project is found. + const xcProject = await lookupXcodeProject({ projectDir }); + const target = await selectXcodeTarget(xcProject); + + // Step - Sentry Project and API Key + const projectData = await getOrAskForProjectData(options, "apple-ios"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Apple/iOS"); + } + + const { selectedProject, authToken } = projectData; + + // Step - Sentry CLI Configuration Setup + configureSentryCLI({ + projectDir, + authToken: authToken, + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + }); + + Sentry.setTag("package-manager", "SPM"); + + // Step - Configure Xcode Project + configureXcodeProject({ + xcProject, + project: selectedProject, + target, + }); + + // Step - Feature Selection + const selectedFeatures = await featureSelectionPrompt([ + { + id: "logs", + prompt: `Do you want to enable ${chalk.bold( + "Logs", + )} to send your application logs to Sentry?`, + enabledHint: "optional", + }, + ]); + + // Step - Add Code Snippet + injectCodeSnippet({ + project: xcProject, + target, + dsn: selectedProject.keys[0].dsn.public, + enableLogs: selectedFeatures["logs"] ?? false, + }); + + // Step - Fastlane Configuration + await configureFastlane({ + projectDir, + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.log.success( + "Sentry was successfully added to your project! Run your project to send your first event to Sentry. Go to Sentry.io to see whether everything is working fine.", + ); +} diff --git a/packages/cli/src/lib/wizard/apple/check-installed-cli.ts b/packages/cli/src/lib/wizard/apple/check-installed-cli.ts new file mode 100644 index 000000000..3caed5630 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/check-installed-cli.ts @@ -0,0 +1,92 @@ +/** + * Check that the debug-file upload build phase can find `sentry`. + * + * The user runs the wizard through `sentry`, so the CLI is installed, but an + * Xcode build phase doesn't see the user's shell `PATH`: it searches the + * system directories plus the ones the generated script adds (see + * {@link xcodeSearchDirs}). Without `sentry` there, the build phase runs it + * with `npx`, so the wizard only notes that builds would be faster with the + * CLI installed. With neither, it warns and prints how to install it where + * Xcode finds it. + */ + +import { homedir } from "node:os"; +import path from "node:path"; + +import { whichSync } from "../../which.js"; +import { Sentry } from "../telemetry.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; + +/** + * The directories a Sentry build phase searches for `sentry`: the + * standalone installer's (`~/.local/bin`, `~/bin`), Homebrew's, and the + * system ones in Xcode's default `PATH`. + */ +export function xcodeSearchDirs(home: string = homedir()): string[] { + return [ + path.join(home, ".local", "bin"), + path.join(home, "bin"), + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + "/bin", + ]; +} + +/** Commands that install the Sentry CLI where an Xcode build phase finds it. */ +const SENTRY_CLI_INSTALL_COMMANDS = [ + " brew install getsentry/tools/sentry", + " curl https://cli.sentry.dev/install -fsS | bash", + " npm install -g sentry", +]; + +/** Default warning when `sentry` is out of the build phase's reach. */ +const DEFAULT_WARNING = + "Xcode build phases can't find the `sentry` CLI, so your builds won't upload debug symbols to Sentry."; + +/** + * Whether an Xcode build phase finds `sentry`, or `npx` to run it with, + * warning with install instructions when it finds neither. + * + * @param warning - Explains what doesn't work without `sentry`. + * @returns The path of the `sentry` or `npx` the build phase would run, if any. + */ +export function checkInstalledCLI( + warning: string = DEFAULT_WARNING, +): string | undefined { + debug("Checking whether Xcode build phases can find sentry"); + const searchDirs = xcodeSearchDirs(); + const searchPath = { PATH: searchDirs.join(path.delimiter) }; + const cliPath = whichSync("sentry", searchPath) ?? undefined; + Sentry.setTag("has-cli", cliPath !== undefined); + if (cliPath) { + debug(`Xcode build phases will run ${cliPath}`); + return cliPath; + } + + const npxPath = whichSync("npx", searchPath) ?? undefined; + if (npxPath) { + debug(`Xcode build phases will run the Sentry CLI with ${npxPath}`); + clack.log.info( + [ + "Xcode build phases will run the Sentry CLI with `npx sentry`, which downloads it on the first build.", + "For faster builds, install it with one of:", + ...SENTRY_CLI_INSTALL_COMMANDS, + ].join("\n"), + ); + return npxPath; + } + + clack.log.warn( + [ + warning, + "Xcode doesn't use your shell's PATH: it looks in", + `${searchDirs.join(", ")}.`, + "", + "Install the Sentry CLI with one of:", + ...SENTRY_CLI_INSTALL_COMMANDS, + ].join("\n"), + ); + return undefined; +} diff --git a/packages/cli/src/lib/wizard/apple/code-tools.ts b/packages/cli/src/lib/wizard/apple/code-tools.ts new file mode 100644 index 000000000..24c4b0e11 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/code-tools.ts @@ -0,0 +1,184 @@ +/** + * Insert the Sentry SDK init snippet into a Swift or Objective-C app's entry + * point (the `@main` App, AppDelegate, or `main`). + */ + +import { Sentry } from "../telemetry.js"; +import { + existsSync, + lstatSync, + readFileSync, + readdirSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; +import { getObjcSnippet, getSwiftSnippet } from "./templates.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; + +const swiftAppLaunchRegex = + /(func\s+application\s*\(\s*_\s+application:\s*[^,]+,\s*didFinishLaunchingWithOptions[^,]+:\s*[^)]+\s*\)\s+->\s+Bool\s+{)|func\s+applicationDidFinishLaunching\s*\(\s*_\s+aNotification:\s+Notification\s*\)\s*{/im; +const objcAppLaunchRegex = + /-\s*\(\s*BOOL\s*\)\s*application:\s*\(\s*UIApplication\s*\*\s*\)\s*application\s+didFinishLaunchingWithOptions:\s*\(\s*NSDictionary\s*\*\s*\)\s*launchOptions\s*{/im; +const swiftUIRegex = /@main\s+struct[^:]+:\s*(SwiftUI\.)?App\s*{/im; +const swiftUIInitRegex = /\binit\s*\(\s*\)\s*\{/m; + +function isAppDelegateFile(filePath: string): boolean { + debug("Checking if " + filePath + " is an AppDelegate file"); + const appLaunchRegex = filePath.toLowerCase().endsWith(".swift") + ? swiftAppLaunchRegex + : objcAppLaunchRegex; + + const fileContent = readFileSync(filePath, "utf8"); + return appLaunchRegex.test(fileContent) || swiftUIRegex.test(fileContent); +} + +function findAppDidFinishLaunchingWithOptionsInDirectory( + dir: string, +): string | null { + debug("Searching for AppDelegate in directory: " + dir); + const files = readdirSync(dir); + const filePaths = files.map((f) => path.join(dir, f)); + return findAppDidFinishLaunchingWithOptions(filePaths); +} + +function findAppDidFinishLaunchingWithOptions(files: string[]): string | null { + debug(`Searching for AppDelegate in ${files.length} files`); + + // Iterate over subdirectories after iterating over files, + // because the AppDelegate is usually in the top level + const dirs: string[] = []; + for (const filePath of files) { + debug("Checking file: " + filePath); + if ( + filePath.endsWith(".swift") || + filePath.endsWith(".m") || + filePath.endsWith(".mm") + ) { + if (existsSync(filePath) && isAppDelegateFile(filePath)) { + debug("Found AppDelegate in " + filePath); + return filePath; + } + } else if ( + !path.basename(filePath).startsWith(".") && + !filePath.endsWith(".xcodeproj") && + !filePath.endsWith(".xcassets") && + existsSync(filePath) && + lstatSync(filePath).isDirectory() + ) { + dirs.push(filePath); + } + } + + for (const dr of dirs) { + const result = findAppDidFinishLaunchingWithOptionsInDirectory(dr); + if (result) { + debug("Found AppDelegate in " + dr); + return result; + } + } + return null; +} + +export function addCodeSnippetToProject( + files: string[], + dsn: string, + enableLogs: boolean, +): boolean { + const appDelegate = findAppDidFinishLaunchingWithOptions(files); + if (!appDelegate) { + return false; + } + + const fileContent = readFileSync(appDelegate, "utf8"); + const isSwift = appDelegate.toLowerCase().endsWith(".swift"); + const appLaunchRegex = isSwift ? swiftAppLaunchRegex : objcAppLaunchRegex; + const importStatement = isSwift ? "import Sentry\n" : "@import Sentry;\n"; + const checkForSentryInit = isSwift ? "SentrySDK.start" : "[SentrySDK start"; + let codeSnippet = isSwift + ? getSwiftSnippet(dsn, enableLogs) + : getObjcSnippet(dsn, enableLogs); + + Sentry.setTag("code-language", isSwift ? "swift" : "objc"); + Sentry.setTag( + "ui-engine", + swiftUIRegex.test(fileContent) ? "swiftui" : "uikit", + ); + + if (fileContent.includes(checkForSentryInit)) { + //already initialized + clack.log.info( + "Sentry is already initialized in your AppDelegate. Skipping adding the code snippet.", + ); + return true; + } + + let match = appLaunchRegex.exec(fileContent); + if (!match) { + const swiftUIMatch = swiftUIRegex.exec(fileContent); + if (!swiftUIMatch) { + // This branch is not reached, because we already checked for SwiftUI in isAppDelegateFile + return false; + } + + const afterStructContent = fileContent.slice(swiftUIMatch.index); + const bodyMatch = /var\s+body\s*:/m.exec(afterStructContent); + const searchRange = bodyMatch + ? afterStructContent.slice(0, bodyMatch.index) + : afterStructContent; + + const initMatch = swiftUIInitRegex.exec(searchRange); + + if (initMatch) { + match = { + index: swiftUIMatch.index + initMatch.index, + 0: initMatch[0], + } as RegExpExecArray; + } else { + match = swiftUIMatch; + codeSnippet = ` init() {\n${codeSnippet} }`; + } + } + + const insertIndex = match.index + match[0].length; + let newFileContent = + fileContent.slice(0, insertIndex) + + "\n" + + codeSnippet + + fileContent.slice(insertIndex); + + if (newFileContent.indexOf(importStatement) < 0) { + const firstImport = /^[ \t]*import +\w+.*$/m.exec(newFileContent); + if (firstImport) { + const importIndex = firstImport.index + firstImport[0].length; + newFileContent = + newFileContent.slice(0, importIndex) + + "\n" + + importStatement + + newFileContent.slice(importIndex); + } else { + newFileContent = importStatement + newFileContent; + } + } + + writeFileSync(appDelegate, newFileContent, "utf8"); + + clack.log.step("Added Sentry initialization code snippet to " + appDelegate); + return true; +} + +/** + * Exported for testing purposes, but should not be used in other modules. + */ +export let exportForTesting: { + isAppDelegateFile: typeof isAppDelegateFile; + findAppDidFinishLaunchingWithOptionsInDirectory: typeof findAppDidFinishLaunchingWithOptionsInDirectory; + findAppDidFinishLaunchingWithOptions: typeof findAppDidFinishLaunchingWithOptions; +}; +if (process.env["NODE_ENV"] === "test") { + exportForTesting = { + isAppDelegateFile, + findAppDidFinishLaunchingWithOptionsInDirectory, + findAppDidFinishLaunchingWithOptions, + }; +} diff --git a/packages/cli/src/lib/wizard/apple/configure-fastlane.ts b/packages/cli/src/lib/wizard/apple/configure-fastlane.ts new file mode 100644 index 000000000..3c524a378 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/configure-fastlane.ts @@ -0,0 +1,60 @@ +/** + * Offer to add the `sentry_debug_files_upload` action to a lane of the + * project's Fastfile. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; +import { traceStep } from "../telemetry.js"; +import { abortIfCancelled } from "../utils/clack/index.js"; +import { debug } from "../utils/debug.js"; +import { addSentryToFastlane, fastFile } from "./fastlane.js"; + +export async function configureFastlane({ + projectDir, + orgSlug, + projectSlug, +}: { + projectDir: string; + orgSlug: string; + projectSlug: string; +}) { + debug(`Checking if Fastfile exists in directory: ${chalk.cyan(projectDir)}`); + const isFastlaneAvailable = fastFile(projectDir); + Sentry.setTag("fastlane-exists", isFastlaneAvailable); + if (!isFastlaneAvailable) { + debug(`Fastfile not found, not configuring Fastlane`); + // If fastlane is not available, we don't need to configure it and exit early. + return; + } + + debug(`Fastfile found, asking user if they want to configure Fastlane`); + const shouldAddLane = await abortIfCancelled( + clack.confirm({ + message: + "Found a Fastfile in your project. Do you want to configure a lane to upload debug symbols to Sentry?", + }), + ); + debug(`User wants to add lane: ${chalk.cyan(shouldAddLane.toString())}`); + Sentry.setTag("fastlane-desired", shouldAddLane); + + if (shouldAddLane) { + debug(`Adding Sentry lane to Fastlane`); + const added = await traceStep("Configure fastlane", () => + addSentryToFastlane(projectDir, orgSlug, projectSlug), + ); + Sentry.setTag("fastlane-added", added); + debug(`Fastlane added: ${chalk.cyan(added.toString())}`); + + if (added) { + clack.log.step( + "A new step was added to your fastlane file. Now and you build your project with fastlane, debug symbols and source context will be uploaded to Sentry.", + ); + } else { + clack.log.warn( + "Could not edit your fastlane file to upload debug symbols to Sentry. Please follow the instructions at https://docs.sentry.io/platforms/apple/guides/ios/dsym/#fastlane", + ); + } + } +} diff --git a/packages/cli/src/lib/wizard/apple/configure-sentry-cli.ts b/packages/cli/src/lib/wizard/apple/configure-sentry-cli.ts new file mode 100644 index 000000000..5e5488e7a --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/configure-sentry-cli.ts @@ -0,0 +1,88 @@ +/** + * Give the Xcode build phase its credentials: write the auth token, org and + * project to a `.sentryclirc` in the project directory, which `sentry` reads, + * and keep that file out of git. + */ + +import { + appendFileSync, + existsSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; + +import chalk from "chalk"; + +import { Sentry } from "../telemetry.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; + +/** + * Write `.sentryclirc` with the auth token and `[defaults]` org and project, + * and add it to `.gitignore`. + */ +export function configureSentryCLI({ + projectDir, + authToken, + orgSlug, + projectSlug, +}: { + projectDir: string; + authToken: string; + orgSlug: string; + projectSlug: string; +}): void { + debug(`Creating sentryclirc file at path: ${chalk.cyan(projectDir)}`); + createSentryCLIRC(projectDir, { authToken, orgSlug, projectSlug }); + clack.log.info( + `Created a ${chalk.cyan( + ".sentryclirc", + )} file in your project directory with your auth token, organization, and project for the Sentry CLI. + +It was also added to your ${chalk.cyan(".gitignore")} file. +In your CI environment, set the ${chalk.cyan( + "SENTRY_AUTH_TOKEN", + )}, ${chalk.cyan("SENTRY_ORG")}, and ${chalk.cyan( + "SENTRY_PROJECT", + )} environment variables, and ${chalk.cyan( + "SENTRY_URL", + )} for self-hosted Sentry. See https://cli.sentry.dev/configuration/ for more information.`, + ); + Sentry.setTag("sentry-cli-configured", true); + debug(`Sentry CLI configured: ${chalk.cyan(true.toString())}`); +} + +/** Write `.sentryclirc` in `directory` and make sure git ignores it. */ +function createSentryCLIRC( + directory: string, + { + authToken, + orgSlug, + projectSlug, + }: { authToken: string; orgSlug: string; projectSlug: string }, +): void { + const rcPath = path.join(directory, ".sentryclirc"); + writeFileSync( + rcPath, + `[auth]\ntoken=${authToken}\n\n[defaults]\norg=${orgSlug}\nproject=${projectSlug}\n`, + ); + + const gitignorePath = path.join(directory, ".gitignore"); + if (!existsSync(gitignorePath)) { + clack.log.info( + `Creating .gitignore file at path: ${chalk.cyan(gitignorePath)}`, + ); + writeFileSync(gitignorePath, ".sentryclirc"); + } else { + const gitIgnore = readFileSync(gitignorePath).toString(); + if (!gitIgnore.includes(".sentryclirc")) { + clack.log.info( + `Appending .sentryclirc to .gitignore file at path: ${chalk.cyan( + gitignorePath, + )}`, + ); + appendFileSync(gitignorePath, "\n.sentryclirc\n"); + } + } +} diff --git a/packages/cli/src/lib/wizard/apple/configure-xcode-project.ts b/packages/cli/src/lib/wizard/apple/configure-xcode-project.ts new file mode 100644 index 000000000..bc82e9268 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/configure-xcode-project.ts @@ -0,0 +1,35 @@ +/** + * Apply the iOS wizard's Xcode project changes to one target (the Sentry + * Swift package and the upload build phase) and save the project. + */ + +import { traceStep } from "../telemetry.js"; +import { type SentryProjectData } from "../utils/types.js"; +import { + SENTRY_SPM_ALREADY_LINKED_FRAMEWORK_COMMENT, + sentrySwiftPackageProductSpec, +} from "./sentry-swift-package.js"; +import { XcodeProject } from "./xcode-manager.js"; + +export function configureXcodeProject({ + xcProject, + project, + target, +}: { + xcProject: XcodeProject; + project: SentryProjectData; + target: string; +}) { + traceStep("Update Xcode project", () => { + xcProject.updateXcodeProject( + project, + target, + { + product: sentrySwiftPackageProductSpec, + existingFrameworkComment: SENTRY_SPM_ALREADY_LINKED_FRAMEWORK_COMMENT, + successMessage: "Added Sentry SPM dependency to your project", + }, + true, + ); + }); +} diff --git a/packages/cli/src/lib/wizard/apple/fastlane.ts b/packages/cli/src/lib/wizard/apple/fastlane.ts new file mode 100644 index 000000000..fdb64a4e4 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/fastlane.ts @@ -0,0 +1,177 @@ +/** + * Find the Fastfile, its iOS platform block and lanes, and add the Sentry + * debug-files upload action to the lane the user picks. + */ + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { askForItemSelection } from "../utils/clack/index.js"; +import { getFastlaneSnippet } from "./templates.js"; +import { clack } from "../utils/clack/prompts.js"; + +export function fastFile(projectPath: string): string | null { + const fastlanePath = path.join(projectPath, "fastlane", "Fastfile"); + return existsSync(fastlanePath) ? fastlanePath : null; +} + +function findIOSPlatform( + content: string, +): { index: number; length: number } | null { + const platformRegex = /^ *platform\s+:([^ ]+)[^\n]*\n/gim; + let match = platformRegex.exec(content); + if (!match) { + // No platform found, treat whole file as one platform. + return { index: 0, length: content.length }; + } + + let index = -1; + while (match) { + if (match[1] === "ios") { + index = match.index + match[0].length; + break; + } + match = platformRegex.exec(content); + } + + if (index === -1) { + return null; + } + + //After finding the platform, we need to find the end of the platform block. + //This solution has the assumption that the file is well formed, + //which is not a perfect solution, but it's good enough assumption. + const platformEndRegex = /^end[^\n]*/gim; + match = platformEndRegex.exec(content.slice(index)); + if (!match) { + return null; + } + + return { index, length: match.index }; +} + +function findLanes( + content: string, +): { index: number; length: number; name: string }[] | null { + const laneRegex = /^ {2}lane\s+:([^ ]+)[^\n]*\n/gim; + let match = laneRegex.exec(content); + if (!match) { + return null; + } + + const lanes: { index: number; length: number; name: string }[] = []; + while (match) { + const laneEnd = /^ {2}end/m.exec( + content.slice(match.index + match[0].length), + ); + if (laneEnd === null) { + return null; + } + lanes.push({ + index: match.index + match[0].length, + length: laneEnd.index, + name: match[1] ?? "", + }); + match = laneRegex.exec(content); + } + return lanes; +} + +function addSentryToLane( + content: string, + lane: { index: number; length: number; name: string }, + org: string, + project: string, +): string { + const laneContent = content.slice(lane.index, lane.index + lane.length); + const sentryCLIMatch = /(\n\s+)sentry_debug_files_upload\s*\([^)]+\)/gim.exec( + laneContent, + ); + if (sentryCLIMatch) { + // Sentry already added to lane. Update it. + // sentryCLIMatch[1] contains the leading newline and whitespace + return ( + content.slice(0, sentryCLIMatch.index + lane.index) + + sentryCLIMatch[1] + + getFastlaneSnippet(org, project).trim() + + content.slice( + sentryCLIMatch.index + sentryCLIMatch[0].length + lane.index, + ) + ); + } + + // Sentry not added to lane. Add it. + return ( + content.slice(0, lane.index + lane.length) + + "\n" + + getFastlaneSnippet(org, project) + + "\n" + + content.slice(lane.index + lane.length) + ); +} + +export async function addSentryToFastlane( + projectDir: string, + org: string, + project: string, +): Promise { + const fastFilePath = fastFile(projectDir); + if (!fastFilePath) { + return false; + } + + const fileContent = readFileSync(fastFilePath, "utf8"); + const platform = findIOSPlatform(fileContent); + if (!platform) { + return false; + } + + const platformContent = fileContent.slice( + platform.index, + platform.index + platform.length, + ); + const lanes = findLanes(platformContent); + for (const lane of lanes ?? []) { + lane.index += platform.index; + } + + if (!lanes || lanes.length === 0) { + clack.log.warn("No suitable lanes in your Fastfile."); + return false; + } + + let newFileContent: string | undefined; + const [onlyLane] = lanes; + if (lanes.length === 1 && onlyLane) { + newFileContent = addSentryToLane(fileContent, onlyLane, org, project); + } else { + const laneNames = lanes.map((l) => l.name); + const selectedLane = await askForItemSelection( + laneNames, + "Select lane to add Sentry to:", + ); + const lane = lanes[selectedLane.index]; + if (!lane) { + return false; + } + newFileContent = addSentryToLane(fileContent, lane, org, project); + } + + writeFileSync(fastFilePath, newFileContent, "utf8"); + return true; +} + +/** + * Exported for testing purposes, but should not be used in other modules. + */ +export let exportForTesting: { + findIOSPlatform: typeof findIOSPlatform; + findLanes: typeof findLanes; + addSentryToLane: typeof addSentryToLane; +}; +if (process.env["NODE_ENV"] === "test") { + exportForTesting = { + findIOSPlatform, + findLanes, + addSentryToLane, + }; +} diff --git a/packages/cli/src/lib/wizard/apple/inject-code-snippet.ts b/packages/cli/src/lib/wizard/apple/inject-code-snippet.ts new file mode 100644 index 000000000..bb5d6b641 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/inject-code-snippet.ts @@ -0,0 +1,49 @@ +/** + * Add the Sentry init snippet to the app target's source files, or print it + * for the user to paste when no entry point is found. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; +import { traceStep } from "../telemetry.js"; +import { debug } from "../utils/debug.js"; +import { addCodeSnippetToProject } from "./code-tools.js"; +import { XcodeProject } from "./xcode-manager.js"; + +export function injectCodeSnippet({ + project, + target, + dsn, + enableLogs, +}: { + project: XcodeProject; + target: string; + dsn: string; + enableLogs: boolean; +}) { + debug( + `Injecting code snippet into project at path: ${chalk.cyan( + project.baseDir, + )}`, + ); + const codeAdded = traceStep("Add code snippet", () => { + const files = project.getSourceFilesForTarget(target); + if (files === undefined || files.length == 0) { + debug("No files found for target: " + target); + Sentry.setTag("snippet-candidate-files-not-found", true); + return false; + } + + debug(`Adding code snippet to ${files.length} candidate files`); + return addCodeSnippetToProject(files, dsn, enableLogs); + }); + Sentry.setTag("Snippet-Added", codeAdded); + debug(`Snippet added: ${chalk.cyan(codeAdded.toString())}`); + + if (!codeAdded) { + clack.log.warn( + "Added the Sentry dependency to your project but could not add the Sentry code snippet. Please add the code snippet manually by following the docs: https://docs.sentry.io/platforms/apple/guides/ios/#configure", + ); + } +} diff --git a/packages/cli/src/lib/wizard/apple/lookup-xcode-project.ts b/packages/cli/src/lib/wizard/apple/lookup-xcode-project.ts new file mode 100644 index 000000000..8a43b1fe8 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/lookup-xcode-project.ts @@ -0,0 +1,127 @@ +/** + * Find the Xcode project (directly or through a workspace) and the target the + * Apple wizards configure, asking when there is more than one. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; +import { existsSync } from "node:fs"; +import path from "node:path"; + +import { traceStep } from "../telemetry.js"; +import { abort, askForItemSelection } from "../utils/clack/index.js"; +import { debug } from "../utils/debug.js"; +import { searchXcodeProjectAtPath } from "./search-xcode-project-at-path.js"; +import { XcodeProject } from "./xcode-manager.js"; + +export async function lookupXcodeProject({ + projectDir, + nonInteractive = false, +}: { + projectDir: string; + nonInteractive?: boolean | undefined; +}): Promise { + debug(`Looking for Xcode project in directory: ${chalk.cyan(projectDir)}`); + const xcodeProjFiles = searchXcodeProjectAtPath(projectDir); + if (xcodeProjFiles.length === 0) { + clack.log.error( + "No Xcode project found. Please run this command from the root of your project.", + ); + Sentry.setTag("no-xcode-project", true); + return await abort(); + } + debug( + `Found ${chalk.cyan( + xcodeProjFiles.length.toString(), + )} candidates for Xcode project`, + ); + + // In case there is only one Xcode project, we can use that one. + // Otherwise, we need to ask the user which one they want to use. + let xcodeProjFile: string; + const [onlyProjFile] = xcodeProjFiles; + if (xcodeProjFiles.length === 1 && onlyProjFile !== undefined) { + debug(`Found exactly one Xcode project, using it`); + Sentry.setTag("multiple-projects", false); + xcodeProjFile = onlyProjFile; + } else { + debug(`Found multiple Xcode projects, asking user to choose one`); + Sentry.setTag("multiple-projects", true); + + if (nonInteractive) { + clack.log.error( + [ + "Multiple Xcode projects found in non-interactive mode.", + `Available projects: ${xcodeProjFiles.join(", ")}.`, + "Run the wizard in a terminal to choose one, or from a directory with a single .xcodeproj.", + ].join(" "), + ); + return await abort(); + } + + xcodeProjFile = ( + await traceStep("Choose Xcode project", () => + askForItemSelection( + xcodeProjFiles, + "Which project do you want to add Sentry to?", + ), + ) + ).value; + } + + const pathToPbxproj = path.join(projectDir, xcodeProjFile, "project.pbxproj"); + debug(`Loading Xcode project pbxproj at path: ${chalk.cyan(pathToPbxproj)}`); + if (!existsSync(pathToPbxproj)) { + clack.log.error(`No pbxproj found at ${xcodeProjFile}`); + Sentry.setTag("pbxproj-not-found", true); + return await abort(); + } + + return new XcodeProject(pathToPbxproj); +} + +export async function selectXcodeTarget( + xcProject: XcodeProject, + { + targetNames = xcProject.getAllTargets(), + noTargetMessage = `No suitable Xcode target found in ${path.basename( + xcProject.xcodeprojPath, + )}`, + promptMessage = "Which target do you want to add Sentry to?", + }: { + targetNames?: string[] | undefined; + noTargetMessage?: string | undefined; + promptMessage?: string | undefined; + } = {}, +): Promise { + if (targetNames.length === 0) { + clack.log.error(noTargetMessage); + Sentry.setTag("No-Target", true); + return await abort(); + } + debug( + `Found ${chalk.cyan( + targetNames.length.toString(), + )} targets in Xcode project`, + ); + + let target: string; + const [onlyTarget] = targetNames; + if (targetNames.length === 1 && onlyTarget !== undefined) { + debug(`Found exactly one target, using it`); + Sentry.setTag("multiple-targets", false); + target = onlyTarget; + } else { + debug(`Found multiple targets, asking user to choose one`); + Sentry.setTag("multiple-targets", true); + target = ( + await traceStep("Choose target", () => + askForItemSelection(targetNames, promptMessage), + ) + ).value; + } + debug(`Selected target: ${chalk.cyan(target)}`); + + return target; +} diff --git a/packages/cli/src/lib/wizard/apple/macos-system-helper.ts b/packages/cli/src/lib/wizard/apple/macos-system-helper.ts new file mode 100644 index 000000000..2eb152c11 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/macos-system-helper.ts @@ -0,0 +1,77 @@ +/** + * Read macOS developer paths the Xcode project manager resolves group paths + * against: Xcode's developer directory, SDK roots, and derived data. + */ + +import { execFileSync, execSync } from "node:child_process"; +import { debug } from "../utils/debug.js"; + +export class MacOSSystemHelpers { + static findSDKRootDirectoryPath(): string | undefined { + try { + // Some Candidates: + // - /Applications/Xcode-16.3.0.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk + // - /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk + const sdkPath = execSync("xcrun --show-sdk-path", { + encoding: "utf8", + }).trim(); + return sdkPath; + } catch (error) { + debug(`Failed to find SDK root directory path: ${error as string}`); + return undefined; + } + } + + static findDeveloperDirectoryPath(): string | undefined { + try { + // Some Candidates: + // - /Applications/Xcode.app/Contents/Developer + // - /Applications/Xcode-16.3.0.app/Contents/Developer + const developerPath = execSync("xcode-select --print-path", { + encoding: "utf8", + }).trim(); + return developerPath; + } catch (error) { + debug(`Failed to find developer directory path: ${error as string}`); + return undefined; + } + } + + static readXcodeBuildSettings( + projectPath: string, + ): Record | undefined { + try { + // execFileSync passes the path as one argument with no shell, so a + // project directory name can't run commands. It throws on a timeout + // or a non-zero exit code. + const output = execFileSync( + "xcodebuild", + ["-project", projectPath, "-showBuildSettings"], + { encoding: "utf8" }, + ).trim(); + // --- Example Output: --- + // Command line invocation: + // /Applications/Xcode-16.3.0.app/Contents/Developer/usr/bin/xcodebuild -project ./fixtures/test-applications/apple/project-with-synchronized-folders/Project.xcodeproj -showBuildSettings + // + // Build settings for action build and target Project: + // ACTION = build + // ALLOW_BUILD_REQUEST_OVERRIDES = NO + // ALLOW_TARGET_PLATFORM_SPECIALIZATION = YES + // ALTERNATE_GROUP = staff + // ... + const lines = output.split("\n"); + const settings: Record = {}; + for (const line of lines) { + const match = line.match(/^\s*(\w+)\s+=\s+(.*)$/); + if (match?.[1] !== undefined && match[2] !== undefined) { + settings[match[1]] = match[2]; + } + } + + return settings; + } catch (error) { + debug(`Failed to read Xcode build settings: ${error as string}`); + return undefined; + } + } +} diff --git a/packages/cli/src/lib/wizard/apple/options.ts b/packages/cli/src/lib/wizard/apple/options.ts new file mode 100644 index 000000000..e5df01eee --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/options.ts @@ -0,0 +1,15 @@ +/** + * Options of the iOS and Apple Snapshots wizards. + */ + +import { type WizardOptions } from "../utils/types.js"; + +export interface AppleWizardOptions extends WizardOptions { + /** Directory to look for the Xcode project in; the current directory when unset. */ + projectDir?: string | undefined; +} + +export interface AppleSnapshotsWizardOptions extends AppleWizardOptions { + /** Fail with the choices instead of prompting, such as when stdin is not a terminal. */ + nonInteractive: boolean; +} diff --git a/packages/cli/src/lib/wizard/apple/search-xcode-project-at-path.ts b/packages/cli/src/lib/wizard/apple/search-xcode-project-at-path.ts new file mode 100644 index 000000000..2d74705de --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/search-xcode-project-at-path.ts @@ -0,0 +1,65 @@ +/** + * List the `.xcodeproj` bundles in a directory, or the ones its + * `.xcworkspace` references, without CocoaPods' `Pods.xcodeproj`. + */ + +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { debug } from "../utils/debug.js"; +import { findFilesWithExtension } from "../utils/find-files-with-extension.js"; + +export function searchXcodeProjectAtPath(searchPath: string): string[] { + debug("Searching for Xcode project at path: " + searchPath); + const projs = findFilesWithExtension(searchPath, ".xcodeproj"); + if (projs.length > 0) { + debug("Found Xcode project at paths:"); + for (const proj of projs) { + debug(" " + proj); + } + return projs; + } + + debug("Searching for Xcode workspace at path: " + searchPath); + const workspace = findFilesWithExtension(searchPath, ".xcworkspace"); + const [workspaceName] = workspace; + if (workspaceName === undefined) { + debug("No Xcode workspace found at path: " + searchPath); + return []; + } + + debug("Found Xcode workspace at path: " + workspaceName); + const xsworkspacedata = path.join( + searchPath, + workspaceName, + "contents.xcworkspacedata", + ); + if (!existsSync(xsworkspacedata)) { + debug("No Xcode workspace data found at path: " + xsworkspacedata); + return []; + } + + debug("Parsing Xcode workspace data at path: " + xsworkspacedata); + const groupRegex = /location *= *"group:([^"]+)"/gim; + const content = readFileSync(xsworkspacedata, "utf8"); + let matches = groupRegex.exec(content); + + while (matches) { + const group = matches[1] ?? ""; + const groupPath = path.join(searchPath, group); + if ( + !group.endsWith("Pods.xcodeproj") && + group.endsWith(".xcodeproj") && + existsSync(groupPath) + ) { + projs.push(group); + } + matches = groupRegex.exec(content); + } + + debug("Found Xcode project at paths:"); + for (const proj of projs) { + debug(" " + proj); + } + return projs; +} diff --git a/packages/cli/src/lib/wizard/apple/sentry-swift-package.ts b/packages/cli/src/lib/wizard/apple/sentry-swift-package.ts new file mode 100644 index 000000000..681318038 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/sentry-swift-package.ts @@ -0,0 +1,25 @@ +/** + * The Sentry Cocoa Swift package and product the iOS wizard links. + */ + +import type { + SwiftPackageProductSpec, + SwiftPackageSpec, +} from "./xcode-manager.js"; + +export const SENTRY_SPM_ALREADY_LINKED_FRAMEWORK_COMMENT = + "Sentry in Frameworks"; + +export const sentrySwiftPackageSpec: SwiftPackageSpec = { + repositoryURL: "https://github.com/getsentry/sentry-cocoa/", + requirement: { + kind: "upToNextMajorVersion", + minimumVersion: "9.0.0", + }, + commentName: "sentry-cocoa", +}; + +export const sentrySwiftPackageProductSpec: SwiftPackageProductSpec = { + package: sentrySwiftPackageSpec, + productName: "Sentry", +}; diff --git a/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts b/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts new file mode 100644 index 000000000..0fd2d14c8 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts @@ -0,0 +1,323 @@ +/** + * The Apple Snapshots wizard (`sentry wizard appleSnapshots`): links + * SnapshotPreviews to a hosted XCTest target, adds a snapshot test, and + * prints how to export and upload the snapshots. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; + +import { clack } from "../../utils/clack/prompts.js"; + +import { withTelemetry } from "../../telemetry.js"; +import { + abort, + abortIfCancelled, + askForItemSelection, + confirmContinueIfNoOrDirtyGitRepo, + printWelcome, +} from "../../utils/clack/index.js"; +import { + lookupXcodeProject, + selectXcodeTarget, +} from "../lookup-xcode-project.js"; +import type { AppleSnapshotsWizardOptions } from "../options.js"; +import type { XcodeProject } from "../xcode-manager.js"; +import { printSnapshotsUploadSetup } from "./snapshots-cli-preflight.js"; +import { configureSnapshotPreviewsXcodeProject } from "./configure-snapshotpreviews-xcode-project.js"; +import { + ensureSnapshotTestFile, + snapshotTestClassName, + snapshotTestTemplate, +} from "./snapshot-test-file.js"; +import { resolveSnapshotVerificationSchemeName } from "./snapshot-verification-scheme.js"; +import { + SNAPSHOTPREVIEWS_MINIMUM_VERSION, + SNAPSHOTPREVIEWS_PACKAGE_URL, + SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT, + SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT, +} from "./snapshotpreviews-package.js"; + +const APPLE_SNAPSHOTS_SETUP_DID_NOT_COMPLETE = + "Apple Snapshots setup did not complete."; + +export async function runAppleSnapshotsWizard( + options: AppleSnapshotsWizardOptions, +): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "appleSnapshots", + wizardOptions: options, + }, + () => runAppleSnapshotsWizardWithTelemetry(options), + ); +} + +async function runAppleSnapshotsWizardWithTelemetry( + options: AppleSnapshotsWizardOptions, +): Promise { + const projectDir = options.projectDir ?? process.cwd(); + + printWelcome({ + wizardName: "Sentry Apple Snapshots Wizard", + }); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: projectDir, + nonInteractive: options.nonInteractive, + }); + + clack.log.info( + [ + `Apple Snapshots setup will use ${SNAPSHOTPREVIEWS_PACKAGE_URL}`, + `${SNAPSHOTPREVIEWS_MINIMUM_VERSION}+ and link`, + `${SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT} to the hosted XCTest`, + `target and ${SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT} to the selected`, + "app target.", + ].join(" "), + ); + + const xcProject = await lookupXcodeProject({ + projectDir, + nonInteractive: options.nonInteractive, + }); + + const appTargetName = await resolveAppTargetName(xcProject, options); + if (!appTargetName) { + return await abort(APPLE_SNAPSHOTS_SETUP_DID_NOT_COMPLETE); + } + + const hostedTestTargetName = await resolveHostedTestTargetName( + xcProject, + appTargetName, + options, + ); + if (!hostedTestTargetName) { + return await abort(APPLE_SNAPSHOTS_SETUP_DID_NOT_COMPLETE); + } + + const previewTargetNames = [appTargetName]; + + clack.log.info( + [ + `${SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT} will be linked to the selected`, + "app target when possible. Import SnapshotPreferences in Swift", + "preview files only if you want to use SnapshotPreviews modifiers.", + ].join(" "), + ); + + if (existsSync(path.join(projectDir, "Package.swift"))) { + clack.log.info( + [ + "Detected Package.swift. This wizard does not edit SwiftPM manifests.", + `If SwiftPM preview targets use SnapshotPreferences modifiers, add`, + `the ${SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT} product dependency to those`, + "targets in Package.swift.", + ].join(" "), + ); + } + + const packageResult = configureSnapshotPreviewsXcodeProject({ + xcodeProject: xcProject, + hostedTestTargetName, + previewTargetNames, + }); + + if (!packageResult.linked) { + clack.log.error( + "SnapshotPreviews package products could not be linked to the selected targets. Please check the Xcode project target build phases and try again.", + ); + await abort(APPLE_SNAPSHOTS_SETUP_DID_NOT_COMPLETE); + return; + } + + if (packageResult.failedSnapshotPreferencesTargetNames.length) { + clack.log.warn( + [ + `${SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT} could not be linked to`, + packageResult.failedSnapshotPreferencesTargetNames.join(", "), + "because the target Frameworks build phase could not be updated.", + "Apple Snapshots setup will continue; link the product manually if", + "you want to use SnapshotPreviews modifiers in Swift previews.", + ].join(" "), + ); + } + + const snapshotTestResult = ensureSnapshotTestFile({ + xcodeProject: xcProject, + hostedTestTargetName, + }); + if (!snapshotTestResult.included) { + clack.log.error( + "SnapshotPreviews test file could not be added to the selected XCTest target. Please check the target Sources build phase and try again.", + ); + await abort(APPLE_SNAPSHOTS_SETUP_DID_NOT_COMPLETE); + return; + } + + if (snapshotTestResult.changed || packageResult.changed) { + xcProject.write(); + clack.log.success("Updated the Xcode project for SnapshotPreviews."); + } else { + clack.log.info("SnapshotPreviews Xcode project setup is already present."); + } + + printSnapshotsUploadSetup({ + projectDir, + verificationGuidance: { + appId: xcProject.getBundleIdentifierForTarget(appTargetName), + hostedTestTargetName, + projectDir, + projectPath: xcProject.xcodeprojPath, + schemeName: resolveSnapshotVerificationSchemeName({ + hostedTestTargetName, + xcodeprojPath: xcProject.xcodeprojPath, + }), + snapshotTestClassName: snapshotTestResult.className, + }, + }); + + clack.outro("Apple Snapshots setup complete."); +} + +async function resolveAppTargetName( + xcodeProject: XcodeProject, + options: AppleSnapshotsWizardOptions, +): Promise { + const appTargetNames = xcodeProject.getAllTargets(); + if (appTargetNames.length === 0) { + clack.log.error("No application target found."); + return undefined; + } + + if (options.nonInteractive && appTargetNames.length !== 1) { + clack.log.error( + [ + "Could not automatically select an Xcode app target in non-interactive mode.", + `Available app targets: ${formatList(appTargetNames)}.`, + "Run the wizard in a terminal to choose the app target that SnapshotPreviews should use.", + ].join(" "), + ); + return undefined; + } + + return await selectXcodeTarget(xcodeProject, { + targetNames: appTargetNames, + noTargetMessage: "No application target found.", + promptMessage: "Which app target should SnapshotPreviews use?", + }); +} + +async function resolveHostedTestTargetName( + xcodeProject: XcodeProject, + appTargetName: string, + options: AppleSnapshotsWizardOptions, +): Promise { + const hostedTestTargetNames = xcodeProject.getHostedUnitTestTargetNames(); + const inferredHostedTestTargetNames = + xcodeProject.getHostedUnitTestTargetNamesForApplicationTarget( + appTargetName, + ); + if (inferredHostedTestTargetNames.length > 0) { + return await selectHostedTestTargetName({ + appTargetName, + hostedTestTargetNames: inferredHostedTestTargetNames, + nonInteractive: options.nonInteractive, + promptMessage: "Which test target should render SnapshotPreviews?", + }); + } + + if (hostedTestTargetNames.length === 0) { + clack.log.error( + [ + `No hosted XCTest target was found for ${appTargetName}.`, + manualAppleSnapshotsSetupInstructions({ appTargetName }), + ].join("\n"), + ); + return undefined; + } + + clack.log.warn( + [ + `Could not automatically match a hosted XCTest target to ${appTargetName}.`, + "This can happen when TEST_HOST uses Xcode build-setting macros for the app bundle or executable name.", + ].join(" "), + ); + + return await selectHostedTestTargetName({ + appTargetName, + hostedTestTargetNames, + nonInteractive: options.nonInteractive, + promptMessage: "Which hosted XCTest target should render SnapshotPreviews?", + }); +} + +async function selectHostedTestTargetName({ + appTargetName, + hostedTestTargetNames, + nonInteractive, + promptMessage, +}: { + appTargetName: string; + hostedTestTargetNames: string[]; + nonInteractive: boolean; + promptMessage: string; +}): Promise { + if (hostedTestTargetNames.length === 1) { + return hostedTestTargetNames[0]; + } + + if (nonInteractive) { + clack.log.error( + [ + `Could not automatically select the hosted XCTest target for ${appTargetName} in non-interactive mode.`, + `Available hosted XCTest targets: ${formatList( + hostedTestTargetNames, + )}.`, + "Run the wizard in a terminal to choose the target.", + manualAppleSnapshotsSetupInstructions({ + appTargetName, + hostedTestTargetName: hostedTestTargetNames[0], + }), + ].join("\n"), + ); + return undefined; + } + + const selection = await abortIfCancelled( + askForItemSelection(hostedTestTargetNames, promptMessage), + ); + return selection.value; +} + +function manualAppleSnapshotsSetupInstructions({ + appTargetName, + hostedTestTargetName, +}: { + appTargetName: string; + hostedTestTargetName?: string | undefined; +}): string { + const exampleHostedTestTargetName = hostedTestTargetName ?? "AppTests"; + const sourceFileInstruction = hostedTestTargetName + ? "3. Add this XCTest source file to the hosted XCTest target:" + : `3. Add this XCTest source file to the hosted XCTest target. This example assumes the hosted XCTest target is named ${exampleHostedTestTargetName}:`; + + return [ + "Manual setup:", + `1. Add the ${SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT} package product to the hosted XCTest target for ${appTargetName}.`, + `2. Add the ${SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT} package product to ${appTargetName} if its Swift previews use SnapshotPreviews modifiers.`, + sourceFileInstruction, + "```swift", + snapshotTestTemplate( + snapshotTestClassName(exampleHostedTestTargetName), + ).trimEnd(), + "```", + "4. Run the hosted XCTest target with xcodebuild.", + ].join("\n"); +} + +function formatList(values: string[]): string { + return values.length > 0 ? values.join(", ") : "none"; +} diff --git a/packages/cli/src/lib/wizard/apple/snapshots/configure-snapshotpreviews-xcode-project.ts b/packages/cli/src/lib/wizard/apple/snapshots/configure-snapshotpreviews-xcode-project.ts new file mode 100644 index 000000000..0d9e5524f --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/configure-snapshotpreviews-xcode-project.ts @@ -0,0 +1,82 @@ +/** + * Link the SnapshotPreviews Swift package to the hosted test target and the + * app targets that use its preview modifiers. + */ + +import type { + SwiftPackageProductSpec, + SwiftPackageSpec, + XcodeProject, +} from "../xcode-manager.js"; +import { + SNAPSHOTPREVIEWS_MINIMUM_VERSION, + SNAPSHOTPREVIEWS_PACKAGE_URL, + SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT, + SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT, +} from "./snapshotpreviews-package.js"; + +export const snapshotPreviewsPackageSpec: SwiftPackageSpec = { + repositoryURL: SNAPSHOTPREVIEWS_PACKAGE_URL, + requirement: { + kind: "upToNextMajorVersion", + minimumVersion: SNAPSHOTPREVIEWS_MINIMUM_VERSION, + }, + commentName: "SnapshotPreviews", +}; + +export const snapshottingTestsProductSpec: SwiftPackageProductSpec = { + package: snapshotPreviewsPackageSpec, + productName: SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT, +}; + +export const snapshotPreferencesProductSpec: SwiftPackageProductSpec = { + package: snapshotPreviewsPackageSpec, + productName: SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT, +}; + +export function configureSnapshotPreviewsXcodeProject({ + xcodeProject, + hostedTestTargetName, + previewTargetNames = [], +}: { + xcodeProject: XcodeProject; + hostedTestTargetName: string; + previewTargetNames?: string[] | undefined; +}): { + changed: boolean; + failedSnapshotPreferencesTargetNames: string[]; + linked: boolean; +} { + if (!xcodeProject.getUnitTestTargetNames().includes(hostedTestTargetName)) { + return { + changed: false, + failedSnapshotPreferencesTargetNames: [], + linked: false, + }; + } + + const snapshottingTestsResult = xcodeProject.ensureSwiftPackageProductLinked( + hostedTestTargetName, + snapshottingTestsProductSpec, + ); + const snapshotPreferencesResults = previewTargetNames.map((targetName) => ({ + result: xcodeProject.ensureSwiftPackageProductLinked( + targetName, + snapshotPreferencesProductSpec, + ), + targetName, + })); + const linkResults = [ + snapshottingTestsResult, + ...snapshotPreferencesResults.map(({ result }) => result), + ]; + const failedSnapshotPreferencesTargetNames = snapshotPreferencesResults + .filter(({ result }) => !result.linked) + .map(({ targetName }) => targetName); + + return { + changed: linkResults.some((result) => result.changed), + failedSnapshotPreferencesTargetNames, + linked: snapshottingTestsResult.linked, + }; +} diff --git a/packages/cli/src/lib/wizard/apple/snapshots/snapshot-test-file.ts b/packages/cli/src/lib/wizard/apple/snapshots/snapshot-test-file.ts new file mode 100644 index 000000000..3f3f06704 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/snapshot-test-file.ts @@ -0,0 +1,157 @@ +/** + * Create the XCTest file that renders SwiftUI previews as snapshots, and add + * it to the hosted test target. + */ + +import { + existsSync, + mkdirSync, + readFileSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import path from "node:path"; + +import type { XcodeProject } from "../xcode-manager.js"; + +const SNAPSHOT_TEST_IMPORT = "import SnapshottingTests"; + +type EnsureSnapshotTestFileResult = + | { changed: false; included: false } + | { + changed: boolean; + className: string; + filePath: string; + included: true; + }; + +export function ensureSnapshotTestFile({ + xcodeProject, + hostedTestTargetName, +}: { + xcodeProject: XcodeProject; + hostedTestTargetName: string; +}): EnsureSnapshotTestFileResult { + const existingSnapshotTestFile = findExistingSnapshotTestFile( + xcodeProject, + hostedTestTargetName, + ); + if (existingSnapshotTestFile) { + return { + changed: false, + className: existingSnapshotTestFile.className, + filePath: existingSnapshotTestFile.filePath, + included: true, + }; + } + + const className = snapshotTestClassName(hostedTestTargetName); + const filePath = path.join( + getSnapshotTestDirectory(xcodeProject, hostedTestTargetName), + `${className}.swift`, + ); + + mkdirSync(path.dirname(filePath), { recursive: true }); + const fileCreated = !existsSync(filePath); + if (fileCreated) { + writeFileSync(filePath, snapshotTestTemplate(className), "utf8"); + } + + const membership = xcodeProject.addSwiftSourceFileToTarget({ + targetName: hostedTestTargetName, + filePath, + }); + + if (!membership.included) { + if (fileCreated) { + unlinkSync(filePath); + } + + return { changed: false, included: false }; + } + + return { + changed: fileCreated || membership.changed, + className, + filePath, + included: true, + }; +} + +export function snapshotTestClassName(hostedTestTargetName: string): string { + return `${swiftSafeTypeName(hostedTestTargetName)}SnapshotTest`; +} + +export function snapshotTestTemplate(className: string): string { + return `${SNAPSHOT_TEST_IMPORT} + +final class ${className}: SnapshotTest { + override class func snapshotPreviews() -> [String]? { nil } + override class func excludedSnapshotPreviews() -> [String]? { nil } + override class func snapshotPreviewModules() -> [String]? { nil } + override class func excludedSnapshotPreviewModules() -> [String]? { nil } +} +`; +} + +export function swiftSafeTypeName(value: string): string { + const words = value.split(/[^A-Za-z0-9]+/).filter((word) => word.length > 0); + const typeName = words + .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`) + .join(""); + + if (!typeName) { + return "Snapshots"; + } + + return /^[0-9]/.test(typeName) ? `_${typeName}` : typeName; +} + +function findExistingSnapshotTestFile( + xcodeProject: XcodeProject, + hostedTestTargetName: string, +): { className: string; filePath: string } | undefined { + const sourceFiles = + xcodeProject.getSourceFilesForTarget(hostedTestTargetName) ?? []; + for (const filePath of sourceFiles) { + if (!filePath.endsWith(".swift") || !existsSync(filePath)) { + continue; + } + + const contents = readFileSync(filePath, "utf8"); + const className = getSnapshotTestClassName(contents); + if (contents.includes(SNAPSHOT_TEST_IMPORT) && className) { + return { className, filePath }; + } + } + + return undefined; +} + +function getSnapshotTestClassName(contents: string): string | undefined { + return contents.match( + /\bclass\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*SnapshotTest\b/, + )?.[1]; +} + +function getSnapshotTestDirectory( + xcodeProject: XcodeProject, + hostedTestTargetName: string, +): string { + const synchronizedRootGroupPath = + xcodeProject.getSynchronizedRootGroupPathsForTarget( + hostedTestTargetName, + )[0]; + if (synchronizedRootGroupPath) { + return synchronizedRootGroupPath; + } + + const existingSwiftFile = xcodeProject + .getSourceFilesForTarget(hostedTestTargetName) + ?.find((filePath) => filePath.endsWith(".swift")); + if (existingSwiftFile) { + return path.dirname(existingSwiftFile); + } + + return path.join(xcodeProject.baseDir, hostedTestTargetName); +} diff --git a/packages/cli/src/lib/wizard/apple/snapshots/snapshot-verification-scheme.ts b/packages/cli/src/lib/wizard/apple/snapshots/snapshot-verification-scheme.ts new file mode 100644 index 000000000..a465d2fbf --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/snapshot-verification-scheme.ts @@ -0,0 +1,119 @@ +/** + * Find the Xcode scheme to suggest in the snapshot export command: the one + * shared or user scheme whose test action runs the hosted test target, or + * else the project's only scheme. + */ + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { debug } from "../../utils/debug.js"; +import { + findFilesWithExtension, + findFilesWithName, +} from "../../utils/files.js"; +import { + getAttributeValues, + getElementContent, + getElementTexts, +} from "./xml-scan.js"; + +type SnapshotVerificationSchemeOptions = { + hostedTestTargetName: string; + xcodeprojPath: string; +}; + +type ExplicitScheme = { + name: string; + testTargetNames: string[]; +}; + +export function resolveSnapshotVerificationSchemeName({ + hostedTestTargetName, + xcodeprojPath, +}: SnapshotVerificationSchemeOptions): string | undefined { + const explicitSchemes = getExplicitSchemes(xcodeprojPath); + const matchingExplicitSchemes = explicitSchemes.filter((scheme) => + scheme.testTargetNames.includes(hostedTestTargetName), + ); + const matchingExplicitSchemeNames = uniqueStrings( + matchingExplicitSchemes.map((scheme) => scheme.name), + ); + if (matchingExplicitSchemeNames.length === 1) { + return matchingExplicitSchemeNames[0]; + } + + const managedSchemeNames = getManagedSchemeNames(xcodeprojPath); + if (managedSchemeNames.length === 1) { + return managedSchemeNames[0]; + } + + return undefined; +} + +function getExplicitSchemes(xcodeprojPath: string): ExplicitScheme[] { + return getSchemeFilePaths(xcodeprojPath).flatMap((schemePath) => { + const schemeName = path.basename(schemePath, ".xcscheme"); + const testTargetNames = readSchemeTestTargetNames(schemePath); + return schemeName ? [{ name: schemeName, testTargetNames }] : []; + }); +} + +function getSchemeFilePaths(xcodeprojPath: string): string[] { + return [ + path.join(xcodeprojPath, "xcshareddata", "xcschemes"), + path.join(xcodeprojPath, "xcuserdata"), + ].flatMap((schemeDirectory) => + findFilesWithExtension(schemeDirectory, ".xcscheme"), + ); +} + +function readSchemeTestTargetNames(schemePath: string): string[] { + const scheme = readXmlFile(schemePath); + if (scheme === undefined) { + return []; + } + + const testAction = getElementContent(scheme, "TestAction"); + if (testAction === undefined) { + return []; + } + return uniqueStrings(getAttributeValues(testAction, "BlueprintName")); +} + +function getManagedSchemeNames(xcodeprojPath: string): string[] { + return uniqueStrings( + findFilesWithName(xcodeprojPath, "xcschememanagement.plist").flatMap( + readManagedSchemeNames, + ), + ); +} + +function readManagedSchemeNames(plistPath: string): string[] { + const plist = readXmlFile(plistPath); + if (plist === undefined) { + return []; + } + + return getElementTexts(plist, "key").flatMap((key) => { + const schemeName = parseManagedSchemeName(key); + return schemeName ? [schemeName] : []; + }); +} + +function parseManagedSchemeName(key: string): string | undefined { + return /^(.+)\.xcscheme(?:_.+)?$/.exec(key)?.[1]; +} + +function readXmlFile(filePath: string): string | undefined { + try { + return readFileSync(filePath, "utf8"); + } catch (error) { + debug("Could not read XML file:", filePath, error); + return undefined; + } +} + +function uniqueStrings(values: string[]): string[] { + return [...new Set(values)]; +} diff --git a/packages/cli/src/lib/wizard/apple/snapshots/snapshotpreviews-package.ts b/packages/cli/src/lib/wizard/apple/snapshots/snapshotpreviews-package.ts new file mode 100644 index 000000000..5318f81c8 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/snapshotpreviews-package.ts @@ -0,0 +1,12 @@ +/** + * The SnapshotPreviews Swift package the Apple Snapshots wizard links. + */ + +export const SNAPSHOTPREVIEWS_PACKAGE_URL = + "https://github.com/getsentry/SnapshotPreviews"; + +export const SNAPSHOTPREVIEWS_MINIMUM_VERSION = "0.17.0"; + +export const SNAPSHOTPREVIEWS_SNAPSHOT_TESTS_PRODUCT = "SnapshottingTests"; + +export const SNAPSHOTPREVIEWS_PREFERENCES_PRODUCT = "SnapshotPreferences"; diff --git a/packages/cli/src/lib/wizard/apple/snapshots/snapshots-cli-preflight.ts b/packages/cli/src/lib/wizard/apple/snapshots/snapshots-cli-preflight.ts new file mode 100644 index 000000000..99dc87c55 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/snapshots-cli-preflight.ts @@ -0,0 +1,147 @@ +/** + * Print how to export SwiftUI preview snapshots with `xcodebuild` and upload + * them with `sentry snapshots upload`, or the project's Fastlane lane when it + * has one. + * + * The wizard runs through `sentry`, whose `snapshots upload` is built in, so + * there is no CLI to check or install here: the upload runs later from the + * user's terminal or CI. + */ + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { sentry } from "../../../app-identity.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; +import { fastFile } from "../fastlane.js"; + +type SnapshotVerificationGuidance = { + appId?: string | undefined; + hostedTestTargetName: string; + projectDir: string; + projectPath: string; + schemeName?: string | undefined; + snapshotTestClassName: string; +}; + +/** Print the snapshot export and upload commands for the project. */ +export function printSnapshotsUploadSetup({ + projectDir, + verificationGuidance, +}: { + projectDir: string; + verificationGuidance: SnapshotVerificationGuidance; +}): void { + printSnapshotsUploadGuidance({ + fastlaneGuidance: getSnapshotFastlaneGuidance(projectDir), + verificationGuidance, + }); +} + +export function getSnapshotFastlaneGuidance(projectDir: string) { + const fastfilePath = fastFile(projectDir) ?? undefined; + if (!fastfilePath) { + return { + hasUploadLane: false, + hasSentryUploadAction: false, + }; + } + + let contents: string; + try { + contents = readFileSync(fastfilePath, "utf8"); + } catch (error) { + // An unreadable Fastfile only means no Fastlane guidance; say so and go on. + debug(error); + clack.log.warn( + `Could not read the Fastfile at ${fastfilePath}. Skipping Fastlane snapshots upload detection.`, + ); + return { + hasUploadLane: false, + hasSentryUploadAction: false, + }; + } + + return { + fastfilePath, + hasUploadLane: /lane\s+:upload_sentry_snapshots\b/.test(contents), + hasSentryUploadAction: /\bsentry_upload_snapshots\s*\(/.test(contents), + }; +} + +function printSnapshotsUploadGuidance({ + fastlaneGuidance, + verificationGuidance, +}: { + fastlaneGuidance: ReturnType; + verificationGuidance: SnapshotVerificationGuidance; +}): void { + if (fastlaneGuidance.fastfilePath && fastlaneGuidance.hasUploadLane) { + clack.log.info( + [ + "Detected existing Fastlane snapshots upload support.", + buildSnapshotExportCommand(verificationGuidance), + "Then verify upload with:", + 'bundle exec fastlane ios upload_sentry_snapshots path: "$PWD/snapshot-images"', + ].join("\n"), + ); + return; + } + + if (fastlaneGuidance.fastfilePath && fastlaneGuidance.hasSentryUploadAction) { + clack.log.info( + [ + "Detected a Fastlane lane that calls sentry_upload_snapshots.", + "After exporting snapshots, run that existing lane with your snapshot image path.", + "If you are unsure which lane to use, fall back to the upload command below.", + ].join("\n"), + ); + } + + clack.log.info( + [ + buildSnapshotExportCommand(verificationGuidance), + "", + "After SnapshotPreviews exports images, verify local upload with:", + // `sentry` reads the org and project from SENTRY_ORG and SENTRY_PROJECT, + // or from .sentryclirc; `snapshots upload` has no flags for them. + "SENTRY_ORG=your-org SENTRY_PROJECT=your-ios-project \\", + sentry`snapshots upload "$PWD/snapshot-images" \\`, + verificationGuidance.appId + ? ` --app-id ${verificationGuidance.appId}` + : " --app-id YOUR_APP_BUNDLE_ID # replace with your app bundle identifier", + "", + `Auth comes from \`${sentry`auth login`}\`, SENTRY_AUTH_TOKEN, or a .sentryclirc file. In CI, set SENTRY_AUTH_TOKEN, SENTRY_ORG, and SENTRY_PROJECT, and SENTRY_URL for self-hosted Sentry. CI workflow setup is documented at https://docs.sentry.io/platforms/apple/snapshots/#step-3-integrate-into-ci; this wizard does not write workflow files.`, + ].join("\n"), + ); +} + +function buildSnapshotExportCommand( + guidance: SnapshotVerificationGuidance, +): string { + return [ + `From ${quoteShell(guidance.projectDir)}, export snapshots with:`, + 'TEST_RUNNER_SNAPSHOTS_EXPORT_DIR="$PWD/snapshot-images" \\', + "xcodebuild test \\", + ` -project ${quoteShell( + path.relative(guidance.projectDir, guidance.projectPath) || + guidance.projectPath, + )} \\`, + ` -scheme ${ + guidance.schemeName ? quoteShell(guidance.schemeName) : "" + } \\`, + " -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \\", + ` -only-testing:${quoteShell( + `${guidance.hostedTestTargetName}/${guidance.snapshotTestClassName}`, + )} \\`, + " CODE_SIGNING_ALLOWED=NO \\", + " | xcpretty", + ].join("\n"); +} + +function quoteShell(value: string): string { + return /^[A-Za-z0-9_./:-]+$/.test(value) + ? value + : `'${value.replace(/'/g, "'\\''")}'`; +} diff --git a/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts b/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts new file mode 100644 index 000000000..5e683ef4c --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts @@ -0,0 +1,102 @@ +/** + * Read the few values the Apple Snapshots wizard needs from Xcode's XML + * files: the `BlueprintName` attributes under a scheme's ``, and + * the `` texts of `xcschememanagement.plist`. + * + * This is a scanner for those shapes, not a general XML parser: it ignores + * comments, CDATA sections and processing instructions, and expects the + * element it extracts not to nest inside itself (true for `TestAction`). + */ + +/** Matches comments, CDATA sections, and `` / `` declarations. */ +const IGNORED_MARKUP_RE = + /||<[?!][^>]*>/g; + +/** The five predefined XML entities plus numeric character references. */ +const ENTITY_RE = /&(?:#(\d+)|#x([\da-f]+)|(amp|lt|gt|quot|apos));/gi; + +const NAMED_ENTITIES: Record = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", +}; + +/** Escape `value` for use inside a regular expression. */ +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Decode XML entity and character references in `value`. */ +export function decodeXmlEntities(value: string): string { + return value.replace( + ENTITY_RE, + (match, decimal?: string, hex?: string, named?: string) => { + if (decimal) { + return String.fromCodePoint(Number.parseInt(decimal, 10)); + } + if (hex) { + return String.fromCodePoint(Number.parseInt(hex, 16)); + } + return NAMED_ENTITIES[named?.toLowerCase() ?? ""] ?? match; + }, + ); +} + +/** + * `xml` without comments, CDATA sections and declarations. Strips until + * nothing changes, so removing one span can't leave another behind, such as + * the `` that `<!-- … -->` turns into. + */ +function stripIgnoredMarkup(xml: string): string { + let previous: string; + let stripped = xml; + do { + previous = stripped; + stripped = previous.replace(IGNORED_MARKUP_RE, ""); + } while (stripped !== previous); + return stripped; +} + +/** + * The markup between the first `` and its ``, or `""` for a + * self-closing ``. `undefined` when there is no such element. + */ +export function getElementContent( + xml: string, + name: string, +): string | undefined { + const tag = escapeRegExp(name); + const match = new RegExp( + `<${tag}(?:\\s[^>]*?)?(?:/>|>([\\s\\S]*?))`, + ).exec(stripIgnoredMarkup(xml)); + if (!match) { + return undefined; + } + return match[1] ?? ""; +} + +/** Every value of the attribute `attribute`, on any element in `xml`. */ +export function getAttributeValues(xml: string, attribute: string): string[] { + const re = new RegExp( + `\\s${escapeRegExp(attribute)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, + "g", + ); + const values: string[] = []; + for (const tag of stripIgnoredMarkup(xml).match(/<[^>]+>/g) ?? []) { + for (const match of tag.matchAll(re)) { + values.push(decodeXmlEntities(match[1] ?? match[2] ?? "")); + } + } + return values; +} + +/** The text of every `text` element in `xml`. */ +export function getElementTexts(xml: string, name: string): string[] { + const tag = escapeRegExp(name); + const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([^<]*)`, "g"); + return [...stripIgnoredMarkup(xml).matchAll(re)].map((match) => + decodeXmlEntities(match[1] ?? ""), + ); +} diff --git a/packages/cli/src/lib/wizard/apple/templates.ts b/packages/cli/src/lib/wizard/apple/templates.ts new file mode 100644 index 000000000..fbd419047 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/templates.ts @@ -0,0 +1,138 @@ +/** + * The Xcode build phase that uploads debug symbols with `sentry debug-files + * upload`. Xcode doesn't use the user's shell `PATH`, so the script adds the + * standalone installer's and Homebrew's directories before looking for + * `sentry`. Without an installed `sentry`, it runs the CLI from npm with + * `npx`, which downloads it on the first build. + * + * The upload passes no `--org` or `--project`: `sentry` reads them from + * `SENTRY_ORG` and `SENTRY_PROJECT`, which the script exports because CI has + * no `.sentryclirc` (it is gitignored). Upload failures are Xcode warnings, + * never build failures. + */ +export function getRunScriptTemplate( + orgSlug: string, + projectSlug: string, + uploadSource: boolean, +): string { + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- Xcode runs this script with the installed `sentry`, not the process running the wizard. + return `# This script is responsible for uploading debug symbols and source context for Sentry. +# Xcode doesn't use your shell's PATH; add the Sentry CLI installer's and Homebrew's directories. +export PATH="$HOME/.local/bin:$HOME/bin:/opt/homebrew/bin:/usr/local/bin:$PATH" + +export SENTRY_ORG=${orgSlug} +export SENTRY_PROJECT=${projectSlug} +# The check skips unrelated sentry binaries, such as the self-hosted Sentry server's. +if sentry debug-files --help >/dev/null 2>&1; then + set -- sentry +elif command -v npx >/dev/null 2>&1; then + # No installed Sentry CLI: run it from npm, downloaded on the first build. + set -- npx --yes sentry +else + echo "warning: Sentry CLI not installed. Install it with: curl https://cli.sentry.dev/install -fsS | bash (see https://cli.sentry.dev/getting-started/)" + exit 0 +fi +if ! ERROR=$("$@" debug-files upload ${ + uploadSource ? "--include-sources " : "" + }"$DWARF_DSYM_FOLDER_PATH" 2>&1 >/dev/null); then + echo "warning: sentry - $ERROR" +fi +`; +} + +/** + * Whether `shellScript` is a Sentry debug-file upload build phase: one that + * runs `debug-files upload` (the wizard's, which picks `sentry` or `npx + * sentry` first), or an older one that runs `sentry-cli`. + */ +export function isSentryUploadScript(shellScript: string): boolean { + return ( + shellScript.includes("sentry-cli") || + /\bdebug-files\s+upload\b/.test(shellScript) + ); +} + +export const scriptInputPath = + '"${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}"'; + +export function getSwiftSnippet(dsn: string, enableLogs: boolean): string { + let snippet = ` SentrySDK.start { options in + options.dsn = "${dsn}" + + // Adds IP for users. + // For more information, visit: https://docs.sentry.io/platforms/apple/data-management/data-collected/ + options.sendDefaultPii = true + + // Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring. + // We recommend adjusting this value in production. + options.tracesSampleRate = 1.0 + + // Configure profiling. Visit https://docs.sentry.io/platforms/apple/profiling/ to learn more. + options.configureProfiling = { + $0.sessionSampleRate = 1.0 // We recommend adjusting this value in production. + $0.lifecycle = .trace + } + + // Uncomment the following lines to add more data to your events + // options.attachScreenshot = true // This adds a screenshot to the error events + // options.attachViewHierarchy = true // This adds the view hierarchy to the error events`; + + if (enableLogs) { + snippet += ` + + // Enable experimental logging features + options.experimental.enableLogs = true`; + } + + snippet += ` + } + // Remove the next line after confirming that your Sentry integration is working. + SentrySDK.capture(message: "This app uses Sentry! :)")\n`; + + return snippet; +} + +export function getObjcSnippet(dsn: string, enableLogs: boolean): string { + let snippet = ` [SentrySDK startWithConfigureOptions:^(SentryOptions * options) { + options.dsn = @"${dsn}"; + + // Adds IP for users. + // For more information, visit: https://docs.sentry.io/platforms/apple/data-management/data-collected/ + options.sendDefaultPii = YES; + + // Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring. + // We recommend adjusting this value in production. + options.tracesSampleRate = @1.0; + + // Configure profiling. Visit https://docs.sentry.io/platforms/apple/profiling/ to learn more. + options.configureProfiling = ^(SentryProfileOptions *profiling) { + profiling.sessionSampleRate = 1.0; // We recommend adjusting this value in production. + profiling.lifecycle = SentryProfilingLifecycleTrace; + }; + + //Uncomment the following lines to add more data to your events + //options.attachScreenshot = YES; //This will add a screenshot to the error events + //options.attachViewHierarchy = YES; //This will add the view hierarchy to the error events`; + + if (enableLogs) { + snippet += ` + + // Enable experimental logging features + options.experimental.enableLogs = YES;`; + } + + snippet += ` + }]; + //Remove the next line after confirming that your Sentry integration is working. + [SentrySDK captureMessage:@"This app uses Sentry!"];\n`; + + return snippet; +} + +export function getFastlaneSnippet(org: string, project: string): string { + return ` sentry_debug_files_upload( + org_slug: '${org}', + project_slug: '${project}', + include_sources: true + )`; +} diff --git a/packages/cli/src/lib/wizard/apple/xcode-manager.ts b/packages/cli/src/lib/wizard/apple/xcode-manager.ts new file mode 100644 index 000000000..03fd83c77 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/xcode-manager.ts @@ -0,0 +1,2123 @@ +/** + * Read and change an Xcode project (`project.pbxproj`) through the `xcode` + * package: targets, build settings, Swift packages, build phases, and the + * files each target compiles. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { existsSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { lt, valid } from "semver"; +import { debug } from "../utils/debug.js"; +import type { SentryProjectData } from "../utils/types.js"; +import { + getRunScriptTemplate, + isSentryUploadScript, + scriptInputPath, +} from "./templates.js"; + +import { + project as createXcodeProject, + type PBXFileReference, + type PBXFileSystemSynchronizedBuildFileExceptionSet, + type PBXSourcesBuildPhase, + type PBXFileSystemSynchronizedRootGroup, + type PBXGroup, + type PBXNativeTarget, + type PBXObjects, + type PBXShellScriptBuildPhase, + type Project, + type XCConfigurationList, +} from "xcode"; +import { MacOSSystemHelpers } from "./macos-system-helper.js"; +import { type XcodeProjectObjectWithId } from "./xcode-project-object-with-id.js"; + +interface ProjectFile { + key?: string | undefined; + name: string; + path: string; +} + +export type SwiftPackageSpec = { + repositoryURL: string; + requirement: { + kind: "upToNextMajorVersion"; + minimumVersion: string; + }; + commentName: string; +}; + +export type SwiftPackageProductSpec = { + package: SwiftPackageSpec; + productName: string; +}; + +const XCODE_APPLICATION_PRODUCT_TYPE = "com.apple.product-type.application"; +const XCODE_UNIT_TEST_PRODUCT_TYPE = "com.apple.product-type.bundle.unit-test"; + +function unquote(value: unknown): string { + return typeof value === "string" ? value.replace(/"/g, "") : ""; +} + +/** + * `value` as a quoted `project.pbxproj` string. Backslashes are escaped + * before quotes, so a backslash in `value` can't end the string early. + */ +function quotePbxString(value: string): string { + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function stripAppExtension(value: string | undefined): string | undefined { + return value?.endsWith(".app") ? value.slice(0, -".app".length) : value; +} + +function resolveBuildSettingValue( + value: unknown, + targetName: string, +): string | undefined { + const resolvedValue = unquote(value) + .replace(/\$\(TARGET_NAME\)/g, targetName) + .replace(/\$\{TARGET_NAME\}/g, targetName) + .trim(); + + return resolvedValue && !resolvedValue.includes("$") + ? resolvedValue + : undefined; +} + +function uniqueStrings(values: Array): string[] { + return [...new Set(values.filter(Boolean))] as string[]; +} + +function testHostReferencesApplication( + testHost: unknown, + appHostCandidates: ApplicationHostCandidates, +): boolean { + const resolvedTestHost = unquote(testHost); + if (!resolvedTestHost) { + return false; + } + + const referencesAppBundle = appHostCandidates.bundleNames.some((bundleName) => + containsPathSegment(resolvedTestHost, `${bundleName}.app`), + ); + if (!referencesAppBundle) { + return false; + } + + return appHostCandidates.executableNames.some((executableName) => + containsPathSegment(resolvedTestHost, executableName), + ); +} + +function containsPathSegment(value: string, segment: string): boolean { + return new RegExp(`(^|/)${escapeRegExp(segment)}(/|$)`).test(value); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function normalizeSwiftPackageRepositoryURL(value: unknown): string { + return unquote(value).replace(/\/+$/, ""); +} + +function shouldUpdatePackageRequirement( + existingRequirement: unknown, + requestedRequirement: SwiftPackageSpec["requirement"], +): boolean { + if (!existingRequirement || typeof existingRequirement !== "object") { + return true; + } + + const requirement = existingRequirement as Record; + if (requirement["kind"] !== requestedRequirement.kind) { + return true; + } + + const existingMinimumVersion = requirement["minimumVersion"]; + if (typeof existingMinimumVersion !== "string") { + return true; + } + + const existingVersion = valid(existingMinimumVersion); + const requestedVersion = valid(requestedRequirement.minimumVersion); + if (!existingVersion || !requestedVersion) { + return existingMinimumVersion !== requestedRequirement.minimumVersion; + } + + return lt(existingVersion, requestedVersion); +} + +function setDebugInformationFormatAndSandbox( + proj: Project, + targetName: string, +): void { + const xcObjects = proj.hash.project.objects; + if (!xcObjects.PBXNativeTarget) { + xcObjects.PBXNativeTarget = {}; + } + const targetKey = Object.keys(xcObjects.PBXNativeTarget).find((key) => { + const value = xcObjects.PBXNativeTarget?.[key]; + return ( + !key.endsWith("_comment") && + typeof value !== "string" && + value?.name === targetName + ); + }); + const target = + targetKey === undefined + ? undefined + : (xcObjects.PBXNativeTarget[targetKey] as PBXNativeTarget | undefined); + + if (!xcObjects.XCBuildConfiguration) { + xcObjects.XCBuildConfiguration = {}; + } + if (!xcObjects.XCConfigurationList) { + xcObjects.XCConfigurationList = {}; + } + const buildConfigurationListId = target?.buildConfigurationList ?? ""; + const configurationList = xcObjects.XCConfigurationList[ + buildConfigurationListId + ] as XCConfigurationList | undefined; + const buildListConfigurationIds = + configurationList?.buildConfigurations ?? []; + for (const buildListConfigId of buildListConfigurationIds) { + const config = xcObjects.XCBuildConfiguration[buildListConfigId.value]; + if (config === undefined || typeof config === "string") { + // Ignore comments + continue; + } + + const buildSettings = config.buildSettings ?? {}; + buildSettings["DEBUG_INFORMATION_FORMAT"] = '"dwarf-with-dsym"'; + buildSettings["ENABLE_USER_SCRIPT_SANDBOXING"] = '"NO"'; + + config.buildSettings = buildSettings; + xcObjects.XCBuildConfiguration[buildListConfigId.value] = config; + } +} + +export type SwiftPackageProductLinkOptions = { + product: SwiftPackageProductSpec; + existingFrameworkComment?: string | undefined; + successMessage?: string | undefined; +}; + +type ApplicationHostCandidates = { + bundleNames: string[]; + executableNames: string[]; +}; + +export class XcodeProject { + /** + * The directory where the Xcode project is located. + */ + baseDir: string; + + /** + * The path to the `.xcodeproj` directory. + */ + xcodeprojPath: string; + + /** + * The path to the `project.pbxproj` file. + */ + pbxprojPath: string; + + /** + * The Xcode project object. + */ + project: Project; + + objects: PBXObjects; + + /** + * Creates a new XcodeProject instance, a wrapper around the Xcode project file `.xcodeproj/project.pbxproj`. + * + * @param projectPath - The path to the Xcode project file + */ + public constructor(projectPath: string) { + this.pbxprojPath = projectPath; + this.xcodeprojPath = path.dirname(projectPath); + this.baseDir = path.dirname(this.xcodeprojPath); + + this.project = createXcodeProject(projectPath); + this.project.parseSync(); + this.objects = this.project.hash.project.objects; + } + + public getAllTargets(): string[] { + const targets = this.objects.PBXNativeTarget ?? {}; + return Object.keys(targets) + .filter((key) => { + const value = targets[key]; + return ( + !key.endsWith("_comment") && + value !== undefined && + typeof value !== "string" && + unquote(value.productType).startsWith(XCODE_APPLICATION_PRODUCT_TYPE) + ); + }) + .map((key) => { + return (targets[key] as PBXNativeTarget).name; + }); + } + + public getUnitTestTargetNames(): string[] { + const targets = this.objects.PBXNativeTarget ?? {}; + return Object.keys(targets) + .filter((key) => { + const value = targets[key]; + return this.isUnitTestTargetEntry(key, value); + }) + .map((key) => { + return (targets[key] as PBXNativeTarget).name; + }); + } + + public getHostedUnitTestTargetNames(): string[] { + const targets = this.objects.PBXNativeTarget ?? {}; + return Object.keys(targets) + .filter((key) => { + const value = targets[key]; + return ( + this.isUnitTestTargetEntry(key, value) && + this.getTargetBuildSettings(value).some((buildSettings) => + Boolean(unquote(buildSettings["TEST_HOST"]).trim()), + ) + ); + }) + .map((key) => { + return (targets[key] as PBXNativeTarget).name; + }); + } + + public getHostedUnitTestTargetNamesForApplicationTarget( + appTargetName: string, + ): string[] { + const appTarget = this.findNativeTargetByName(appTargetName); + if (!appTarget) { + return []; + } + + const appHostCandidates = this.getApplicationHostCandidates(appTarget); + const targets = this.objects.PBXNativeTarget ?? {}; + return Object.keys(targets) + .filter((key) => { + const value = targets[key]; + return ( + !key.endsWith("_comment") && + value !== undefined && + typeof value !== "string" && + unquote(value.productType) === XCODE_UNIT_TEST_PRODUCT_TYPE && + this.getTargetBuildSettings(value).some((buildSettings) => + testHostReferencesApplication( + buildSettings["TEST_HOST"], + appHostCandidates, + ), + ) + ); + }) + .map((key) => { + return (targets[key] as PBXNativeTarget).name; + }); + } + + public getBundleIdentifierForTarget(targetName: string): string | undefined { + const target = this.findNativeTargetByName(targetName); + if (!target) { + return undefined; + } + + return this.getTargetBuildSettings(target.obj) + .map((buildSettings) => { + return unquote(buildSettings["PRODUCT_BUNDLE_IDENTIFIER"]); + }) + .find(Boolean); + } + + /** + * Idempotently links a Swift package product to one target dependency list + * and Frameworks build phase. Returns whether the pbxproj graph changed and + * whether the product is linked after the operation. + */ + public ensureSwiftPackageProductLinked( + targetName: string, + product: SwiftPackageProductSpec, + ): { changed: boolean; linked: boolean } { + const target = this.findNativeTargetByName(targetName); + if (!target) { + debug(`Target not found: ${targetName}`); + return { changed: false, linked: false }; + } + + const frameworksBuildPhase = this.findFrameworksBuildPhaseInTarget( + target.obj, + ); + if (!frameworksBuildPhase) { + debug(`Frameworks build phase not found for target: ${targetName}`); + return { changed: false, linked: false }; + } + + let changed = false; + + // Ensure the remote Swift package object exists. + const packageReference = this.ensureSwiftPackageReference(product.package); + changed = packageReference.changed || changed; + + // Attach the Swift package object to the root Xcode project. + changed = + this.ensureProjectSwiftPackageReference( + packageReference.packageRefId, + product.package.commentName, + ) || changed; + + // Ensure the package product dependency object exists. + const productDependency = this.ensureSwiftPackageProductDependency( + packageReference.packageRefId, + product, + ); + changed = productDependency.changed || changed; + + if (!target.obj.packageProductDependencies) { + target.obj.packageProductDependencies = []; + } + + // Attach the package product dependency to the selected target. + if ( + !target.obj.packageProductDependencies.some((dependency) => { + return dependency.value === productDependency.productDependencyId; + }) + ) { + target.obj.packageProductDependencies.push({ + value: productDependency.productDependencyId, + comment: product.productName, + }); + changed = true; + } + + // Link the package product in the target Frameworks build phase. + changed = + this.ensureFrameworksBuildFile( + frameworksBuildPhase, + productDependency.productDependencyId, + product, + ) || changed; + + return { changed, linked: true }; + } + + public updateXcodeProject( + sentryProject: SentryProjectData, + target: string, + swiftPackageProduct?: SwiftPackageProductLinkOptions, + uploadSource = true, + ): void { + this.addUploadSymbolsScript({ + sentryProject, + targetName: target, + uploadSource, + }); + if (uploadSource) { + setDebugInformationFormatAndSandbox(this.project, target); + } + if ( + swiftPackageProduct && + !( + swiftPackageProduct.existingFrameworkComment && + this.hasFrameworkBuildFileCommentInTarget( + target, + swiftPackageProduct.existingFrameworkComment, + ) + ) + ) { + const result = this.ensureSwiftPackageProductLinked( + target, + swiftPackageProduct.product, + ); + if (result.changed && swiftPackageProduct.successMessage) { + clack.log.step(swiftPackageProduct.successMessage); + } + } + this.write(); + } + + addUploadSymbolsScript({ + sentryProject, + targetName, + uploadSource, + }: { + sentryProject: SentryProjectData; + targetName: string; + uploadSource: boolean; + }): void { + const xcObjects = this.project.hash.project.objects; + if (!xcObjects.PBXNativeTarget) { + xcObjects.PBXNativeTarget = {}; + } + const targetKey = Object.keys(xcObjects.PBXNativeTarget).find((key) => { + const value = xcObjects.PBXNativeTarget?.[key]; + return ( + !key.endsWith("_comment") && + typeof value !== "string" && + value?.name === targetName + ); + }); + const target = + targetKey === undefined + ? undefined + : (xcObjects.PBXNativeTarget[targetKey] as PBXNativeTarget | undefined); + if (!target || targetKey === undefined) { + debug(`Target not found: ${targetName}`); + return; + } + + // Generate the new script content + const shellScript = getRunScriptTemplate( + sentryProject.organization.slug, + sentryProject.slug, + uploadSource, + ); + + if (!xcObjects.PBXShellScriptBuildPhase) { + xcObjects.PBXShellScriptBuildPhase = {}; + } + + // Look for existing Sentry build phase in the current target + let existingSentryBuildPhaseId: string | undefined; + let existingSentryBuildPhase: PBXShellScriptBuildPhase | undefined; + + // Check target's build phases for an existing Sentry upload script, from this wizard or an older sentry-cli one + if (target.buildPhases) { + for (const phase of target.buildPhases) { + const buildPhase = xcObjects.PBXShellScriptBuildPhase[phase.value]; + if ( + typeof buildPhase === "object" && + buildPhase.shellScript !== undefined && + isSentryUploadScript(buildPhase.shellScript) + ) { + existingSentryBuildPhaseId = phase.value; + existingSentryBuildPhase = buildPhase; + break; + } + } + } + + // Clean up orphaned build phase references that may exist from previous runs + // Find all build phase IDs that are referenced in targets but don't exist in PBXShellScriptBuildPhase + const orphanedBuildPhaseIds: string[] = []; + for (const targetKey in xcObjects.PBXNativeTarget) { + const targetValue = xcObjects.PBXNativeTarget[targetKey]; + if (typeof targetValue === "object" && targetValue.buildPhases) { + for (const phase of targetValue.buildPhases) { + // Check if this is a shell script build phase that doesn't exist + if ( + !xcObjects.PBXShellScriptBuildPhase[phase.value] && + phase.comment?.includes("Upload Debug Symbols to Sentry") + ) { + orphanedBuildPhaseIds.push(phase.value); + } + } + } + } + + // Remove orphaned build phase references from all targets + if (orphanedBuildPhaseIds.length > 0) { + for (const targetKey in xcObjects.PBXNativeTarget) { + const targetValue = xcObjects.PBXNativeTarget[targetKey]; + if (typeof targetValue === "object" && targetValue.buildPhases) { + targetValue.buildPhases = targetValue.buildPhases.filter((phase) => { + return !orphanedBuildPhaseIds.includes(phase.value); + }); + } + } + } + + if (existingSentryBuildPhaseId && existingSentryBuildPhase) { + // Update existing build phase instead of adding a new one + // This call is idempotent, so it will not add a new build phase if it already exists + this.updateScriptBuildPhase(existingSentryBuildPhaseId, shellScript, [ + scriptInputPath, + ]); + clack.log.step( + `Updated existing Sentry upload script for "${targetName}" build phase`, + ); + } else { + // Add new build phase to the target + this.addScriptBuildPhase( + targetKey, + "Upload Debug Symbols to Sentry", + shellScript, + [scriptInputPath], + ); + clack.log.step( + `Added Sentry upload script to "${targetName}" build phase`, + ); + } + } + + public write(): void { + const newContent = this.project.writeSync(); + writeFileSync(this.pbxprojPath, newContent); + } + + public getSynchronizedRootGroupPathsForTarget(targetName: string): string[] { + const nativeTarget = this.findNativeTargetByName(targetName); + if (!nativeTarget) { + return []; + } + + return (nativeTarget.obj.fileSystemSynchronizedGroups ?? []).reduce( + (groupPaths, group) => { + const groupObj = + this.objects.PBXFileSystemSynchronizedRootGroup?.[group.value]; + if (!groupObj || typeof groupObj !== "object") { + return groupPaths; + } + + const groupPath = this.resolveAbsolutePathOfSynchronizedRootGroup({ + id: group.value, + obj: groupObj, + }); + if (!groupPath) { + return groupPaths; + } + + return [...groupPaths, groupPath]; + }, + new Array(), + ); + } + + /** + * Ensures a Swift file is compiled by a target, either through an Xcode + * synchronized root group or an explicit Sources build phase entry. + */ + public addSwiftSourceFileToTarget(args: { + targetName: string; + filePath: string; + }): { changed: boolean; included: boolean } { + const nativeTarget = this.findNativeTargetByName(args.targetName); + const defaultResult = { changed: false, included: false }; + if (!nativeTarget) { + debug(`Target not found: ${args.targetName}`); + return defaultResult; + } + + const absoluteFilePath = args.filePath; + if ( + this.isFileIncludedBySynchronizedRootGroup(nativeTarget, absoluteFilePath) + ) { + return { + changed: false, + included: true, + }; + } + + const sourceBuildPhase = this.findSourceBuildPhaseInTarget( + nativeTarget.obj, + ); + if (!sourceBuildPhase) { + debug(`Sources build phase not found for target: ${args.targetName}`); + return defaultResult; + } + + const fileReference = this.ensureSwiftFileReference(absoluteFilePath); + const sourceBuildPhaseFiles = sourceBuildPhase.obj.files ?? []; + const existingBuildFileReference = sourceBuildPhaseFiles.find((file) => { + const buildFile = this.objects.PBXBuildFile?.[file.value]; + return ( + buildFile && + typeof buildFile !== "string" && + buildFile.fileRef === fileReference.fileReferenceId + ); + }); + + if (existingBuildFileReference) { + return { + changed: fileReference.changed, + included: true, + }; + } + + if (!this.objects.PBXBuildFile) { + this.objects.PBXBuildFile = {}; + } + + const buildFileId = this.project.generateUuid(); + const fileName = path.basename(absoluteFilePath); + this.objects.PBXBuildFile[buildFileId] = { + isa: "PBXBuildFile", + fileRef: fileReference.fileReferenceId, + fileRef_comment: fileName, + }; + this.objects.PBXBuildFile[`${buildFileId}_comment`] = + `${fileName} in Sources`; + + sourceBuildPhase.obj.files = [ + ...sourceBuildPhaseFiles, + { + value: buildFileId, + comment: `${fileName} in Sources`, + }, + ]; + + return { changed: true, included: true }; + } + + /** + * Retrieves all source files associated with a specific target in the Xcode project. + * This is used to find files where we can inject Sentry initialization code. + * + * @param targetName - The name of the target to get files for + * @returns An array of absolute file paths for the target's source files, or undefined if target not found + */ + public getSourceFilesForTarget(targetName: string): string[] | undefined { + // ## Summary how Xcode Projects are structured: + // - Every Xcode Project has exactly one main group of type `PBXGroup` + // - The main group contains a list of children identifiers + // - Each child can be a `PBXGroup`, a `PBXFileReference` or a `PBXFileSystemSynchronizedRootGroup` + // - Each `PBXGroup` has a list of children identifiers which again can be `PBXGroup`, `PBXFileReference` or `PBXFileSystemSynchronizedRootGroup` + // - The target defines the list of `fileSystemSynchronizedGroups` which are `PBXFileSystemSynchronizedRootGroup` to be included in the build phase + // - The `PBXFileSystemSynchronizedRootGroup` has a list of `exceptions` which are `PBXFileSystemSynchronizedBuildFileExceptionSet` + // - Each `PBXFileSystemSynchronizedBuildFileExceptionSet` represents a folder to be excluded from the build. + // - The `PBXFileSystemSynchronizedBuildFileExceptionSet` has a list of `membershipExceptions` which are files to be excluded from being excluded, therefore included in the build. + // - The Xcode project has a build phase `PBXSourcesBuildPhase` which has a list of `files` which are `PBXBuildFile` + // - A file which is not part of a `PBXFileSystemSynchronizedRootGroup` must be added to the `files` list of the `PBXSourcesBuildPhase` build phase + // - Nested subfolders in `fileSystemSynchronizedGroups` are not declared but recursively included + // + // Based on the findings above the files included in the build phase are: + // - All files in the `files` of the `PBXSourcesBuildPhase` build phase `Sources` of the target + // - All files in directories of the `fileSystemSynchronizedGroups` of the target + // - Excluding all files in the `exceptions` of the `PBXFileSystemSynchronizedRootGroup` of the target + // - Including all files in the `membershipExceptions` of the `PBXFileSystemSynchronizedBuildFileExceptionSet` of the target + const nativeTarget = this.findNativeTargetByName(targetName); + if (!nativeTarget) { + debug("Target not found: " + targetName); + return undefined; + } + + const filesInBuildPhase = this.findFilesInSourceBuildPhase(nativeTarget); + debug( + `Found ${filesInBuildPhase.length} files in build phase for target: ${targetName}`, + ); + + const filesInSynchronizedRootGroups = + this.findFilesInSynchronizedRootGroups(nativeTarget); + debug( + `Found ${filesInSynchronizedRootGroups.length} files in synchronized root groups for target: ${targetName}`, + ); + return [...filesInBuildPhase, ...filesInSynchronizedRootGroups]; + } + + private isUnitTestTargetEntry( + key: string, + value: PBXNativeTarget | string | undefined, + ): value is PBXNativeTarget { + return ( + !key.endsWith("_comment") && + typeof value !== "string" && + value !== undefined && + unquote(value.productType) === XCODE_UNIT_TEST_PRODUCT_TYPE + ); + } + + private getTargetBuildSettings( + target: PBXNativeTarget, + ): Record[] { + const buildConfigurationListId = target.buildConfigurationList; + if (!buildConfigurationListId) { + return []; + } + + const configurationList = this.objects.XCConfigurationList?.[ + buildConfigurationListId + ] as XCConfigurationList | undefined; + if (!configurationList || typeof configurationList === "string") { + return []; + } + + return (configurationList.buildConfigurations ?? []).reduce( + (buildSettings, buildConfiguration) => { + const configuration = + this.objects.XCBuildConfiguration?.[buildConfiguration.value]; + if (!configuration || typeof configuration === "string") { + return buildSettings; + } + + return [...buildSettings, configuration.buildSettings ?? {}]; + }, + new Array>(), + ); + } + + private getApplicationHostCandidates( + target: XcodeProjectObjectWithId, + ): ApplicationHostCandidates { + const buildSettings = this.getTargetBuildSettings(target.obj); + const productReferencePath = this.getProductReferencePath(target.obj); + const productReferenceName = stripAppExtension(productReferencePath); + const targetProductName = resolveBuildSettingValue( + target.obj.productName, + target.obj.name, + ); + const buildSettingProductNames = buildSettings.flatMap((settings) => [ + resolveBuildSettingValue(settings["PRODUCT_NAME"], target.obj.name), + stripAppExtension( + resolveBuildSettingValue( + settings["FULL_PRODUCT_NAME"], + target.obj.name, + ), + ), + stripAppExtension( + resolveBuildSettingValue(settings["WRAPPER_NAME"], target.obj.name), + ), + ]); + const buildSettingExecutableNames = buildSettings.map((settings) => + resolveBuildSettingValue(settings["EXECUTABLE_NAME"], target.obj.name), + ); + + return { + bundleNames: uniqueStrings([ + target.obj.name, + targetProductName, + productReferenceName, + ...buildSettingProductNames, + ]), + executableNames: uniqueStrings([ + target.obj.name, + targetProductName, + productReferenceName, + ...buildSettingExecutableNames, + ]), + }; + } + + private getProductReferencePath(target: PBXNativeTarget): string | undefined { + if (!target.productReference) { + return undefined; + } + + const productReference = + this.objects.PBXFileReference?.[target.productReference]; + if (!productReference || typeof productReference === "string") { + return undefined; + } + + return unquote(productReference.path); + } + + private hasFrameworkBuildFileCommentInTarget( + targetName: string, + comment: string, + ): boolean { + const target = this.findNativeTargetByName(targetName); + if (!target) { + return false; + } + + const frameworksBuildPhase = this.findFrameworksBuildPhaseInTarget( + target.obj, + ); + return (frameworksBuildPhase?.files ?? []).some((framework) => { + return framework.comment === comment; + }); + } + + private ensureSwiftPackageReference(packageSpec: SwiftPackageSpec): { + packageRefId: string; + changed: boolean; + } { + if (!this.objects.XCRemoteSwiftPackageReference) { + this.objects.XCRemoteSwiftPackageReference = {}; + } + + const packageReferences = this.objects + .XCRemoteSwiftPackageReference as Record; + const requestedRepositoryURL = normalizeSwiftPackageRepositoryURL( + packageSpec.repositoryURL, + ); + const existingPackageReference = Object.entries(packageReferences).find( + ([id, value]) => { + if (id.endsWith("_comment") || typeof value !== "object") { + return false; + } + + const packageReference = value as Record; + return ( + normalizeSwiftPackageRepositoryURL( + packageReference["repositoryURL"], + ) === requestedRepositoryURL + ); + }, + ); + + if (existingPackageReference) { + const packageReference = existingPackageReference[1] as Record< + string, + unknown + >; + if ( + shouldUpdatePackageRequirement( + packageReference["requirement"], + packageSpec.requirement, + ) + ) { + packageReference["requirement"] = packageSpec.requirement; + return { packageRefId: existingPackageReference[0], changed: true }; + } + + return { packageRefId: existingPackageReference[0], changed: false }; + } + + const packageRefId = this.project.generateUuid(); + packageReferences[packageRefId] = { + isa: "XCRemoteSwiftPackageReference", + repositoryURL: `"${packageSpec.repositoryURL}"`, + requirement: packageSpec.requirement, + }; + packageReferences[`${packageRefId}_comment`] = + this.swiftPackageReferenceComment(packageSpec.commentName); + + return { packageRefId, changed: true }; + } + + private ensureProjectSwiftPackageReference( + packageRefId: string, + commentName: string, + ): boolean { + const xcodeProject = this.project.getFirstProject().firstProject as { + packageReferences?: { value: string; comment?: string }[]; + }; + if (!xcodeProject.packageReferences) { + xcodeProject.packageReferences = []; + } + + if ( + xcodeProject.packageReferences.some((packageReference) => { + return packageReference.value === packageRefId; + }) + ) { + return false; + } + + xcodeProject.packageReferences.push({ + value: packageRefId, + comment: this.swiftPackageReferenceComment(commentName), + }); + return true; + } + + private ensureSwiftPackageProductDependency( + packageRefId: string, + product: SwiftPackageProductSpec, + ): { productDependencyId: string; changed: boolean } { + if (!this.objects.XCSwiftPackageProductDependency) { + this.objects.XCSwiftPackageProductDependency = {}; + } + + const productDependencies = this.objects + .XCSwiftPackageProductDependency as Record; + const existingProductDependency = Object.entries(productDependencies).find( + ([id, value]) => { + if (id.endsWith("_comment") || typeof value !== "object") { + return false; + } + + const productDependency = value as Record; + return ( + productDependency["package"] === packageRefId && + unquote(productDependency["productName"]) === product.productName + ); + }, + ); + + if (existingProductDependency) { + return { + productDependencyId: existingProductDependency[0], + changed: false, + }; + } + + const productDependencyId = this.project.generateUuid(); + productDependencies[productDependencyId] = { + isa: "XCSwiftPackageProductDependency", + package: packageRefId, + package_comment: this.swiftPackageReferenceComment( + product.package.commentName, + ), + productName: product.productName, + }; + productDependencies[`${productDependencyId}_comment`] = product.productName; + + return { productDependencyId, changed: true }; + } + + private ensureFrameworksBuildFile( + frameworksBuildPhase: { + files?: { value: string; comment?: string }[]; + }, + productDependencyId: string, + product: SwiftPackageProductSpec, + ): boolean { + if (!this.objects.PBXBuildFile) { + this.objects.PBXBuildFile = {}; + } + + const existingFrameworkEntry = (frameworksBuildPhase.files ?? []).find( + (framework) => { + const buildFile = this.objects.PBXBuildFile?.[framework.value]; + return ( + buildFile && + typeof buildFile !== "string" && + buildFile.productRef === productDependencyId + ); + }, + ); + if (existingFrameworkEntry) { + return false; + } + + const buildFileId = this.project.generateUuid(); + this.objects.PBXBuildFile[buildFileId] = { + isa: "PBXBuildFile", + productRef: productDependencyId, + productRef_comment: product.productName, + }; + this.objects.PBXBuildFile[`${buildFileId}_comment`] = + `${product.productName} in Frameworks`; + + if (!frameworksBuildPhase.files) { + frameworksBuildPhase.files = []; + } + frameworksBuildPhase.files.push({ + value: buildFileId, + comment: `${product.productName} in Frameworks`, + }); + + return true; + } + + private findFrameworksBuildPhaseInTarget(target: PBXNativeTarget): + | { + files?: { value: string; comment?: string }[]; + } + | undefined { + for (const buildPhaseReference of target.buildPhases ?? []) { + const buildPhase = + this.objects.PBXFrameworksBuildPhase?.[buildPhaseReference.value]; + if (buildPhase && typeof buildPhase !== "string") { + return buildPhase; + } + } + + return undefined; + } + + private swiftPackageReferenceComment(commentName: string): string { + return `XCRemoteSwiftPackageReference "${commentName}"`; + } + + private isFileIncludedBySynchronizedRootGroup( + nativeTarget: XcodeProjectObjectWithId, + absoluteFilePath: string, + ): boolean { + return this.findFilesInSynchronizedRootGroups(nativeTarget).some( + (filePath) => filePath === absoluteFilePath, + ); + } + + private ensureSwiftFileReference(absoluteFilePath: string): { + fileReferenceId: string; + changed: boolean; + } { + if (!this.objects.PBXFileReference) { + this.objects.PBXFileReference = {}; + } + + const existingFileReference = Object.entries( + this.objects.PBXFileReference, + ).find(([id, fileReference]) => { + if (id.endsWith("_comment") || typeof fileReference !== "object") { + return false; + } + + const resolvedFilePath = this.resolveAbsolutePathOfFileReference({ + id, + obj: fileReference, + }); + return resolvedFilePath === absoluteFilePath; + }); + + if (existingFileReference) { + return { fileReferenceId: existingFileReference[0], changed: false }; + } + + const fileReferenceId = this.project.generateUuid(); + const fileName = path.basename(absoluteFilePath); + const relativePath = path.relative(this.baseDir, absoluteFilePath); + this.objects.PBXFileReference[fileReferenceId] = { + isa: "PBXFileReference", + lastKnownFileType: "sourcecode.swift", + path: relativePath, + sourceTree: "SOURCE_ROOT", + }; + this.objects.PBXFileReference[`${fileReferenceId}_comment`] = fileName; + + this.addFileReferenceToBestGroup( + fileReferenceId, + fileName, + absoluteFilePath, + ); + + return { fileReferenceId, changed: true }; + } + + private addFileReferenceToBestGroup( + fileReferenceId: string, + fileName: string, + absoluteFilePath: string, + ): void { + const parentDirectory = path.dirname(absoluteFilePath); + const parentGroup = + this.groups.find((group) => { + const groupPath = this.resolveAbsolutePathOfGroup(group); + return groupPath === parentDirectory; + }) ?? this.mainGroup; + + if (!parentGroup) { + return; + } + + if (!parentGroup.obj.children) { + parentGroup.obj.children = []; + } + + if ( + parentGroup.obj.children.some((child) => child.value === fileReferenceId) + ) { + return; + } + + parentGroup.obj.children.push({ + value: fileReferenceId, + comment: fileName, + }); + } + + private get mainGroup(): XcodeProjectObjectWithId | undefined { + const project = Object.entries(this.objects.PBXProject ?? {}).find( + ([id, candidate]) => { + return !id.endsWith("_comment") && typeof candidate === "object"; + }, + )?.[1]; + if (!project || typeof project !== "object") { + return undefined; + } + + const mainGroupId = (project as { mainGroup?: string }).mainGroup; + if (!mainGroupId) { + return undefined; + } + + const mainGroup = this.objects.PBXGroup?.[mainGroupId]; + if (!mainGroup || typeof mainGroup !== "object") { + return undefined; + } + + return { id: mainGroupId, obj: mainGroup }; + } + + // ================================ TARGET HELPERS ================================ + + /** + * Finds a native target by name. + * + * @param targetName - The name of the target to find + * @returns The native target, or undefined if the target is not found + */ + private findNativeTargetByName( + targetName: string, + ): XcodeProjectObjectWithId | undefined { + debug("Finding native target by name: " + targetName); + + if (!this.objects.PBXNativeTarget) { + debug("No native targets found"); + return undefined; + } + + const nativeTargets = Object.entries(this.objects.PBXNativeTarget); + for (const [key, target] of nativeTargets) { + // Ignore comments + if (key.endsWith("_comment") || typeof target === "string") { + continue; + } + + // Ignore targets that are not the target we are looking for + if (target.name !== targetName) { + continue; + } + debug("Found native target: " + targetName); + return { + id: key, + obj: target, + }; + } + + debug("Target not found: " + targetName); + return undefined; + } + + // ================================ BUILD PHASE HELPERS ================================ + + /** + * Finds the source build phase in a target. + * + * @param target - The target to find the source build phase in + * @returns The source build phase, or undefined if the target is not found or has no source build phase + */ + findSourceBuildPhaseInTarget( + target: PBXNativeTarget, + ): XcodeProjectObjectWithId | undefined { + debug(`Finding source build phase in target: ${target.name}`); + if (!target.buildPhases) { + debug("No build phases found for target: " + target.name); + return undefined; + } + for (const phase of target.buildPhases) { + const buildPhaseId = phase.value; + const buildPhase = this.objects.PBXSourcesBuildPhase?.[buildPhaseId]; + if (typeof buildPhase !== "object") { + // Ignore comments + continue; + } + debug( + `Found source build phase: ${buildPhaseId} for target: ${target.name}`, + ); + return { + id: buildPhaseId, + obj: buildPhase, + }; + } + + debug(`No source build phase found for target: ${target.name}`); + return undefined; + } + + /** + * Adds a new script build phase to the specified target. + * + * @param targetKey - The key of the target to add the build phase to + * @param name - The name of the build phase + * @param script - The shell script content + * @param inputPaths - Array of input paths for the script + * @returns The UUID of the created build phase + */ + addScriptBuildPhase( + targetKey: string, + name: string, + script: string, + inputPaths: string[] = [], + ): string { + const buildPhaseUuid = this.project.generateUuid(); + // Create the shell script build phase object + const buildPhase = { + isa: "PBXShellScriptBuildPhase" as const, + buildActionMask: 2147483647, + files: [], + inputPaths, + outputPaths: [], + runOnlyForDeploymentPostprocessing: 0, + shellPath: "/bin/sh", + shellScript: quotePbxString(script), + name: `"${name}"`, + }; + + // Add to PBXShellScriptBuildPhase section + if (!this.objects.PBXShellScriptBuildPhase) { + this.objects.PBXShellScriptBuildPhase = {}; + } + this.objects.PBXShellScriptBuildPhase[buildPhaseUuid] = buildPhase; + this.objects.PBXShellScriptBuildPhase[`${buildPhaseUuid}_comment`] = name; + + // Add to target's build phases + const target = this.objects.PBXNativeTarget?.[targetKey] as + | PBXNativeTarget + | undefined; + if (target?.buildPhases) { + target.buildPhases.push({ + value: buildPhaseUuid, + comment: name, + }); + } + + return buildPhaseUuid; + } + + /** + * Updates an existing script build phase. + * + * @param buildPhaseId - The UUID of the build phase to update + * @param script - The new shell script content + * @param inputPaths - Array of input paths for the script + */ + updateScriptBuildPhase( + buildPhaseId: string, + script: string, + inputPaths: string[] = [], + ): void { + const buildPhase = this.objects.PBXShellScriptBuildPhase?.[buildPhaseId]; + if (!buildPhase || typeof buildPhase === "string") { + debug(`Build phase not found: ${buildPhaseId}`); + return; + } + + buildPhase.shellScript = quotePbxString(script); + buildPhase.inputPaths = inputPaths; + buildPhase.shellPath = "/bin/sh"; + } + + // ================================ FILE HELPERS ================================ + + /** + * Finds all files in the source build phase of a target. + * + * @param nativeTarget - The target to find the files in + * @returns The files in the source build phase of the target, or an empty array if the target is not found or has no source build phase + */ + findFilesInSourceBuildPhase( + nativeTarget: XcodeProjectObjectWithId, + ): string[] { + debug( + "Finding files in source build phase for target: " + + nativeTarget.obj.name, + ); + const buildPhase = this.findSourceBuildPhaseInTarget(nativeTarget.obj); + if (!buildPhase) { + debug( + `Sources build phase not found for target: ${nativeTarget.obj.name}`, + ); + return []; + } + const buildPhaseFiles = buildPhase.obj.files; + if (!buildPhaseFiles) { + debug( + `No files found in sources build phase for target: ${nativeTarget.obj.name}`, + ); + return []; + } + if (!this.objects.PBXBuildFile) { + debug("PBXBuildFile is undefined"); + return []; + } + if (!this.objects.PBXFileReference) { + debug("PBXFileReference is undefined"); + return []; + } + + const result: string[] = []; + for (const file of buildPhaseFiles) { + debug(`Resolving build phase file: ${file.value}`); + // Find the related build file object + const buildFileObj = this.objects.PBXBuildFile[file.value]; + if (!buildFileObj || typeof buildFileObj !== "object") { + debug(`Build file object not found for file: ${file.value}`); + continue; + } + debug(`Build file object found for file: ${file.value}`); + + const buildFileRefId = buildFileObj.fileRef; + if (!buildFileRefId) { + debug(`File reference not found for file: ${file.value}`); + continue; + } + debug(`Build file reference found for file: ${file.value}`); + + // Find the related file reference object + const buildFile = this.objects.PBXFileReference[buildFileRefId]; + if (!buildFile || typeof buildFile !== "object") { + debug(`File not found in file dictionary for file: ${file.value}`); + continue; + } + debug(`Build file found in file dictionary for file: ${file.value}`); + + // Resolve the path of the file based on the `sourceTree` property + const resolvedFilePath = this.resolveAbsolutePathOfFileReference({ + id: buildFileRefId, + obj: buildFile, + }); + if (!resolvedFilePath) { + debug(`Failed to resolve file path for file: ${file.value}`); + continue; + } + debug(`Resolved file ${file.value} to path: ${resolvedFilePath}`); + + result.push(resolvedFilePath); + } + + debug( + `Resolved ${result.length} files for target: ${nativeTarget.obj.name}`, + ); + return result; + } + + /** + * Resolves the absolute path of a file reference. + * + * @param fileRef - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsolutePathOfFileReference( + fileRef: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of file reference: ${fileRef.id} with path: ${fileRef.obj.path}`, + ); + // File path is expected to be set, therefore typing is non-nullable. + // As the file is loaded from a project file, it is not guaranteed to be set, + // therefore we treat it as optional. + if (!fileRef.obj.path) { + debug(`File reference path not found for file reference: ${fileRef.id}`); + return undefined; + } + + // File references are resolved based on the `sourceTree` property + // which can have one of the following values: + // - '': The file path is absolute + // - '': The file path is relative to the parent group of the file reference + // - 'BUILT_PRODUCTS_DIR': The file path is relative to the built products directory, i.e. the build output directory in derived data + // - 'SOURCE_ROOT': The file path is relative to the source root, i.e. the directory where the Xcode project is located + // - 'SDKROOT': The file path is relative to the SDK root, i.e. the directory where the SDK is installed + // - 'DEVELOPER_DIR': The file path is relative to the developer directory, i.e. the directory where the Xcode command line tools are installed + + // The default is '' + const fileRefSourceTree = + fileRef.obj.sourceTree?.replace(/"/g, "") ?? ""; + switch (fileRefSourceTree) { + case "": + return fileRef.obj.path.replace(/"/g, ""); + case "": + return this.resolveAbsoluteFilePathRelativeToGroup(fileRef); + case "BUILT_PRODUCTS_DIR": + return this.resolveAbsoluteFilePathRelativeToBuiltProductsDir(fileRef); + case "SOURCE_ROOT": + return this.resolveAbsoluteFilePathRelativeToSourceRoot(fileRef); + case "SDKROOT": + return this.resolveAbsoluteFilePathRelativeToSdkRoot(fileRef); + case "DEVELOPER_DIR": + return this.resolveAbsoluteFilePathRelativeToDeveloperDir(fileRef); + default: + debug( + `Unknown source tree '${fileRef.obj.sourceTree}' for build file: ${fileRef.obj.path}`, + ); + return undefined; + } + } + + /** + * Resolves the absolute path of a file reference relative to the parent group. + * + * @param fileRef - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsoluteFilePathRelativeToGroup( + fileRef: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving absolute file path relative to group for file reference: ${ + fileRef.id + } with path: ${fileRef.obj.path ?? ""}`, + ); + const fileRefPath = fileRef.obj.path?.replace(/"/g, ""); + if (!fileRefPath) { + debug(`File reference path not found for file reference: ${fileRef.id}`); + return undefined; + } + + // Find the parent group of the file reference by searching for the reverse relationship + const parentGroup = this.findParentGroupByChildId(fileRef.id); + if (!parentGroup) { + debug( + `Parent group not found for file reference: ${fileRef.id} at path: ${fileRefPath}`, + ); + return undefined; + } + + // Resolve the path of the parent group + const absoluteGroupPath = this.resolveAbsolutePathOfGroup(parentGroup); + if (!absoluteGroupPath) { + debug(`Failed to resolve path of group: ${parentGroup.id}`); + return undefined; + } + + return path.join(absoluteGroupPath, fileRefPath); + } + + /** + * Resolves the absolute path of a file reference relative to the built products directory. + * + * @param buildFile - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsoluteFilePathRelativeToBuiltProductsDir( + buildFile: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving absolute file path relative to built products directory for file reference: ${ + buildFile.id + } with path: ${buildFile.obj.path ?? ""}`, + ); + const builtProductsDir = this.getBuildProductsDirectoryPath(); + if (!builtProductsDir) { + debug(`Failed to resolve built products directory path`); + return undefined; + } + + return path.join( + builtProductsDir, + (buildFile.obj.path ?? "").replace(/"/g, ""), + ); + } + + /** + * Resolves the absolute path of a file reference relative to the source root. + * + * The source root is the directory where the `.xcodeproj` file is located. + * + * @param buildFile - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsoluteFilePathRelativeToSourceRoot( + buildFile: XcodeProjectObjectWithId, + ): string | undefined { + return path.join( + this.baseDir, + (buildFile.obj.path ?? "").replace(/"/g, ""), + ); + } + + /** + * Resolves the absolute path of a file reference relative to the SDK root. + * + * @param buildFile - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsoluteFilePathRelativeToSdkRoot( + buildFile: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving absolute file path relative to SDK root for file reference: ${ + buildFile.id + } with path: ${buildFile.obj.path ?? ""}`, + ); + + const sdkRoot = MacOSSystemHelpers.findSDKRootDirectoryPath(); + if (!sdkRoot) { + debug(`Failed to resolve SDK root directory path`); + return undefined; + } + + return path.join(sdkRoot, (buildFile.obj.path ?? "").replace(/"/g, "")); + } + + /** + * Resolves the absolute path of a file reference relative to the developer directory. + * + * @param buildFile - The file reference to resolve the path of + * @returns The absolute path of the file reference, or undefined if the file reference is not found or has no path + */ + private resolveAbsoluteFilePathRelativeToDeveloperDir( + buildFile: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving absolute file path relative to developer directory for file reference: ${ + buildFile.id + } with path: ${buildFile.obj.path ?? ""}`, + ); + const developerDir = MacOSSystemHelpers.findDeveloperDirectoryPath(); + if (!developerDir) { + debug(`Failed to resolve developer directory path`); + return undefined; + } + + return path.join( + developerDir, + (buildFile.obj.path ?? "").replace(/"/g, ""), + ); + } + + /** + * Resolves the absolute path of a group. + * + * @param group - The group to resolve the path of + * @returns The absolute path of the group, or undefined if the group is not found or has no path + */ + private resolveAbsolutePathOfGroup( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of group: ${group.id} with path: ${group.obj.path ?? ""}`, + ); + + // Group paths are resolved based on the `sourceTree` property + // which can have one of the following values: + // - '': The group path is relative to the parent group of the group + // - 'SOURCE_ROOT': The group path is relative to the source root, i.e. the directory where the Xcode project is located + // - 'BUILT_PRODUCTS_DIR': The group path is relative to the built products directory, i.e. the build output directory in derived data + // - 'SDKROOT': The group path is relative to the SDK root, i.e. the directory where the SDK is installed + // - 'DEVELOPER_DIR': The group path is relative to the developer directory, i.e. the directory where the Xcode command line tools are installed + + // The default is '' + const groupSourceTree = + group.obj.sourceTree?.replace(/"/g, "") ?? ""; + + switch (groupSourceTree) { + case "": + return this.resolvePathOfGroupRelativeToGroup(group); + case "SOURCE_ROOT": + return this.resolvePathOfGroupRelativeToSourceRoot(group); + case "BUILT_PRODUCTS_DIR": + return this.resolvePathOfGroupRelativeToBuiltProductsDir(group); + case "SDKROOT": + return this.resolvePathOfGroupRelativeToSdkRoot(group); + case "DEVELOPER_DIR": + return this.resolvePathOfGroupRelativeToDeveloperDir(group); + default: + debug( + `Unknown source tree '${groupSourceTree}' for group: ${group.id}`, + ); + return undefined; + } + } + + /** + * Resolves the path of a group relative to the parent group. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the parent group, or undefined if the group is not found or has no path + */ + private resolvePathOfGroupRelativeToGroup( + group: XcodeProjectObjectWithId, + ): string | undefined { + const parentGroup = this.findParentGroupByChildId(group.id); + + if (!parentGroup) { + debug(`Parent group not found for group: ${group.id}`); + // If the parent group is not found, check if the group is the main group + // We assume the main group is at the root of the project + if (this.isMainGroup(group.id)) { + return this.baseDir; + } + return undefined; + } + + const parentGroupPath = this.resolveAbsolutePathOfGroup(parentGroup); + if (!parentGroupPath) { + debug(`Failed to resolve path of parent group: ${parentGroup.id}`); + return undefined; + } + + const groupPath = group.obj.path?.replace(/"/g, "") ?? ""; + if (!groupPath) { + debug(`Group path not found for group: ${group.id}`); + return undefined; + } + + return path.join(parentGroupPath, groupPath); + } + + /** + * Resolves the path of a group relative to the source root. + * + * The source root is the directory where the `.xcodeproj` file is located. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the source root, or undefined if the group is not found or has no path + */ + private resolvePathOfGroupRelativeToSourceRoot( + group: XcodeProjectObjectWithId, + ): string | undefined { + const groupPath = group.obj.path?.replace(/"/g, "") ?? ""; + if (!groupPath) { + debug(`Group path not found for group: ${group.id}`); + return this.baseDir; + } + return path.join(this.baseDir, groupPath); + } + + /** + * Resolves the path of a group relative to the built products directory. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the built products directory, or undefined if the group is not found or has no path + */ + private resolvePathOfGroupRelativeToBuiltProductsDir( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of group: ${group.id} relative to built products directory`, + ); + const builtProductsDir = this.getBuildProductsDirectoryPath(); + if (!builtProductsDir) { + debug(`Failed to resolve built products directory path`); + return undefined; + } + + return path.join(builtProductsDir, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Resolves the path of a group relative to the SDK root. + * + * The SDK root is the directory where the SDK is installed. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the SDK root, or undefined if the group is not found or has no path + */ + private resolvePathOfGroupRelativeToSdkRoot( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug(`Resolving path of group: ${group.id} relative to SDK root`); + const sdkRoot = MacOSSystemHelpers.findSDKRootDirectoryPath(); + if (!sdkRoot) { + debug(`Failed to resolve SDK root directory path`); + return undefined; + } + + return path.join(sdkRoot, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Resolves the path of a group relative to the developer directory. + * + * The developer directory is the directory where the Xcode command line tools are installed. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the developer directory, or undefined if the group is not found or has no path + */ + private resolvePathOfGroupRelativeToDeveloperDir( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of group: ${group.id} relative to developer directory`, + ); + const developerDir = MacOSSystemHelpers.findDeveloperDirectoryPath(); + if (!developerDir) { + debug(`Failed to resolve developer directory path`); + return undefined; + } + + return path.join(developerDir, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Resolves the absolute path of a group. + * + * @param group - The group to resolve the path of + * @returns The absolute path of the group, or undefined if the group is not found or has no path + */ + private resolveAbsolutePathOfSynchronizedRootGroup( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of synchronized root group: ${group.id} with path: ${ + group.obj.path ?? "" + }`, + ); + + // Group paths are resolved based on the `sourceTree` property + // which can have one of the following values: + // - '': The group path is relative to the parent group of the group + // - 'SOURCE_ROOT': The group path is relative to the source root, i.e. the directory where the Xcode project is located + // - 'BUILT_PRODUCTS_DIR': The group path is relative to the built products directory, i.e. the build output directory in derived data + // - 'SDKROOT': The group path is relative to the SDK root, i.e. the directory where the SDK is installed + // - 'DEVELOPER_DIR': The group path is relative to the developer directory, i.e. the directory where the Xcode command line tools are installed + + // The default is '' + const groupSourceTree = + group.obj.sourceTree?.replace(/"/g, "") ?? ""; + + switch (groupSourceTree) { + case "": + return this.resolvePathOfSynchronizedRootGroupRelativeToGroup(group); + case "SOURCE_ROOT": + return this.resolvePathOfSynchronizedRootGroupRelativeToSourceRoot( + group, + ); + case "BUILT_PRODUCTS_DIR": + return this.resolvePathOfSynchronizedRootGroupRelativeToBuiltProductsDir( + group, + ); + case "SDKROOT": + return this.resolvePathOfSynchronizedRootGroupRelativeToSdkRoot(group); + case "DEVELOPER_DIR": + return this.resolvePathOfSynchronizedRootGroupRelativeToDeveloperDir( + group, + ); + default: + debug( + `Unknown source tree '${groupSourceTree}' for group: ${group.id}`, + ); + return undefined; + } + } + + /** + * Resolves the path of a group relative to the parent group. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the parent group, or undefined if the group is not found or has no path + */ + private resolvePathOfSynchronizedRootGroupRelativeToGroup( + group: XcodeProjectObjectWithId, + ): string | undefined { + const parentGroup = this.findParentGroupByChildId(group.id); + + if (!parentGroup) { + debug(`Parent group not found for group: ${group.id}`); + // If the parent group is not found, check if the group is the main group + // We assume the main group is at the root of the project + if (this.isMainGroup(group.id)) { + return this.baseDir; + } + return undefined; + } + + const parentGroupPath = this.resolveAbsolutePathOfGroup(parentGroup); + if (!parentGroupPath) { + debug(`Failed to resolve path of parent group: ${parentGroup.id}`); + return undefined; + } + + const groupPath = group.obj.path?.replace(/"/g, "") ?? ""; + if (!groupPath) { + debug(`Group path not found for group: ${group.id}`); + return undefined; + } + + return path.join(parentGroupPath, groupPath); + } + + /** + * Resolves the path of a group relative to the source root. + * + * The source root is the directory where the `.xcodeproj` file is located. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the source root, or undefined if the group is not found or has no path + */ + private resolvePathOfSynchronizedRootGroupRelativeToSourceRoot( + group: XcodeProjectObjectWithId, + ): string | undefined { + const groupPath = group.obj.path?.replace(/"/g, "") ?? ""; + if (!groupPath) { + debug(`Group path not found for group: ${group.id}`); + return this.baseDir; + } + return path.join(this.baseDir, groupPath); + } + + /** + * Resolves the path of a group relative to the built products directory. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the built products directory, or undefined if the group is not found or has no path + */ + private resolvePathOfSynchronizedRootGroupRelativeToBuiltProductsDir( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of synchronized root group: ${group.id} relative to built products directory`, + ); + const builtProductsDir = this.getBuildProductsDirectoryPath(); + if (!builtProductsDir) { + debug(`Failed to resolve built products directory path`); + return undefined; + } + + return path.join(builtProductsDir, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Resolves the path of a group relative to the SDK root. + * + * The SDK root is the directory where the SDK is installed. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the SDK root, or undefined if the group is not found or has no path + */ + private resolvePathOfSynchronizedRootGroupRelativeToSdkRoot( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug(`Resolving path of group: ${group.id} relative to SDK root`); + const sdkRoot = MacOSSystemHelpers.findSDKRootDirectoryPath(); + if (!sdkRoot) { + debug(`Failed to resolve SDK root directory path`); + return undefined; + } + + return path.join(sdkRoot, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Resolves the path of a group relative to the developer directory. + * + * The developer directory is the directory where the Xcode command line tools are installed. + * + * @param group - The group to resolve the path of + * @returns The path of the group relative to the developer directory, or undefined if the group is not found or has no path + */ + private resolvePathOfSynchronizedRootGroupRelativeToDeveloperDir( + group: XcodeProjectObjectWithId, + ): string | undefined { + debug( + `Resolving path of synchronized root group: ${group.id} relative to developer directory`, + ); + const developerDir = MacOSSystemHelpers.findDeveloperDirectoryPath(); + if (!developerDir) { + debug(`Failed to resolve developer directory path`); + return undefined; + } + + return path.join(developerDir, group.obj.path?.replace(/"/g, "") ?? ""); + } + + /** + * Finds all files in the synchronized root groups of a target. + * + * @param nativeTarget - The target to find the files in + * @returns The files in the synchronized root groups of the target, or an empty array if the target is not found or has no synchronized root groups + */ + findFilesInSynchronizedRootGroups( + nativeTarget: XcodeProjectObjectWithId, + ): string[] { + debug( + `Finding files in synchronized root groups for target: ${nativeTarget.obj.name}`, + ); + const synchronizedRootGroups = + nativeTarget.obj.fileSystemSynchronizedGroups ?? []; + + const result: string[] = []; + for (const group of synchronizedRootGroups) { + const groupObj = + this.objects.PBXFileSystemSynchronizedRootGroup?.[group.value]; + if (!groupObj || typeof groupObj !== "object") { + debug(`Synchronized root group not found: ${group.value}`); + continue; + } + debug(`Found synchronized root group: ${group.value}`); + + const files = this.getFilesInSynchronizedRootGroup({ + id: group.value, + obj: groupObj, + }); + debug( + `Found ${files.length} files in synchronized root group: ${group.value}`, + ); + result.push(...files.map((file) => file.path)); + } + debug( + `Found ${result.length} files in synchronized root groups for target: ${nativeTarget.obj.name}`, + ); + return result; + } + + private getFilesInSynchronizedRootGroup( + group: XcodeProjectObjectWithId, + ): ProjectFile[] { + // Group path is expected to be set, therefore typing is non-nullable. + // As the group is loaded from a project file, it is not guaranteed to be set, + // therefore we treat it as optional. + if (!group.obj.path) { + debug(`Group path not found for group: ${group.id}`); + return []; + } + + // Resolve the path of the synchronized root group + const absoluteGroupPath = + this.resolveAbsolutePathOfSynchronizedRootGroup(group); + if (!absoluteGroupPath) { + debug(`Failed to resolve path of synchronized root group: ${group.id}`); + return []; + } + + // Build a list of all exception paths for the group + const exceptionSets = this.getExceptionSetsForGroup(group); + + // Resolve a list of all files in the group + const files = this.getAbsoluteFilePathsInDirectoryTree(absoluteGroupPath); + + // Filter out files that are excluded by the exception sets + const filteredFiles = this.filterFilesByExceptionSets(files, exceptionSets); + + return filteredFiles; + } + + /** + * Returns all files in a directory tree. + * + * @param dirPath - The path of the directory to get the files in + * @returns All files in the directory tree, or an empty array if the directory does not exist + */ + private getAbsoluteFilePathsInDirectoryTree(dirPath: string): ProjectFile[] { + // If the directory does not exist, return an empty array + // This can happen if the group is not found in the project + if (!existsSync(dirPath)) { + return []; + } + const result: ProjectFile[] = []; + const files = readdirSync(dirPath); + for (const file of files) { + // Ignore hidden files and directories + if (file.startsWith(".")) { + continue; + } + + const filePath = path.join(dirPath, file); + // If the file is a directory, recursively get the files in the directory + if (statSync(filePath).isDirectory()) { + result.push(...this.getAbsoluteFilePathsInDirectoryTree(filePath)); + continue; + } + // If the file is a file, add it to the result + if (statSync(filePath).isFile()) { + result.push({ + name: file, + path: filePath, + }); + continue; + } + } + + return result; + } + + private filterFilesByExceptionSets( + files: ProjectFile[], + exceptionSets: XcodeProjectObjectWithId[], + ): ProjectFile[] { + // Iterate over all files and filter out files that are excluded by any exception sets + return files.filter((file) => { + return !exceptionSets.some((exceptionSet) => { + const membershipExceptions = + exceptionSet.obj.membershipExceptions ?? []; + return membershipExceptions.some((path) => { + const unescapedPath = path.replace(/"/g, ""); + return file.path.includes(unescapedPath); + }); + }); + }); + } + + // ================================ GROUP HELPERS ================================ + + /** + * Returns all groups that are PBXGroup. + * + * This is a helper method to avoid having to map and filter the groups manually. + * + * @returns All groups that are PBXGroup, excluding comments and non-object values. + */ + private get groups(): XcodeProjectObjectWithId[] { + // Map and filter the groups to only include the groups that are PBXGroup + return Object.entries(this.objects.PBXGroup ?? {}).reduce( + (acc, [key, group]) => { + if (typeof group !== "object") { + return acc; + } + return [ + ...acc, + { + id: key, + obj: group, + }, + ]; + }, + new Array>(), + ); + } + + /** + * Finds the parent group of a child group or file reference. + * + * @param childId - The ID of the child group or file reference + * @returns The parent group of the child group or file reference, or undefined if the child group or file reference is not found or has no parent group + */ + private findParentGroupByChildId( + childId: string, + ): XcodeProjectObjectWithId | undefined { + return this.groups.find((group) => { + return (group.obj.children ?? []).some((child) => { + return child.value === childId; + }); + }); + } + + /** + * Checks if a group is the main group of any project. + * + * @param groupId - The ID of the group to check + * @returns True if the group is the main group, false otherwise + */ + private isMainGroup(groupId: string): boolean { + return Object.values(this.objects.PBXProject ?? {}).some((project) => { + if (typeof project !== "object") { + return false; + } + return project.mainGroup === groupId; + }); + } + + private getExceptionSetsForGroup( + group: XcodeProjectObjectWithId, + ): XcodeProjectObjectWithId[] { + const exceptions = group.obj.exceptions ?? []; + const exceptionSets: XcodeProjectObjectWithId[] = + []; + for (const exception of exceptions) { + const exceptionSet = + this.objects.PBXFileSystemSynchronizedBuildFileExceptionSet?.[ + exception.value + ]; + if (typeof exceptionSet !== "object") { + continue; + } + exceptionSets.push({ + id: exception.value, + obj: exceptionSet, + comment: exception.comment, + }); + } + return exceptionSets; + } + + /** + * The path to the build products directory for the project. + * + * This is cached to avoid having to read the build settings from Xcode for each call to `getBuildProductsDirectoryPath`. + */ + private buildProductsDir: string | undefined; + + /** + * Returns the path to the build products directory for the project. + * + * @returns The path to the build products directory for the project, or undefined if the path is not found + */ + private getBuildProductsDirectoryPath(): string | undefined { + if (this.buildProductsDir) { + return this.buildProductsDir; + } + const buildSettings = MacOSSystemHelpers.readXcodeBuildSettings( + this.xcodeprojPath, + ); + if (!buildSettings) { + debug(`Failed to read Xcode build settings`); + return undefined; + } + this.buildProductsDir = + buildSettings["TARGET_BUILD_DIR"] ?? buildSettings["BUILD_DIR"]; + + return this.buildProductsDir; + } +} diff --git a/packages/cli/src/lib/wizard/apple/xcode-project-object-with-id.ts b/packages/cli/src/lib/wizard/apple/xcode-project-object-with-id.ts new file mode 100644 index 000000000..804c3d321 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/xcode-project-object-with-id.ts @@ -0,0 +1,9 @@ +/** + * An object from an Xcode project together with its id. + */ + +export interface XcodeProjectObjectWithId { + id: string; + obj: T; + comment?: string | undefined; +} diff --git a/packages/cli/src/lib/wizard/react-native/cocoapod.ts b/packages/cli/src/lib/wizard/react-native/cocoapod.ts new file mode 100644 index 000000000..53e97c685 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/cocoapod.ts @@ -0,0 +1,139 @@ +/** + * Detect CocoaPods in a React Native iOS project, enable modular headers, and + * run `pod install`. + */ + +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { reportCliError } from "../../error-reporting.js"; +import path from "node:path"; +import { execute } from "../utils/bash.js"; +import { Sentry } from "../telemetry.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; + +export function usesCocoaPod(projPath: string): boolean { + return existsSync(path.join(projPath, "Podfile")); +} + +/** + * Ensures `use_modular_headers!` is present in the Podfile. + * + * As of `@sentry/react-native` 8.19.0 the `RNSentry` pod ships Swift code (the + * `RNSentryInternal` bridge over `SentrySDK.internal`, part of the migration to + * the prebuilt `Sentry.xcframework`). CocoaPods refuses to integrate a Swift pod + * that depends on a non-modular Objective-C pod (e.g. `React-hermes` on React + * Native versions that don't modularize it by default) unless the Podfile opts + * into module maps. Without it, `pod install` fails with: + * + * [!] The following Swift pods cannot yet be integrated as static libraries: + * The Swift pod `RNSentry` depends upon `React-hermes`, which does not define + * modules. [...] you may set `use_modular_headers!` globally in your Podfile + * + * The SDK's own docs instruct users to add this line manually; we do it for them. + * + * @returns `true` if the Podfile already had (or now has) `use_modular_headers!`, + * `false` if there is no Podfile to patch. + */ +export function addModularHeaders(projPath: string): boolean { + const podfile = path.join(projPath, "Podfile"); + + if (!existsSync(podfile)) { + return false; + } + + const podContent = readFileSync(podfile, "utf8"); + + if (/^\s*use_modular_headers!/m.test(podContent)) { + // Already opted into modular headers, nothing to do. + return true; + } + + // Insert above the first `target '...' do` block, matching the placement the + // SDK docs recommend. The `^\s*` anchor avoids matching commented-out targets. + const targetMatch = /^([ \t]*)target\s+['"][^'"]+['"]\s+do/m.exec(podContent); + + let newFileContent: string; + if (targetMatch) { + const insertIndex = targetMatch.index; + newFileContent = + podContent.slice(0, insertIndex) + + "use_modular_headers!\n\n" + + podContent.slice(insertIndex); + } else { + // No target block found, append to the end as a safe fallback. + const separator = + podContent.endsWith("\n") || podContent.length === 0 ? "" : "\n"; + newFileContent = `${podContent}${separator}use_modular_headers!\n`; + } + + writeFileSync(podfile, newFileContent, "utf8"); + + clack.log.step( + `Added ${chalk.cyan("use_modular_headers!")} to the iOS ${chalk.cyan( + "Podfile", + )} (required by the Sentry React Native SDK).`, + ); + + return true; +} + +export async function addCocoaPods(projPath: string): Promise { + const podfile = path.join(projPath, "Podfile"); + + const podContent = readFileSync(podfile, "utf8"); + + if ( + /^\s*pod\s+(['"]Sentry['"]|['"]SentrySwiftUI['"])\s*$/im.test(podContent) + ) { + // Already have Sentry pod + return true; + } + + let podMatch = /^( *)pod\s+['"](\w+)['"] *$/im.exec(podContent); + if (!podMatch) { + // No Podfile is empty, will try to add Sentry pod after "use_frameworks!" + const frameworkMatch = /^( *)use_frameworks![^\n]* *$/im.exec(podContent); + if (!frameworkMatch) { + return false; + } + podMatch = frameworkMatch; + } + + const insertIndex = podMatch.index + podMatch[0].length; + const newFileContent = + podContent.slice(0, insertIndex) + + "\n" + + podMatch[1] + + "pod 'Sentry'\n" + + podContent.slice(insertIndex); + writeFileSync(podfile, newFileContent, "utf8"); + + clack.log.step("Sentry pod added to the project podFile."); + + await podInstall(); + + return true; +} + +export async function podInstall(dir = ".") { + const installSpinner = clack.spinner(); + installSpinner.start("Running 'pod install'. This may take a few minutes..."); + + try { + await execute(`cd ${dir} && pod repo update`); + await execute(`cd ${dir} && pod install --silent`); + installSpinner.stop("Pods installed."); + Sentry.setTag("pods-installed", true); + } catch (e) { + installSpinner.stop("Failed to install pods."); + Sentry.setTag("pods-installed", false); + clack.log.error( + `${chalk.red( + "Encountered the following error during pods installation:", + )}\n\n${String(e)}\n\n${chalk.dim( + "If you think this issue is caused by the Sentry wizard, let us know here:\nhttps://github.com/getsentry/toolkit/issues", + )}`, + ); + reportCliError(new Error("Sentry pod install failed.")); + } +} diff --git a/packages/cli/src/lib/wizard/react-native/expo-env-file.ts b/packages/cli/src/lib/wizard/react-native/expo-env-file.ts new file mode 100644 index 000000000..76b29d1a2 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/expo-env-file.ts @@ -0,0 +1,67 @@ +/** + * Write the Sentry auth token to Expo's `.env.local` and keep that file out + * of git. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { reportCliError } from "../../error-reporting.js"; +import chalk from "chalk"; +import fs from "fs"; +import { Sentry } from "../telemetry.js"; +import { type RNCliSetupConfigContent } from "./react-native-wizard.js"; +import { addToGitignore } from "./git.js"; + +const EXPO_ENV_LOCAL_FILE = ".env.local"; + +export async function addExpoEnvLocal( + options: RNCliSetupConfigContent, +): Promise { + const newContent = `#DO NOT COMMIT THIS\nSENTRY_AUTH_TOKEN=${options.authToken}\n`; + + const added = await addToGitignore(EXPO_ENV_LOCAL_FILE); + if (added) { + Sentry.setTag("expo-env-local", "added-to-gitignore"); + clack.log.success( + `Added ${chalk.cyan(EXPO_ENV_LOCAL_FILE)} to .gitignore.`, + ); + } else { + Sentry.setTag("expo-env-local", "add-to-gitignore-error"); + clack.log.error( + `Could not add ${chalk.cyan( + EXPO_ENV_LOCAL_FILE, + )} to .gitignore, please add it to not commit your auth key.`, + ); + reportCliError( + new Error(`Could not add ${EXPO_ENV_LOCAL_FILE} to .gitignore`), + ); + } + + if (!fs.existsSync(EXPO_ENV_LOCAL_FILE)) { + try { + await fs.promises.writeFile(EXPO_ENV_LOCAL_FILE, newContent); + Sentry.setTag("expo-env-local", "written"); + clack.log.success(`Written ${chalk.cyan(EXPO_ENV_LOCAL_FILE)}.`); + return true; + } catch (error) { + Sentry.setTag("expo-env-local", "write-error"); + clack.log.error(`Unable to write ${chalk.cyan(EXPO_ENV_LOCAL_FILE)}.`); + reportCliError(new Error(`Unable to write ${EXPO_ENV_LOCAL_FILE}.`)); + return false; + } + } + + Sentry.setTag("expo-env-local", "exists"); + clack.log.info(`Updating existing ${chalk.cyan(EXPO_ENV_LOCAL_FILE)}.`); + + try { + await fs.promises.appendFile(EXPO_ENV_LOCAL_FILE, newContent); + Sentry.setTag("expo-env-local", "updated"); + clack.log.success(`Updated ${chalk.cyan(EXPO_ENV_LOCAL_FILE)}.`); + return true; + } catch (error) { + Sentry.setTag("expo-env-local", "update-error"); + clack.log.error(`Unable to update ${chalk.cyan(EXPO_ENV_LOCAL_FILE)}.`); + reportCliError(new Error(`Unable to update ${EXPO_ENV_LOCAL_FILE}.`)); + return false; + } +} diff --git a/packages/cli/src/lib/wizard/react-native/expo-metro.ts b/packages/cli/src/lib/wizard/react-native/expo-metro.ts new file mode 100644 index 000000000..3c3d12df9 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/expo-metro.ts @@ -0,0 +1,268 @@ +/** + * Add Sentry to an Expo project's Metro config through + * `getSentryExpoConfig`. + */ + +import { existsSync, promises } from "node:fs"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { ProxifiedModule } from "magicast"; +import chalk from "chalk"; +import { Sentry } from "../telemetry.js"; + +import { getLastRequireIndex, hasSentryContent } from "../utils/ast-utils.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; + +import { + findMetroConfigPath, + parseMetroConfig, + writeMetroConfig, +} from "./metro.js"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +const b = recast.types.builders; + +export async function addSentryToExpoMetroConfig() { + let metroConfigPath = findMetroConfigPath(); + + if (!metroConfigPath) { + // No existing metro config found, create metro.config.js (Expo default) + metroConfigPath = "metro.config.js"; + } + + if (!existsSync(metroConfigPath)) { + const success = await createSentryExpoMetroConfig(metroConfigPath); + if (!success) { + Sentry.setTag("expo-metro-config", "create-new-error"); + return await showInstructions(metroConfigPath); + } + Sentry.setTag("expo-metro-config", "created-new"); + return undefined; + } + + Sentry.setTag("expo-metro-config", "exists"); + clack.log.info(`Updating existing ${metroConfigPath}.`); + + const mod = await parseMetroConfig(metroConfigPath); + if (!mod) { + return await showInstructions(metroConfigPath); + } + + let didPatch = false; + try { + didPatch = patchMetroInMemory(mod, metroConfigPath); + } catch (e) { + reportCliError(new Error("Unable to patch expo metro config")); + } + if (!didPatch) { + Sentry.setTag("expo-metro-config", "patch-error"); + clack.log.error( + `Could not patch ${chalk.cyan( + metroConfigPath, + )} with Sentry configuration.`, + ); + return await showInstructions(metroConfigPath); + } + + const saved = await writeMetroConfig(mod, metroConfigPath); + if (saved) { + Sentry.setTag("expo-metro-config", "patch-saved"); + clack.log.success( + chalk.green(`${chalk.cyan(metroConfigPath)} changes saved.`), + ); + } else { + Sentry.setTag("expo-metro-config", "patch-save-error"); + clack.log.error( + `Could not save changes to ${chalk.cyan( + metroConfigPath, + )}, please follow the manual steps.`, + ); + return await showInstructions(metroConfigPath); + } +} + +export function patchMetroInMemory( + mod: ProxifiedModule, + metroConfigPath: string, +): boolean { + const ast = mod.$ast as t.Program; + + if (hasSentryContent(ast)) { + clack.log.warn( + `The ${chalk.cyan( + metroConfigPath, + )} file already has Sentry configuration.`, + ); + return false; + } + + // Set in the visitor below, which TypeScript can't follow. + let didReplaceDefaultConfigCall = false as boolean; + + recast.visit(ast, { + visitVariableDeclaration(path) { + const { node } = path; + + const declaration = node.declarations[0]; + const init = + declaration?.type === "VariableDeclarator" ? declaration.init : null; + const requiredModule = + init?.type === "CallExpression" ? init.arguments[0] : undefined; + const destructured = + declaration?.type === "VariableDeclarator" && + declaration.id.type === "ObjectPattern" && + declaration.id.properties.length === 1 + ? declaration.id.properties[0] + : undefined; + if ( + // path is require("expo/metro-config") + // and only getDefaultConfig is being destructured + // then remove the entire declaration + init?.type === "CallExpression" && + init.callee.type === "Identifier" && + init.callee.name === "require" && + requiredModule?.type === "StringLiteral" && + requiredModule.value === "expo/metro-config" && + destructured?.type === "ObjectProperty" && + destructured.key.type === "Identifier" && + destructured.key.name === "getDefaultConfig" + ) { + path.prune(); + return false; + } + + this.traverse(path); + return undefined; + }, + + visitCallExpression(path) { + const { node } = path; + if ( + // path is getDefaultConfig + // then rename it to getSentryExpoConfig + node.callee.type === "Identifier" && + node.callee.name === "getDefaultConfig" + ) { + node.callee.name = "getSentryExpoConfig"; + didReplaceDefaultConfigCall = true; + return false; + } + + this.traverse(path); + return undefined; + }, + }); + + if (!didReplaceDefaultConfigCall) { + clack.log.warn( + `Could not find \`getDefaultConfig\` in ${chalk.cyan(metroConfigPath)}.`, + ); + return false; + } + + addSentryExpoConfigRequire(ast, metroConfigPath); + + return true; +} + +export function addSentryExpoConfigRequire( + program: t.Program, + metroConfigPath: string, +) { + try { + const lastRequireIndex = getLastRequireIndex(program); + const sentryExpoConfigRequire = createSentryExpoConfigRequire(); + + // Add the require statement after the last require or at the beginning + program.body.splice(lastRequireIndex + 1, 0, sentryExpoConfigRequire); + } catch (error) { + clack.log.error( + `Could not add Sentry Expo config require statement to ${chalk.cyan( + metroConfigPath, + )}.`, + ); + reportCliError( + new Error( + `Could not add Sentry Expo config require statement to ${metroConfigPath}.`, + ), + ); + } +} + +/** + * Creates const { getSentryExpoConfig } = require("@sentry/react-native/metro"); + */ +function createSentryExpoConfigRequire() { + return b.variableDeclaration("const", [ + b.variableDeclarator( + b.objectPattern([ + b.objectProperty.from({ + key: b.identifier("getSentryExpoConfig"), + value: b.identifier("getSentryExpoConfig"), + shorthand: true, + }), + ]), + b.callExpression(b.identifier("require"), [ + b.literal("@sentry/react-native/metro"), + ]), + ), + ]); +} + +async function createSentryExpoMetroConfig( + metroConfigPath: string, +): Promise { + const snippet = `const { getSentryExpoConfig } = require("@sentry/react-native/metro"); + +const config = getSentryExpoConfig(__dirname); + +module.exports = config; +`; + try { + await promises.writeFile(metroConfigPath, snippet); + } catch (e) { + clack.log.error( + `Could not create ${chalk.cyan( + metroConfigPath, + )} with Sentry configuration.`, + ); + reportCliError( + new Error( + `Could not create ${metroConfigPath} with Sentry configuration.`, + ), + ); + return false; + } + clack.log.success( + `Created ${chalk.cyan(metroConfigPath)} with Sentry configuration.`, + ); + return true; +} + +function showInstructions(metroConfigPath: string) { + return showCopyPasteInstructions({ + filename: metroConfigPath, + codeSnippet: getMetroWithSentryExpoConfigSnippet(true), + }); +} + +function getMetroWithSentryExpoConfigSnippet(colors: boolean): string { + return makeCodeSnippet(colors, (unchanged, plus, minus) => + unchanged(`${minus( + `// const { getDefaultConfig } = require("expo/metro-config");`, + )} +${plus( + `const { getSentryExpoConfig } = require("@sentry/react-native/metro");`, +)} + +${minus(`// const config = getDefaultConfig(__dirname);`)} +${plus(`const config = getSentryExpoConfig(__dirname);`)} + +module.exports = config;`), + ); +} diff --git a/packages/cli/src/lib/wizard/react-native/expo.ts b/packages/cli/src/lib/wizard/react-native/expo.ts new file mode 100644 index 000000000..6031c72bf --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/expo.ts @@ -0,0 +1,231 @@ +/** + * Expo support for the React Native wizard: detect continuous native + * generation, and add the Sentry config plugin to `app.json`. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; +import { reportCliError } from "../../error-reporting.js"; +import chalk from "chalk"; +import { existsSync, promises } from "node:fs"; +import { EOL } from "node:os"; + +import { Sentry } from "../telemetry.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { type RNCliSetupConfigContent } from "./react-native-wizard.js"; +import { traceStep } from "../telemetry.js"; +import { isFolderInGitignore } from "./git.js"; + +export const SENTRY_EXPO_PLUGIN_NAME = "@sentry/react-native/expo"; +export const DEPRECATED_SENTRY_EXPO_PLUGIN_NAME = "sentry-expo"; + +export const SENTRY_PLUGIN_FUNCTION_NAME = "withSentry"; + +const APP_CONFIG_JSON = `app.json`; + +export interface AppConfigJson { + expo?: { + plugins?: Array<[string, undefined | Record]>; + }; +} + +export function printSentryExpoMigrationOutro(): void { + clack.outro( + `Deprecated ${chalk.cyan( + "sentry-expo", + )} package installed in your dependencies. Please follow the migration guide at ${chalk.cyan( + "https://docs.sentry.io/platforms/react-native/migration/sentry-expo/", + )}`, + ); +} + +/** + * Finds app.json in the project root and add Sentry Expo `withSentry` plugin. + */ +export async function patchExpoAppConfig(options: RNCliSetupConfigContent) { + function showInstructions() { + return showCopyPasteInstructions({ + filename: APP_CONFIG_JSON, + codeSnippet: getSentryAppConfigJsonCodeSnippet(options), + hint: "This ensures auto upload of source maps during native app build.", + }); + } + + const appConfigJsonExists = existsSync(APP_CONFIG_JSON); + + Sentry.setTag( + "app-config-file-status", + appConfigJsonExists ? "found" : "not-found", + ); + if (!appConfigJsonExists) { + return await showInstructions(); + } + + const patched = await patchAppConfigJson(APP_CONFIG_JSON, options); + if (!patched) { + Sentry.setTag("app-config-file-status", "patch-error"); + clack.log.error(`Unable to patch ${chalk.cyan("app.config.json")}.`); + return await showInstructions(); + } +} + +async function patchAppConfigJson( + path: string, + options: RNCliSetupConfigContent, +): Promise { + const appConfigContent = ( + await promises.readFile(path, { encoding: "utf-8" }) + ).toString(); + const patchedContent = traceStep("app-config-json-patch", () => + addWithSentryToAppConfigJson(appConfigContent, options), + ); + if (patchedContent === null) { + return false; + } + + try { + await promises.writeFile(path, patchedContent); + } catch (error) { + Sentry.setTag("app-config-file-status", "json-write-error"); + clack.log.error(`Unable to write ${chalk.cyan("app.config.json")}.`); + reportCliError(new Error(`Unable to write 'app.config.json'.`)); + return false; + } + Sentry.setTag("app-config-file-status", "json-write-success"); + clack.log.success( + `Added Sentry Expo plugin to ${chalk.cyan("app.config.json")}.`, + ); + return true; +} + +export function addWithSentryToAppConfigJson( + appConfigContent: string, + options: RNCliSetupConfigContent, +): string | null { + try { + const parsedAppConfig: AppConfigJson = JSON.parse(appConfigContent); + const includesWithSentry = + appConfigContent.includes(SENTRY_EXPO_PLUGIN_NAME) || + appConfigContent.includes(DEPRECATED_SENTRY_EXPO_PLUGIN_NAME); + + if (includesWithSentry) { + Sentry.setTag("app-config-file-status", "already-patched"); + clack.log.warn( + `Your ${chalk.cyan( + "app.config.json", + )} already includes the Sentry Expo plugin.`, + ); + return null; + } + + if ( + parsedAppConfig.expo !== undefined && + !isPlainObject(parsedAppConfig.expo) + ) { + Sentry.setTag("app-config-file-status", "invalid-json"); + clack.log.error( + `Unable to find expo in your ${chalk.cyan( + "app.config.json", + )}. Make sure it has a valid format!`, + ); + return null; + } + if ( + parsedAppConfig.expo?.plugins !== undefined && + !Array.isArray(parsedAppConfig.expo.plugins) + ) { + Sentry.setTag("app-config-file-status", "invalid-json"); + clack.log.error( + `Unable to find expo plugins in your ${chalk.cyan( + "app.config.json", + )}. Make sure it has a valid format!`, + ); + return null; + } + + parsedAppConfig.expo = parsedAppConfig.expo ?? {}; + parsedAppConfig.expo.plugins = parsedAppConfig.expo.plugins ?? []; + parsedAppConfig.expo.plugins.push([ + SENTRY_EXPO_PLUGIN_NAME, + { + url: options.url, + project: options.project, + organization: options.org, + }, + ]); + + return JSON.stringify(parsedAppConfig, null, 2) + EOL; + } catch (error) { + Sentry.setTag("app-config-file-status", "invalid-json"); + clack.log.error( + `Unable to parse your ${chalk.cyan( + "app.config.json", + )}. Make sure it has a valid format!`, + ); + reportCliError(new Error(`Error to parsing 'app.config.json'`)); + return null; + } +} + +export function getSentryAppConfigJsonCodeSnippet({ + url, + project, + org, +}: Omit) { + return makeCodeSnippet(true, (unchanged, plus, _minus) => { + return unchanged(`{ + "name": "my app", + "plugins": [ + ${plus(`[ + "@sentry/react-native/expo", + { + "url": "${url}", + "project": "${project}", + "organization": "${org}" + } + ]`)} + ], +}`); + }); +} + +/** + * Checks whether the given value is a plain object (as opposed to something like a class instance or a primitive). + * vendored from @sentry/utils to avoid registering the dependency. + */ +function isPlainObject(what: unknown): boolean { + return Object.prototype.toString.call(what) === "[object Object]"; +} + +/** + * Checks if the project is using Expo's Config Plugins (CNG) + * It checks by checking if the native folders are in gitignore or not + * If native folders are in gitignore then we can skip the native properties file step + */ +export const isExpoCNG = async (): Promise => { + const iOSExists = existsSync("ios"); + const androidExists = existsSync("android"); + + const anyNativeFolderExists = iOSExists || androidExists; + + if (!anyNativeFolderExists) { + // Definitely CNG and using prebuild steps + return true; + } + + try { + const [isIosInGitIgnore, isAndroidInGitIgnore] = await Promise.all([ + iOSExists ? isFolderInGitignore("ios") : Promise.resolve(true), // If the folder doesn't exist, we can consider it as ignored + androidExists ? isFolderInGitignore("android") : Promise.resolve(true), + ]); + + return isIosInGitIgnore && isAndroidInGitIgnore; + } catch (error) { + // Without a readable .gitignore, assume the native folders are committed. + debug(error); + return false; + } +}; diff --git a/packages/cli/src/lib/wizard/react-native/git.ts b/packages/cli/src/lib/wizard/react-native/git.ts new file mode 100644 index 000000000..e1470c5b4 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/git.ts @@ -0,0 +1,69 @@ +/** + * Check and update a React Native project's `.gitignore`. + */ + +import { promises } from "node:fs"; +import { debug } from "../utils/debug.js"; + +const GITIGNORE_FILENAME = ".gitignore"; + +export async function addToGitignore(filepath: string): Promise { + /** + * Don't check whether the given file is ignored because: + * 1. It's tricky to check it without git. + * 2. Git might not be installed or accessible. + * 3. It's convenient to use a module to interact with git, but it would + * increase the size x2 approximately. Docs say to run the Wizard without + * installing it, and duplicating the size would slow the set-up down. + * 4. The Wizard is meant to be run once. + * 5. A message is logged informing users it's been added to the gitignore. + * 6. It will be added to the gitignore as many times as it runs - not a big + * deal. + * 7. It's straightforward to remove it from the gitignore. + */ + try { + await promises.appendFile(GITIGNORE_FILENAME, `\n${filepath}\n`); + return true; + } catch (error) { + // The caller tells the user to add the path to .gitignore themselves. + debug(error); + return false; + } +} + +/** + * Checks if gitignore file contains ios and android folders + * Processes line by line, ignoring comments and checking for exact patterns + */ +export const isFolderInGitignore = async (folder: string): Promise => { + try { + const content = await promises.readFile(GITIGNORE_FILENAME, { + encoding: "utf-8", + }); + + // Split by lines and normalize line endings + const lines = content.replace(/\r\n/g, "\n").split("\n"); + + return lines.some((line) => { + const lineWithoutComment = (line.split("#")[0] ?? "").trim(); + + if (!lineWithoutComment || !lineWithoutComment.includes(folder)) { + return false; + } + + const patterns = [ + folder, // Exact match: ios + `${folder}/`, // Folder with trailing slash: ios/ + `${folder}/*`, // Folder with wildcard: ios/* + `/${folder}`, // Folder with leading slash: /ios + `/${folder}/`, // Folder with leading and trailing slash: /ios/ + ]; + + return patterns.includes(lineWithoutComment); + }); + } catch (error) { + // No readable .gitignore means the folder is not ignored. + debug(error); + return false; + } +}; diff --git a/packages/cli/src/lib/wizard/react-native/glob.ts b/packages/cli/src/lib/wizard/react-native/glob.ts new file mode 100644 index 000000000..2836ace22 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/glob.ts @@ -0,0 +1,26 @@ +/** + * Find the first file that matches a glob, such as the iOS project or the + * Android app's `build.gradle`. + */ + +import { globSync } from "tinyglobby"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; + +export const XCODE_PROJECT = "ios/*.xcodeproj/project.pbxproj"; +export const APP_BUILD_GRADLE = "**/app/build.gradle"; + +const IGNORE_PATTERNS = ["node_modules/**", "ios/Pods/**", "**/Pods/**"]; +export function getFirstMatchedPath(pattern: string): string | undefined { + try { + const matches = globSync(pattern, { + ignore: IGNORE_PATTERNS, + }); + + return matches[0]; + } catch (error) { + clack.log.error(`Error while matching path pattern "${pattern}"`); + reportCliError(new Error(`Error while matching path pattern "${pattern}"`)); + return undefined; + } +} diff --git a/packages/cli/src/lib/wizard/react-native/gradle.ts b/packages/cli/src/lib/wizard/react-native/gradle.ts new file mode 100644 index 000000000..369d94e1a --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/gradle.ts @@ -0,0 +1,35 @@ +/** + * Add the Sentry Gradle plugin to a React Native Android app's + * `build.gradle`. + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import { reportCliError } from "../../error-reporting.js"; +import { clack } from "../utils/clack/prompts.js"; + +const applyFrom = `apply from: new File(["node", "--print", "require.resolve('@sentry/react-native/package.json')"].execute().text.trim(), "../sentry.gradle")`; + +export function doesAppBuildGradleIncludeRNSentryGradlePlugin( + content: string, +): boolean { + return content.includes("sentry.gradle"); +} + +export function addRNSentryGradlePlugin(content: string): string { + return content.replace(/^android {/m, (match) => `${applyFrom}\n${match}`); +} + +export function writeAppBuildGradle(path: string, newContent: string): void { + try { + const currentContent = readFileSync(path, "utf-8"); + if (newContent === currentContent) { + clack.log.info(`No changes to ${path}.`); + return; + } + + writeFileSync(path, newContent, "utf-8"); + } catch (error) { + clack.log.error(`Error while writing ${path}`); + reportCliError(new Error("Error while writing app/build.gradle")); + } +} diff --git a/packages/cli/src/lib/wizard/react-native/javascript.ts b/packages/cli/src/lib/wizard/react-native/javascript.ts new file mode 100644 index 000000000..2f680e105 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/javascript.ts @@ -0,0 +1,458 @@ +/** + * Add `Sentry.init` to a React Native app's entry file and wrap its root + * component with `Sentry.wrap`. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { reportCliError } from "../../error-reporting.js"; +import chalk from "chalk"; +import path from "node:path"; +import { cwd } from "node:process"; +import { readFileSync, writeFileSync } from "node:fs"; +import { Sentry } from "../telemetry.js"; + +import { traceStep } from "../telemetry.js"; +import { + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { getFirstMatchedPath } from "./glob.js"; +import { RN_SDK_PACKAGE } from "./react-native-wizard.js"; +import { preserveTrailingNewline } from "../utils/ast-utils.js"; + +import { generateCode, type ProxifiedModule, parseModule } from "magicast"; +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; + +const n = recast.types.namedTypes; +const b = recast.types.builders; + +export const sessionReplaySampleRate = 0.1; +export const sessionReplayOnErrorSampleRate = 1.0; + +export async function addSentryInit({ + dsn, + enableSessionReplay = false, + enableFeedbackWidget = false, + enableLogs = false, +}: { + dsn: string; + enableSessionReplay?: boolean | undefined; + enableFeedbackWidget?: boolean | undefined; + enableLogs?: boolean | undefined; +}) { + const jsPath = getMainAppFilePath(); + Sentry.setTag("app-js-file-status", jsPath ? "found" : "not-found"); + if (!jsPath) { + clack.log.warn( + `Could not find main App file. Place the following code snippet close to the Apps Root component.`, + ); + reportCliError(new Error("Could not find main App file.")); + await showCopyPasteInstructions({ + filename: "App.js or _layout.tsx", + codeSnippet: getSentryInitColoredCodeSnippet( + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + ), + hint: "This ensures the Sentry SDK is ready to capture errors.", + }); + return; + } + const jsRelativePath = path.relative(cwd(), jsPath); + + const js = readFileSync(jsPath, "utf-8"); + const includesSentry = doesJsCodeIncludeSdkSentryImport(js, { + sdkPackageName: RN_SDK_PACKAGE, + }); + if (includesSentry) { + Sentry.setTag("app-js-file-status", "already-includes-sentry"); + clack.log.warn( + `${chalk.cyan( + jsRelativePath, + )} already includes Sentry. We wont't add it again.`, + ); + return; + } + + const newContent = addSentryInitWithSdkImport(js, { + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + }); + if (newContent === js) { + Sentry.setTag("app-js-file-status", "no-import-found"); + clack.log.warn( + `Could not find an import in ${chalk.cyan(jsRelativePath)}. Place the following code snippet close to the Apps Root component.`, + ); + await showCopyPasteInstructions({ + filename: jsRelativePath, + codeSnippet: getSentryInitColoredCodeSnippet( + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + ), + hint: "This ensures the Sentry SDK is ready to capture errors.", + }); + return; + } + + traceStep("add-sentry-init", () => { + try { + writeFileSync(jsPath, newContent, "utf-8"); + clack.log.success( + `Added ${chalk.cyan("Sentry.init")} to ${chalk.cyan(jsRelativePath)}.`, + ); + } catch (error) { + clack.log.error(`Error while writing ${jsPath}`); + reportCliError(new Error("Error while writing app.js")); + } + }); + + Sentry.setTag("app-js-file-status", "added-sentry-init"); + clack.log.success( + chalk.green(`${chalk.cyan(jsRelativePath)} changes saved.`), + ); +} + +export function addSentryInitWithSdkImport( + js: string, + { + dsn, + enableSessionReplay = false, + enableFeedbackWidget = false, + enableLogs = false, + }: { + dsn: string; + enableSessionReplay?: boolean | undefined; + enableFeedbackWidget?: boolean | undefined; + enableLogs?: boolean | undefined; + }, +): string { + return js.replace( + // The last import statement: one ending in `;`, or a line-start import + // whose module specifier ends the line (no semicolon). + /^([^]*)(import\s+[^;]*?;$|^import\s(?:[^;]*?\sfrom\s*)?['"][^'"\n]+['"][ \t]*$)/m, + (match: string) => `${match} +${getSentryInitPlainTextSnippet( + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, +)}`, + ); +} + +export function doesJsCodeIncludeSdkSentryImport( + js: string, + { sdkPackageName }: { sdkPackageName: string }, +): boolean { + return !!js.match(sdkPackageName); +} + +export function getSentryInitColoredCodeSnippet( + dsn: string, + enableSessionReplay = false, + enableFeedbackWidget = false, + enableLogs = false, +) { + return makeCodeSnippet(true, (_unchanged, plus, _minus) => { + return plus( + getSentryInitPlainTextSnippet( + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + ), + ); + }); +} + +export function getSentryInitPlainTextSnippet( + dsn: string, + enableSessionReplay = false, + enableFeedbackWidget = false, + enableLogs = false, +) { + return `import * as Sentry from '@sentry/react-native'; + +Sentry.init({ + dsn: '${dsn}', + + // Adds more context data to events (IP address, cookies, user, etc.) + // For more information, visit: https://docs.sentry.io/platforms/react-native/data-management/data-collected/ + sendDefaultPii: true, + + // Enable Logs + enableLogs: ${enableLogs ? "true" : "false"}, +${ + enableSessionReplay + ? ` + // Configure Session Replay + replaysSessionSampleRate: ${sessionReplaySampleRate}, + replaysOnErrorSampleRate: ${sessionReplayOnErrorSampleRate}, +` + : "" +}${getSentryIntegrationsPlainTextSnippet( + enableSessionReplay, + enableFeedbackWidget, + )} + // uncomment the line below to enable Spotlight (https://spotlightjs.com) + // spotlight: __DEV__, +});`; +} + +export function getSentryIntegrationsPlainTextSnippet( + enableSessionReplay = false, + enableFeedbackWidget = false, +) { + if (!enableSessionReplay && !enableFeedbackWidget) { + return ""; + } + return ` integrations: [${ + enableSessionReplay ? "Sentry.mobileReplayIntegration()" : "" + }${enableSessionReplay && enableFeedbackWidget ? ", " : ""}${ + enableFeedbackWidget ? "Sentry.feedbackIntegration()" : "" + }], +`; +} + +function getMainAppFilePath(): string | undefined { + const prefixGlob = "{.,./src,./app}"; + const suffixGlob = "@(j|t|cj|mj)s?(x)"; + const universalGlob = `@(App|_layout).${suffixGlob}`; + const jsFileGlob = `${prefixGlob}/+(${universalGlob})`; + const jsPath = traceStep("find-app-js-file", () => + getFirstMatchedPath(jsFileGlob), + ); + return jsPath; +} + +/** + * This step should be executed after `addSentryInit` + */ +export async function wrapRootComponent() { + const showInstructions = () => + showCopyPasteInstructions({ + filename: "App.js or _layout.tsx", + codeSnippet: getSentryWrapColoredCodeSnippet(), + }); + + const jsPath = getMainAppFilePath(); + Sentry.setTag("app-js-file-status", jsPath ? "found" : "not-found"); + if (!jsPath) { + clack.log.warn( + `Could not find main App file. Please wrap your App's Root component.`, + ); + await showInstructions(); + return; + } + + const jsRelativePath = path.relative(cwd(), jsPath); + + const js = readFileSync(jsPath, "utf-8"); + + const mod = parseModule(js); + const result = checkAndWrapRootComponent(mod); + + if (result === SentryWrapResult.AlreadyWrapped) { + Sentry.setTag("app-js-file-status", "already-includes-sentry-wrap"); + clack.log.warn( + `${chalk.cyan( + jsRelativePath, + )} already includes Sentry.wrap. We wont't add it again.`, + ); + return; + } + + if (result === SentryWrapResult.NotFound) { + clack.log.warn( + `Could not find your App's Root component. Please wrap your App's Root component manually.`, + ); + await showInstructions(); + return; + } + + traceStep("add-sentry-wrap", () => { + try { + const code = preserveTrailingNewline(js, generateCode(mod.$ast).code); + writeFileSync(jsPath, code, "utf-8"); + clack.log.success( + `Added ${chalk.cyan("Sentry.wrap")} to ${chalk.cyan(jsRelativePath)}.`, + ); + } catch (error) { + clack.log.error(`Error while writing ${jsPath}`); + reportCliError(new Error("Error while writing app.js")); + return; + } + }); + + Sentry.setTag("app-js-file-status", "added-sentry-wrap"); + clack.log.success( + chalk.green(`${chalk.cyan(jsRelativePath)} changes saved.`), + ); +} + +/** The outcome of {@link checkAndWrapRootComponent}. */ +export const SentryWrapResult = { + NotFound: "RootComponentNotFound", + AlreadyWrapped: "AlreadyWrapped", + Success: "Success", +} as const; + +/** One of the {@link SentryWrapResult} values. */ +export type SentryWrapResult = + (typeof SentryWrapResult)[keyof typeof SentryWrapResult]; + +export function checkAndWrapRootComponent( + mod: ProxifiedModule, +): SentryWrapResult { + if (doesContainSentryWrap(mod.$ast as t.Program)) { + return SentryWrapResult.AlreadyWrapped; + } + + const defaultExport = getDefaultExport(mod.$ast as t.Program); + if (!defaultExport) { + return SentryWrapResult.NotFound; + } + + const wrappedConfig = wrapWithSentry(defaultExport); + + const replacedDefaultExport = replaceDefaultExport( + mod.$ast as t.Program, + wrappedConfig, + ); + + if (!replacedDefaultExport) { + return SentryWrapResult.NotFound; + } + + return SentryWrapResult.Success; +} + +export function getDefaultExport( + program: t.Program, +): + | t.Identifier + | t.CallExpression + | t.ObjectExpression + | t.FunctionDeclaration + | t.ArrowFunctionExpression + | t.ClassDeclaration + | undefined { + for (const node of program.body) { + if ( + n.ExportDefaultDeclaration.check(node) && + (n.Identifier.check(node.declaration) || + n.CallExpression.check(node.declaration) || + n.ObjectExpression.check(node.declaration) || + n.FunctionDeclaration.check(node.declaration) || + n.ArrowFunctionExpression.check(node.declaration) || + n.ClassDeclaration.check(node.declaration)) + ) { + Sentry.setTag("app-js-file-status", "default-export"); + return node.declaration; + } + } + + Sentry.setTag("app-js-file-status", "default-export-not-found"); + return undefined; +} + +export function wrapWithSentry( + configObj: + | t.Identifier + | t.CallExpression + | t.ObjectExpression + | t.FunctionDeclaration + | t.ArrowFunctionExpression + | t.ClassDeclaration, +): t.CallExpression { + if (n.FunctionDeclaration.check(configObj)) { + return b.callExpression( + b.memberExpression(b.identifier("Sentry"), b.identifier("wrap")), + [ + b.functionExpression.from({ + id: configObj.id ?? null, + params: configObj.params, + body: configObj.body, + generator: configObj.generator ?? false, + async: configObj.async ?? false, + }), + ], + ); + } + + if (n.ArrowFunctionExpression.check(configObj)) { + return b.callExpression( + b.memberExpression(b.identifier("Sentry"), b.identifier("wrap")), + [configObj], + ); + } + + if (n.ClassDeclaration.check(configObj)) { + return b.callExpression( + b.memberExpression(b.identifier("Sentry"), b.identifier("wrap")), + [ + b.classExpression.from({ + id: configObj.id ?? null, + superClass: configObj.superClass ?? null, + body: configObj.body, + decorators: configObj.decorators ?? null, + }), + ], + ); + } + + return b.callExpression( + b.memberExpression(b.identifier("Sentry"), b.identifier("wrap")), + [configObj], + ); +} + +export function replaceDefaultExport( + program: t.Program, + wrappedDefaultExport: t.CallExpression, +): boolean { + for (const node of program.body) { + if (n.ExportDefaultDeclaration.check(node)) { + node.declaration = wrappedDefaultExport; + return true; + } + } + return false; +} + +export function doesContainSentryWrap(program: t.Program): boolean { + for (const node of program.body) { + if (n.ExportDefaultDeclaration.check(node)) { + const declaration = node.declaration; + if (n.CallExpression.check(declaration)) { + const callExpr = declaration; + if (n.MemberExpression.check(callExpr.callee)) { + const callee = callExpr.callee; + if ( + n.Identifier.check(callee.object) && + callee.object.name === "Sentry" && + n.Identifier.check(callee.property) && + callee.property.name === "wrap" + ) { + return true; + } + } + } + } + } + return false; +} + +function getSentryWrapColoredCodeSnippet() { + return makeCodeSnippet(true, (_unchanged, plus, _minus) => { + return plus(`import * as Sentry from '@sentry/react-native'; + +export default Sentry.wrap(App);`); + }); +} diff --git a/packages/cli/src/lib/wizard/react-native/metro.ts b/packages/cli/src/lib/wizard/react-native/metro.ts new file mode 100644 index 000000000..1852e1e94 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/metro.ts @@ -0,0 +1,522 @@ +/** + * Add Sentry to a bare React Native project's Metro config through + * `withSentryConfig`. + */ + +import { clack } from "../utils/clack/prompts.js"; +import { reportCliError } from "../../error-reporting.js"; +import { type ProxifiedModule, parseModule, writeFile } from "magicast"; +import { existsSync, promises } from "node:fs"; +import { Sentry } from "../telemetry.js"; + +import { getLastRequireIndex, hasSentryContent } from "../utils/ast-utils.js"; +import { + abortIfCancelled, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; + +import recast from "recast"; +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; + +const b = recast.types.builders; + +const METRO_CONFIG_FILENAMES = ["metro.config.js", "metro.config.cjs"]; + +export function findMetroConfigPath(): string | undefined { + return METRO_CONFIG_FILENAMES.find((filename) => existsSync(filename)); +} + +export async function patchMetroWithSentryConfig() { + const metroConfigPath = findMetroConfigPath(); + + if (!metroConfigPath) { + clack.log.error( + `No Metro config file found. Expected: ${METRO_CONFIG_FILENAMES.join( + " or ", + )}`, + ); + // Fallback to .js for manual instructions + return await showCopyPasteInstructions({ + filename: "metro.config.js", + codeSnippet: getMetroWithSentryConfigSnippet(true), + }); + } + + const showInstructions = () => + showCopyPasteInstructions({ + filename: metroConfigPath, + codeSnippet: getMetroWithSentryConfigSnippet(true), + }); + + const mod = await parseMetroConfig(metroConfigPath); + if (!mod) { + clack.log.error( + `Could not read from file ${chalk.cyan( + metroConfigPath, + )}, please follow the manual steps.`, + ); + return await showInstructions(); + } + + const success = await patchMetroWithSentryConfigInMemory( + mod, + metroConfigPath, + ); + if (!success) { + return; + } + + const saved = await writeMetroConfig(mod, metroConfigPath); + if (saved) { + clack.log.success( + chalk.green(`${chalk.cyan(metroConfigPath)} changes saved.`), + ); + } else { + clack.log.warn( + `Could not save changes to ${chalk.cyan( + metroConfigPath, + )}, please follow the manual steps.`, + ); + return await showInstructions(); + } +} + +export async function patchMetroWithSentryConfigInMemory( + mod: ProxifiedModule, + metroConfigPath: string, + skipInstructions = false, +): Promise { + const showInstructions = () => { + if (skipInstructions) { + return Promise.resolve(); + } + return showCopyPasteInstructions({ + filename: metroConfigPath, + codeSnippet: getMetroWithSentryConfigSnippet(true), + }); + }; + + if (hasSentryContent(mod.$ast as t.Program)) { + const shouldContinue = await confirmPathMetroConfig(); + if (!shouldContinue) { + await showInstructions(); + return false; + } + } + + const configExpression = getModuleExportsAssignmentRight( + mod.$ast as t.Program, + ); + if (!configExpression) { + clack.log.warn( + "Could not find Metro config, please follow the manual steps.", + ); + reportCliError(new Error("Could not find Metro config.")); + await showInstructions(); + return false; + } + + const wrappedConfig = wrapWithSentryConfig(configExpression); + + const replacedModuleExportsRight = replaceModuleExportsRight( + mod.$ast as t.Program, + wrappedConfig, + ); + if (!replacedModuleExportsRight) { + clack.log.warn( + "Could not automatically wrap the config export, please follow the manual steps.", + ); + reportCliError( + new Error("Could not automatically wrap the config export."), + ); + await showInstructions(); + return false; + } + + const addedSentryMetroImport = addSentryMetroRequireToMetroConfig( + mod.$ast as t.Program, + ); + if (!addedSentryMetroImport) { + clack.log.warn( + "Could not add `@sentry/react-native/metro` import to Metro config, please follow the manual steps.", + ); + reportCliError( + new Error( + "Could not add `@sentry/react-native/metro` import to Metro config.", + ), + ); + await showInstructions(); + return false; + } + + clack.log.success( + `Added Sentry Metro plugin to ${chalk.cyan(metroConfigPath)}.`, + ); + return true; +} + +export async function parseMetroConfig( + configPath: string, +): Promise { + try { + const metroConfigContent = (await promises.readFile(configPath)).toString(); + + return parseModule(metroConfigContent); + } catch (error) { + clack.log.error( + `Could not read Metro config file ${chalk.cyan(configPath)}`, + ); + reportCliError(new Error("Could not read Metro config file")); + return undefined; + } +} + +export async function writeMetroConfig( + mod: ProxifiedModule, + configPath: string, +): Promise { + try { + await writeFile(mod.$ast, configPath); + } catch (e) { + clack.log.error( + `Failed to write to ${chalk.cyan(configPath)}: ${JSON.stringify(e)}`, + ); + reportCliError(new Error("Failed to write to Metro config file")); + return false; + } + return true; +} + +export function addSentrySerializerToMetroConfig( + configObj: t.ObjectExpression, +): boolean { + const serializerProp = getSerializerProp(configObj); + if ("invalid" === serializerProp) { + return false; + } + + // case 1: serializer property doesn't exist yet, so we can just add it + if ("undefined" === serializerProp) { + configObj.properties.push( + b.objectProperty( + b.identifier("serializer"), + b.objectExpression([ + b.objectProperty( + b.identifier("customSerializer"), + b.callExpression(b.identifier("createSentryMetroSerializer"), []), + ), + ]), + ), + ); + return true; + } + + const customSerializerProp = getCustomSerializerProp(serializerProp); + // case 2: serializer.customSerializer property doesn't exist yet, so we just add it + if ( + "undefined" === customSerializerProp && + serializerProp.value.type === "ObjectExpression" + ) { + serializerProp.value.properties.push( + b.objectProperty( + b.identifier("customSerializer"), + b.callExpression(b.identifier("createSentryMetroSerializer"), []), + ), + ); + return true; + } + + return false; +} + +function getCustomSerializerProp( + prop: t.ObjectProperty, +): t.ObjectProperty | "undefined" | "invalid" { + const customSerializerProp = + prop.value.type === "ObjectExpression" && + prop.value.properties.find( + (p) => + "key" in p && + p.key.type === "Identifier" && + p.key.name === "customSerializer", + ); + + if (!customSerializerProp) { + return "undefined"; + } + + if (customSerializerProp.type === "ObjectProperty") { + return customSerializerProp; + } + + return "invalid"; +} + +function getSerializerProp( + obj: t.ObjectExpression, +): t.ObjectProperty | "undefined" | "invalid" { + const serializerProp = obj.properties.find( + (p) => + "key" in p && p.key.type === "Identifier" && p.key.name === "serializer", + ); + + if (!serializerProp) { + return "undefined"; + } + + if (serializerProp.type === "ObjectProperty") { + return serializerProp; + } + + return "invalid"; +} + +export function addSentrySerializerRequireToMetroConfig( + program: t.Program, +): boolean { + const lastRequireIndex = getLastRequireIndex(program); + const sentrySerializerRequire = createSentrySerializerRequire(); + const sentryImportIndex = lastRequireIndex + 1; + if (sentryImportIndex < program.body.length) { + // insert after last require + program.body.splice(lastRequireIndex + 1, 0, sentrySerializerRequire); + } else { + // insert at the beginning + program.body.unshift(sentrySerializerRequire); + } + return true; +} + +export function addSentryMetroRequireToMetroConfig( + program: t.Program, +): boolean { + if (declaresWithSentryConfig(program)) { + return true; + } + const lastRequireIndex = getLastRequireIndex(program); + const sentryMetroRequire = createSentryMetroRequire(); + const sentryImportIndex = lastRequireIndex + 1; + if (sentryImportIndex < program.body.length) { + // insert after last require + program.body.splice(lastRequireIndex + 1, 0, sentryMetroRequire); + } else { + // insert at the beginning + program.body.unshift(sentryMetroRequire); + } + return true; +} + +function wrapWithSentryConfig( + configObj: t.Identifier | t.CallExpression | t.ObjectExpression, +): t.CallExpression { + if ( + configObj.type === "CallExpression" && + configObj.callee.type === "Identifier" && + configObj.callee.name === "withSentryConfig" + ) { + return configObj; + } + return b.callExpression(b.identifier("withSentryConfig"), [configObj]); +} + +/** Whether a top-level `const { withSentryConfig } = ...` already exists. */ +function declaresWithSentryConfig(program: t.Program): boolean { + return program.body.some( + (statement) => + statement.type === "VariableDeclaration" && + statement.declarations.some( + (declarator) => + declarator.type === "VariableDeclarator" && + declarator.id.type === "ObjectPattern" && + declarator.id.properties.some( + (property) => + property.type === "ObjectProperty" && + property.value.type === "Identifier" && + property.value.name === "withSentryConfig", + ), + ), + ); +} + +function replaceModuleExportsRight( + program: t.Program, + wrappedConfig: t.CallExpression, +): boolean { + const moduleExports = getModuleExports(program); + if (!moduleExports) { + return false; + } + + if (moduleExports.expression.type === "AssignmentExpression") { + moduleExports.expression.right = wrappedConfig; + return true; + } + + return false; +} + +/** + * Creates const {createSentryMetroSerializer} = require('@sentry/react-native/dist/js/tools/sentryMetroSerializer'); + */ +function createSentrySerializerRequire() { + return b.variableDeclaration("const", [ + b.variableDeclarator( + b.objectPattern([ + b.objectProperty.from({ + key: b.identifier("createSentryMetroSerializer"), + value: b.identifier("createSentryMetroSerializer"), + shorthand: true, + }), + ]), + b.callExpression(b.identifier("require"), [ + b.literal("@sentry/react-native/dist/js/tools/sentryMetroSerializer"), + ]), + ), + ]); +} + +/** + * Creates const {withSentryConfig} = require('@sentry/react-native/metro'); + */ +function createSentryMetroRequire() { + return b.variableDeclaration("const", [ + b.variableDeclarator( + b.objectPattern([ + b.objectProperty.from({ + key: b.identifier("withSentryConfig"), + value: b.identifier("withSentryConfig"), + shorthand: true, + }), + ]), + b.callExpression(b.identifier("require"), [ + b.literal("@sentry/react-native/metro"), + ]), + ), + ]); +} + +async function confirmPathMetroConfig() { + const shouldContinue = await abortIfCancelled( + clack.select({ + message: `Metro Config already contains Sentry-related code. Should the wizard modify it anyway?`, + options: [ + { + label: "Yes, add the Sentry Metro plugin", + value: true, + }, + { + label: "No, show me instructions to manually add the plugin", + value: false, + }, + ], + initialValue: true, + }), + ); + + if (!shouldContinue) { + Sentry.setTag("ast-mod-fail-reason", "has-sentry-content"); + } + + return shouldContinue; +} + +/** + * Returns value from `module.exports = value` or `const config = value` + */ +export function getMetroConfigObject( + program: t.Program, +): t.ObjectExpression | undefined { + // check config variable + const configVariable = program.body.find((s) => { + if (s.type !== "VariableDeclaration" || s.declarations.length !== 1) { + return false; + } + const [declaration] = s.declarations; + return ( + declaration?.type === "VariableDeclarator" && + declaration.id.type === "Identifier" && + declaration.id.name === "config" + ); + }) as t.VariableDeclaration | undefined; + + const configDeclaration = configVariable?.declarations[0]; + if ( + configDeclaration?.type === "VariableDeclarator" && + configDeclaration.init?.type === "ObjectExpression" + ) { + Sentry.setTag("metro-config", "config-variable"); + return configDeclaration.init; + } + + return getModuleExportsObject(program); +} + +function getModuleExportsObject( + program: t.Program, +): t.ObjectExpression | undefined { + // check module.exports + const moduleExports = getModuleExportsAssignmentRight(program); + + if (moduleExports?.type === "ObjectExpression") { + return moduleExports; + } + + Sentry.setTag("metro-config", "not-found"); + return undefined; +} + +export function getModuleExportsAssignmentRight( + program: t.Program, +): t.Identifier | t.CallExpression | t.ObjectExpression | undefined { + // check module.exports + const moduleExports = getModuleExports(program); + + if ( + moduleExports?.expression.type === "AssignmentExpression" && + (moduleExports.expression.right.type === "ObjectExpression" || + moduleExports.expression.right.type === "CallExpression" || + moduleExports.expression.right.type === "Identifier") + ) { + Sentry.setTag("metro-config", "module-exports"); + return moduleExports.expression.right; + } + + Sentry.setTag("metro-config", "not-found"); + return undefined; +} + +function getModuleExports( + program: t.Program, +): t.ExpressionStatement | undefined { + // find module.exports + return program.body.find((s) => { + if ( + s.type === "ExpressionStatement" && + s.expression.type === "AssignmentExpression" && + s.expression.left.type === "MemberExpression" && + s.expression.left.object.type === "Identifier" && + s.expression.left.object.name === "module" && + s.expression.left.property.type === "Identifier" && + s.expression.left.property.name === "exports" + ) { + return true; + } + return false; + }) as t.ExpressionStatement | undefined; +} + +function getMetroWithSentryConfigSnippet(colors: boolean) { + return makeCodeSnippet(colors, (unchanged, plus, _) => + unchanged(`const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config'); +${plus("const {withSentryConfig} = require('@sentry/react-native/metro');")} + +const config = {}; + +module.exports = ${plus( + "withSentryConfig(", + )}mergeConfig(getDefaultConfig(__dirname), config)${plus(")")}; +`), + ); +} diff --git a/packages/cli/src/lib/wizard/react-native/options.ts b/packages/cli/src/lib/wizard/react-native/options.ts new file mode 100644 index 000000000..08853d303 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/options.ts @@ -0,0 +1,7 @@ +/** + * Options of the React Native wizard. + */ + +import { type WizardOptions } from "../utils/types.js"; + +export type ReactNativeWizardOptions = WizardOptions; diff --git a/packages/cli/src/lib/wizard/react-native/react-native-wizard.ts b/packages/cli/src/lib/wizard/react-native/react-native-wizard.ts new file mode 100644 index 000000000..531310eb5 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/react-native-wizard.ts @@ -0,0 +1,537 @@ +/** + * The React Native wizard (`sentry wizard reactNative`): installs + * `@sentry/react-native`, initializes it, and sets up source map and debug + * file uploads for Xcode, Gradle, Metro and Expo. + */ + +import { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { existsSync, readFileSync } from "node:fs"; + +import { Sentry } from "../telemetry.js"; +import { platform } from "node:os"; +import { addModularHeaders, podInstall, usesCocoaPod } from "./cocoapod.js"; +import { traceStep, withTelemetry } from "../telemetry.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { + type CliSetupConfigContent, + abort, + abortIfCancelled, + addSentryCliConfig, + confirmContinueIfNoOrDirtyGitRepo, + confirmContinueIfPackageVersionNotSupported, + ensurePackageIsInstalled, + getOrAskForProjectData, + getPackageDotJson, + installPackage, + printWelcome, + propertiesCliSetupConfig, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import { + isExpoCNG, + patchExpoAppConfig, + printSentryExpoMigrationOutro, +} from "./expo.js"; +import { addExpoEnvLocal } from "./expo-env-file.js"; +import { addSentryToExpoMetroConfig } from "./expo-metro.js"; +import { + APP_BUILD_GRADLE, + XCODE_PROJECT, + getFirstMatchedPath, +} from "./glob.js"; +import { + addRNSentryGradlePlugin, + doesAppBuildGradleIncludeRNSentryGradlePlugin, + writeAppBuildGradle, +} from "./gradle.js"; +import { + addSentryInit, + sessionReplayOnErrorSampleRate, + sessionReplaySampleRate, + wrapRootComponent, +} from "./javascript.js"; +import { patchMetroWithSentryConfig } from "./metro.js"; +import { type ReactNativeWizardOptions } from "./options.js"; +import { + addDebugFilesUploadPhaseWithBundledScripts, + addSentryWithBundledScriptsToBundleShellScript, + findBundlePhase, + findDebugFilesUploadPhase, + getValidExistingBuildPhases, + patchBundlePhase, + usesSwiftPMAutolinking, + writeXcodeProject, +} from "./xcode.js"; + +import xcode from "xcode"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; + +export const RN_SDK_PACKAGE = "@sentry/react-native"; +export const RN_SDK_SUPPORTED_RANGE = ">=6.12.0"; + +export const RN_PACKAGE = "react-native"; +export const RN_HUMAN_NAME = "React Native"; + +export const SUPPORTED_RN_RANGE = ">=0.69.0"; +export const SUPPORTED_EXPO_RANGE = ">=50.0.0"; + +export type RNCliSetupConfigContent = Pick< + Required, + "authToken" | "org" | "project" | "url" +>; + +export async function runReactNativeWizard( + params: ReactNativeWizardOptions, +): Promise { + return await withTelemetry( + { + enabled: params.telemetryEnabled, + integration: "react-native", + wizardOptions: params, + }, + () => runReactNativeWizardWithTelemetry(params), + ); +} + +export async function runReactNativeWizardWithTelemetry( + options: ReactNativeWizardOptions, +): Promise { + const { telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry React Native Wizard", + telemetryEnabled, + }); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + const hasInstalled = (dep: string) => hasPackageInstalled(dep, packageJson); + + if (hasInstalled("sentry-expo")) { + Sentry.setTag("has-sentry-expo-installed", true); + printSentryExpoMigrationOutro(); + return; + } + + await ensurePackageIsInstalled(packageJson, RN_PACKAGE, RN_HUMAN_NAME); + + const rnVersion = getPackageVersion(RN_PACKAGE, packageJson); + if (rnVersion) { + await confirmContinueIfPackageVersionNotSupported({ + packageName: RN_HUMAN_NAME, + packageVersion: rnVersion, + packageId: RN_PACKAGE, + acceptableVersions: SUPPORTED_RN_RANGE, + note: `Please upgrade to ${SUPPORTED_RN_RANGE} if you wish to use the Sentry Wizard. +Or setup using ${chalk.cyan( + "https://docs.sentry.io/platforms/react-native/manual-setup/manual-setup/", + )}`, + }); + } + + await installPackage({ + packageName: RN_SDK_PACKAGE, + alreadyInstalled: hasPackageInstalled(RN_SDK_PACKAGE, packageJson), + forceInstall, + }); + const sdkVersion = getPackageVersion( + RN_SDK_PACKAGE, + await getPackageDotJson(), + ); + if (sdkVersion) { + await confirmContinueIfPackageVersionNotSupported({ + packageName: "Sentry React Native SDK", + packageVersion: sdkVersion, + packageId: RN_SDK_PACKAGE, + acceptableVersions: RN_SDK_SUPPORTED_RANGE, + note: `Please upgrade to ${RN_SDK_SUPPORTED_RANGE} to continue with the wizard in this project.`, + }); + } else { + const continueWithoutSdk = await abortIfCancelled( + clack.confirm({ + message: + "Could not detect Sentry React Native SDK version. Do you want to continue anyway?", + }), + ); + if (!continueWithoutSdk) { + await abort(undefined, 0); + } + } + Sentry.setTag(`detected-sentry-react-native-sdk-version`, sdkVersion); + + const expoVersion = getPackageVersion("expo", packageJson); + const isExpo = !!expoVersion; + if (expoVersion) { + await confirmContinueIfPackageVersionNotSupported({ + packageName: "Expo SDK", + packageVersion: expoVersion, + packageId: "expo", + acceptableVersions: SUPPORTED_EXPO_RANGE, + note: `Please upgrade to ${SUPPORTED_EXPO_RANGE} to continue with the wizard in this Expo project.`, + }); + } + + const projectData = await getOrAskForProjectData(options, "react-native"); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("React Native"); + } + + const { selectedProject, authToken, sentryUrl } = projectData; + const orgSlug = selectedProject.organization.slug; + const projectSlug = selectedProject.slug; + const projectId = selectedProject.id; + const cliConfig: RNCliSetupConfigContent = { + authToken, + org: orgSlug, + project: projectSlug, + url: sentryUrl, + }; + + // Ask if user wants to enable Logs + const enableLogs = await abortIfCancelled( + clack.confirm({ + message: + "Do you want to enable Logs? Structured logs allow you to send, view and query logs and parameters sent from your applications (See https://docs.sentry.io/platforms/react-native/logs/)", + }), + ); + Sentry.setTag("enable-logs", enableLogs); + + if (enableLogs) { + clack.log.info( + `Logs will be enabled with default settings. You can send logs using the Sentry.logger APIs.`, + ); + } + + // Ask if user wants to enable Session Replay + const enableSessionReplay = await abortIfCancelled( + clack.confirm({ + message: + "Do you want to enable Session Replay to help debug issues? (See https://docs.sentry.io/platforms/react-native/session-replay/)", + }), + ); + Sentry.setTag("enable-session-replay", enableSessionReplay); + + if (enableSessionReplay) { + clack.log.info( + `Session Replay will be enabled with default settings (replaysSessionSampleRate: ${sessionReplaySampleRate}, replaysOnErrorSampleRate: ${sessionReplayOnErrorSampleRate}).`, + ); + clack.log.message( + "By default, all text content, images, and webviews will be masked for privacy. You can customize this in your code later.", + ); + } + + // Ask if user wants to enable the User Feedback Widget + const enableFeedbackWidget = await abortIfCancelled( + clack.confirm({ + message: + "Do you want to enable the User Feedback Widget to collect feedback from your users? (See https://docs.sentry.io/platforms/react-native/user-feedback/)", + }), + ); + Sentry.setTag("enable-feedback-widget", enableFeedbackWidget); + + if (enableFeedbackWidget) { + clack.log.info( + `The User Feedback Widget will be enabled with default settings. You can show the widget by calling Sentry.showFeedbackWidget() in your code.`, + ); + } + + await traceStep("patch-app-js", () => + addSentryInit({ + dsn: selectedProject.keys[0].dsn.public, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + }), + ); + + await traceStep("patch-app-js-wrap", () => wrapRootComponent()); + + if (isExpo) { + await traceStep("patch-expo-app-config", () => + patchExpoAppConfig(cliConfig), + ); + await traceStep("add-expo-env-local", () => addExpoEnvLocal(cliConfig)); + } + + if (isExpo) { + await traceStep("patch-metro-config", addSentryToExpoMetroConfig); + } else { + await traceStep("patch-metro-config", patchMetroWithSentryConfig); + } + + if (isExpo && (await isExpoCNG())) { + Sentry.setTag("expo-cng", true); + clack.log.info( + `Detected Expo Continuous Native Generation (CNG) setup. Skipping native files patching.`, + ); + } else { + if (existsSync("ios")) { + Sentry.setTag("patch-ios", true); + await traceStep("patch-xcode-files", () => patchXcodeFiles(cliConfig)); + } + + if (existsSync("android")) { + Sentry.setTag("patch-android", true); + await traceStep("patch-android-files", () => + patchAndroidFiles(cliConfig), + ); + } + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + const confirmedFirstException = await confirmFirstSentryException( + orgSlug, + projectId, + ); + + Sentry.setTag("user-confirmed-first-error", confirmedFirstException); + + if (confirmedFirstException) { + clack.outro( + `${chalk.green("Everything is set up!")} + + ${chalk.dim( + "If you encounter any issues, let us know here: https://github.com/getsentry/sentry-react-native/issues", + )}`, + ); + } else { + clack.outro( + chalk.dim( + "Let us know here: https://github.com/getsentry/sentry-react-native/issues", + ), + ); + } +} + +/** Asks whether the test event arrived; Ctrl+C exits the wizard. */ +export async function confirmFirstSentryException( + orgSlug: string, + projectId: string, +) { + const issuesStreamUrl = buildProjectIssuesUrl(orgSlug, projectId); + + clack.log + .step(`To make sure everything is set up correctly, put the following code snippet into your application. +The snippet will create a button that, when tapped, sends a test event to Sentry. + +After that check your project issues: + +${chalk.cyan(issuesStreamUrl)}`); + + // We want the code snippet to be easily copy-pasteable, without any clack artifacts + clack.rawOutput( + chalk.greenBright(` +