From 949060de6ede9e82943d381bbbc379f775ed6e5b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:48:12 +0000 Subject: [PATCH 01/18] feat(cli): add sentry wizard with Next.js Start moving getsentry/sentry-wizard into the CLI as `sentry wizard`. This adds the command with the `@sentry/wizard` integrations and flags (`-i`, `--url`, `--org`, `--project`, `--saas`, `--spotlight`, and the rest), the shared wizard helpers, and the Next.js flow. The other integrations report that they are not available in this version yet. The wizard logs in with the CLI's own login: a stored `sentry auth login` session, an agent handoff, or the device flow, instead of the `account/settings/wizard/` browser flow. It then picks or creates the project, reads its DSN, and creates an org auth token for source map uploads. Telemetry goes through the CLI's client. `sentry init` stays the agent setup guide; its help now points to `sentry wizard` for the interactive setup. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/content/docs/contributing.md | 3 +- .../cli-docs/src/fragments/commands/wizard.md | 24 + packages/cli/package.json | 1 + .../sentry-cli/skills/sentry-cli/SKILL.md | 8 + .../skills/sentry-cli/references/wizard.md | 44 + packages/cli/src/app.ts | 2 + packages/cli/src/command-manifest.ts | 1 + packages/cli/src/commands/init.ts | 4 +- packages/cli/src/commands/wizard.ts | 221 ++ packages/cli/src/lib/env-registry.ts | 18 + packages/cli/src/lib/errors.ts | 15 + packages/cli/src/lib/telemetry.ts | 13 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 1325 ++++++++++++ .../cli/src/lib/wizard/nextjs/templates.ts | 910 +++++++++ packages/cli/src/lib/wizard/nextjs/utils.ts | 182 ++ packages/cli/src/lib/wizard/run.ts | 128 ++ packages/cli/src/lib/wizard/sourcemaps/ci.ts | 130 ++ packages/cli/src/lib/wizard/telemetry.ts | 78 + .../cli/src/lib/wizard/utils/clack/index.ts | 1781 +++++++++++++++++ .../src/lib/wizard/utils/clack/mcp-config.ts | 639 ++++++ .../cli/src/lib/wizard/utils/clack/prompts.ts | 71 + .../src/lib/wizard/utils/data-collection.ts | 122 ++ packages/cli/src/lib/wizard/utils/debug.ts | 32 + packages/cli/src/lib/wizard/utils/git.ts | 75 + .../cli/src/lib/wizard/utils/node-version.ts | 50 + .../cli/src/lib/wizard/utils/package-json.ts | 186 ++ .../src/lib/wizard/utils/package-manager.ts | 239 +++ .../cli/src/lib/wizard/utils/project-data.ts | 479 +++++ packages/cli/src/lib/wizard/utils/semver.ts | 65 + packages/cli/src/lib/wizard/utils/types.ts | 104 + packages/cli/src/top-level-briefs.ts | 1 + packages/cli/test/commands/wizard.test.ts | 131 ++ .../test/lib/wizard/nextjs/templates.test.ts | 963 +++++++++ .../cli/test/lib/wizard/nextjs/utils.test.ts | 232 +++ .../wizard-double-wrap-prevention.test.ts | 300 +++ .../test/lib/wizard/utils/clack/index.test.ts | 719 +++++++ .../lib/wizard/utils/clack/mcp-config.test.ts | 1049 ++++++++++ .../lib/wizard/utils/data-collection.test.ts | 92 + .../cli/test/lib/wizard/utils/git.test.ts | 126 ++ .../lib/wizard/utils/node-version.test.ts | 69 + .../lib/wizard/utils/package-json.test.ts | 594 ++++++ .../lib/wizard/utils/package-manager.test.ts | 37 + .../lib/wizard/utils/project-data.test.ts | 252 +++ pnpm-lock.yaml | 50 + 44 files changed, 11563 insertions(+), 2 deletions(-) create mode 100644 apps/cli-docs/src/fragments/commands/wizard.md create mode 100644 packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md create mode 100644 packages/cli/src/commands/wizard.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/templates.ts create mode 100644 packages/cli/src/lib/wizard/nextjs/utils.ts create mode 100644 packages/cli/src/lib/wizard/run.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/ci.ts create mode 100644 packages/cli/src/lib/wizard/telemetry.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/index.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/mcp-config.ts create mode 100644 packages/cli/src/lib/wizard/utils/clack/prompts.ts create mode 100644 packages/cli/src/lib/wizard/utils/data-collection.ts create mode 100644 packages/cli/src/lib/wizard/utils/debug.ts create mode 100644 packages/cli/src/lib/wizard/utils/git.ts create mode 100644 packages/cli/src/lib/wizard/utils/node-version.ts create mode 100644 packages/cli/src/lib/wizard/utils/package-json.ts create mode 100644 packages/cli/src/lib/wizard/utils/package-manager.ts create mode 100644 packages/cli/src/lib/wizard/utils/project-data.ts create mode 100644 packages/cli/src/lib/wizard/utils/semver.ts create mode 100644 packages/cli/src/lib/wizard/utils/types.ts create mode 100644 packages/cli/test/commands/wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/utils.test.ts create mode 100644 packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/clack/index.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/data-collection.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/git.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/node-version.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/package-json.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/package-manager.test.ts create mode 100644 packages/cli/test/lib/wizard/utils/project-data.test.ts diff --git a/apps/cli-docs/src/content/docs/contributing.md b/apps/cli-docs/src/content/docs/contributing.md index c10e6eb026..208c1d8747 100644 --- a/apps/cli-docs/src/content/docs/contributing.md +++ b/apps/cli-docs/src/content/docs/contributing.md @@ -97,7 +97,8 @@ toolkit/ │ │ │ ├── init.ts # Print instructions for a coding agent to set up Sentry │ │ │ ├── mcp.ts # Start a local Sentry MCP server │ │ │ ├── schema.ts # Browse the Sentry API schema -│ │ │ └── wasm-split.ts# Add build ids to WebAssembly modules and split out debug data +│ │ │ ├── wasm-split.ts# Add build ids to WebAssembly modules and split out debug data +│ │ │ └── wizard.ts # Set up the Sentry SDK in your project interactively │ │ ├── lib/ # Shared utilities │ │ └── types/ # TypeScript types and Valibot schemas │ ├── test/ # Test files (mirrors src/ structure) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md new file mode 100644 index 0000000000..1e49305bdb --- /dev/null +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -0,0 +1,24 @@ + + +## Setting up Sentry interactively + +`sentry wizard` sets up the Sentry SDK in the project in the current +directory. It asks a few questions, installs the SDK for your framework, +writes its configuration, and sets up source map or debug file uploads. +Pass `-i` with an integration, such as `nextjs`, to skip the integration +picker. + +It logs in with your `sentry auth login` account, or starts a login when you +have none, and lets you pick or create the Sentry project to send data to. +Pass `--org` and `--project` to skip those questions. + +`sentry wizard` changes your project's files. To have a coding agent set up +Sentry instead, run `sentry init`, which prints the agent's setup guide and +changes nothing. + +## Coming from `@sentry/wizard` + +`sentry wizard` takes the same integrations and flags as +`npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and +`sentry wizard -i nextjs` do the same thing. The Cordova and Electron wizards +were removed; follow their setup guides in the Sentry docs instead. diff --git a/packages/cli/package.json b/packages/cli/package.json index fc2d5ef556..ebda846304 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -131,6 +131,7 @@ "http-cache-semantics": "^4.2.0", "ignore": "^7.0.5", "jpeg-js": "^0.4.4", + "magicast": "0.2.11", "marked": "catalog:", "node-sqlite3-wasm": "0.8.59", "p-limit": "^7.3.0", diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 70ab0025b3..963ccb51a1 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -814,6 +814,14 @@ Print instructions for a coding agent to set up Sentry → Full flags and examples: `references/init.md` +### Wizard + +Set up the Sentry SDK in your project interactively + +- `sentry wizard` — Set up the Sentry SDK in your project interactively + +→ Full flags and examples: `references/wizard.md` + ### Info Print configuration and verify authentication diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md new file mode 100644 index 0000000000..37be843225 --- /dev/null +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -0,0 +1,44 @@ +--- +name: sentry-cli-wizard +version: 0.52.0-dev.0 +description: Set up the Sentry SDK in your project interactively +requires: + bins: ["sentry"] + auth: true +--- + +# Wizard Commands + +Set up the Sentry SDK in your project interactively + +### `sentry wizard` + +Set up the Sentry SDK in your project interactively + +**Flags:** +- `-i, --integration - Integration to set up (skips the picker)` +- `-u, --url - URL of your self-hosted Sentry instance` +- `--org - Slug of the Sentry organization to use` +- `--project - Slug of the Sentry project to use` +- `--saas - Use Sentry SaaS (sentry.io) without asking` +- `--spotlight - Set up Spotlight for local development, without a Sentry account` +- `--force-install - Install the SDK even when the package manager's checks fail` +- `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` +- `--disable-telemetry - Don't send telemetry about this run to Sentry` +- `--debug - Print the wizard's debug output` +- `--promo-code - Promo code to apply when signing up` + +**Examples:** + +```bash +# Pick an integration and set it up +sentry wizard + +# Set up Next.js for a known org and project on sentry.io +sentry wizard -i nextjs --saas --org my-org --project my-project + +# Set up Next.js for Spotlight, without a Sentry account +sentry wizard -i nextjs --spotlight +``` + +All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/packages/cli/src/app.ts b/packages/cli/src/app.ts index bfc9ef4f25..870afced8e 100644 --- a/packages/cli/src/app.ts +++ b/packages/cli/src/app.ts @@ -66,6 +66,7 @@ import { listCommand as traceListCommand } from "./commands/trace/list.js"; import { trialRoute } from "./commands/trial/index.js"; import { listCommand as trialListCommand } from "./commands/trial/list.js"; import { wasmSplitCommand } from "./commands/wasm-split.js"; +import { wizardCommand } from "./commands/wizard.js"; import { buildSentryApp, buildSentryRoutes } from "./app-root.js"; import { registerGraphicsBanner } from "./graphics-banner.js"; @@ -116,6 +117,7 @@ export const routes = buildSentryRoutes({ trace: traceRoute, trial: trialRoute, init: initCommand, + wizard: wizardCommand, info: infoCommand, local: localRoute, api: apiCommand, diff --git a/packages/cli/src/command-manifest.ts b/packages/cli/src/command-manifest.ts index 93ecb09e4f..9758b18f7d 100644 --- a/packages/cli/src/command-manifest.ts +++ b/packages/cli/src/command-manifest.ts @@ -139,6 +139,7 @@ export const COMMAND_MANIFEST: Readonly> = { trace: route(() => import("./commands/trace/index.js"), "traceRoute"), trial: route(() => import("./commands/trial/index.js"), "trialRoute"), init: route(() => import("./commands/init.js"), "initCommand"), + wizard: route(() => import("./commands/wizard.js"), "wizardCommand"), info: route(() => import("./commands/info.js"), "infoCommand"), local: route(() => import("./commands/local/index.js"), "localRoute"), api: route(() => import("./commands/api.js"), "apiCommand"), diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 334915591f..e6dcd6c6e3 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -50,7 +50,9 @@ export const initCommand = buildCommand({ "project already uses Sentry, the guide covers upgrading the SDKs and " + "turning on more features instead.\n\n" + "The command changes nothing and needs no login. The same guide is " + - "published at https://cli.sentry.dev/get-started-with-sentry.md.", + "published at https://cli.sentry.dev/get-started-with-sentry.md.\n\n" + + "To set up Sentry yourself with an interactive wizard that changes " + + "your project's files, run `sentry wizard` instead.", examples: [ { description: "Print the setup guide", diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts new file mode 100644 index 0000000000..b48e6a6d2e --- /dev/null +++ b/packages/cli/src/commands/wizard.ts @@ -0,0 +1,221 @@ +/** + * sentry wizard + * + * Run the interactive setup wizard of a framework or platform: it installs + * the Sentry SDK, writes its config files, and sets up source map or debug + * file uploads in the current project. Ported from `@sentry/wizard`, whose + * `-i ` invocations keep working. + * + * The wizard logs in with the CLI's own login instead of the old browser + * hand-off, so `auth: false` here: a run in Spotlight mode, or with a + * preselected project, needs no login at all. + */ + +import type { SentryContext } from "../context.js"; +import { buildCommand } from "../lib/command.js"; +import { + parseOrgSlug, + parseProjectSlug, + parseText, + parseUrl, +} from "../lib/completion-target.js"; +import { getEnv } from "../lib/env.js"; +import { WizardExitError } from "../lib/errors.js"; +import { + disableTelemetryForRun, + isTelemetryEnabled, +} from "../lib/telemetry.js"; +import { INTEGRATION_IDS, runWizard } from "../lib/wizard/run.js"; +import { topLevelBrief } from "../top-level-briefs.js"; + +type WizardFlags = { + readonly integration?: string; + readonly url?: string; + readonly org?: string; + readonly project?: string; + readonly saas: boolean; + readonly debug: boolean; + readonly spotlight: boolean; + readonly "disable-telemetry": boolean; + readonly "force-install": boolean; + readonly "ignore-git-changes": boolean; + readonly "promo-code"?: string; + readonly "coming-from"?: string; + readonly signup: boolean; + readonly "skip-connect": boolean; + readonly quiet: boolean; + readonly uninstall: boolean; +}; + +/** The trimmed value of the environment variable `name`, unless empty. */ +function envValue(name: string): string | undefined { + return getEnv()[name]?.trim() || undefined; +} + +export const wizardCommand = buildCommand({ + auth: false, + docs: { + brief: topLevelBrief("wizard"), + fullDescription: + "Set up Sentry in the project in the current directory. The wizard " + + "asks you a few questions, installs the Sentry SDK for your framework, " + + "writes its configuration, and sets up source map or debug file " + + "uploads. It logs in with your `sentry auth login` account (or starts " + + "a login), and lets you pick or create the Sentry project to send " + + "data to.\n\n" + + "Pass `-i` to skip the integration picker. These are the same " + + "integrations and flags `npx @sentry/wizard` takes.\n\n" + + "The wizard changes files in your project. To have a coding agent set " + + "up Sentry instead, run `sentry init`, which prints the agent's setup " + + "guide and changes nothing.", + examples: [ + { + description: "Pick an integration and set it up", + run: "wizard", + }, + { + description: "Set up Next.js for a known org and project on sentry.io", + run: "wizard -i nextjs --saas --org my-org --project my-project", + }, + { + description: "Set up Next.js for Spotlight, without a Sentry account", + run: "wizard -i nextjs --spotlight", + }, + ], + }, + parameters: { + flags: { + integration: { + kind: "enum", + values: INTEGRATION_IDS, + brief: "Integration to set up (skips the picker)", + optional: true, + }, + url: { + kind: "parsed", + parse: parseUrl, + brief: "URL of your self-hosted Sentry instance", + placeholder: "url", + optional: true, + }, + org: { + kind: "parsed", + parse: parseOrgSlug, + brief: "Slug of the Sentry organization to use", + placeholder: "org", + optional: true, + }, + project: { + kind: "parsed", + parse: parseProjectSlug, + brief: "Slug of the Sentry project to use", + placeholder: "project", + optional: true, + }, + saas: { + kind: "boolean", + brief: "Use Sentry SaaS (sentry.io) without asking", + default: false, + }, + spotlight: { + kind: "boolean", + brief: + "Set up Spotlight for local development, without a Sentry account", + default: false, + }, + "force-install": { + kind: "boolean", + brief: "Install the SDK even when the package manager's checks fail", + default: false, + }, + "ignore-git-changes": { + kind: "boolean", + brief: "Don't ask before changing a project with uncommitted changes", + default: false, + }, + "disable-telemetry": { + kind: "boolean", + brief: "Don't send telemetry about this run to Sentry", + default: false, + }, + debug: { + kind: "boolean", + brief: "Print the wizard's debug output", + default: false, + }, + "promo-code": { + kind: "parsed", + parse: parseText, + brief: "Promo code to apply when signing up", + placeholder: "code", + optional: true, + }, + "coming-from": { + kind: "parsed", + parse: parseText, + brief: "Partner the command was copied from, such as vercel", + placeholder: "partner", + optional: true, + hidden: true as const, + }, + // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so + // copied commands still run. + signup: { + kind: "boolean", + brief: "Ignored: the login page offers sign-up", + default: false, + hidden: true as const, + }, + "skip-connect": { + kind: "boolean", + brief: "Ignored", + default: false, + hidden: true as const, + }, + quiet: { + kind: "boolean", + brief: "Ignored", + default: false, + hidden: true as const, + }, + uninstall: { + kind: "boolean", + brief: "Ignored: only the retired Cordova wizard could uninstall", + default: false, + hidden: true as const, + }, + }, + aliases: { i: "integration", u: "url", s: "signup" }, + }, + // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. + async *func(this: SentryContext, flags: WizardFlags) { + if (flags["disable-telemetry"]) { + disableTelemetryForRun(); + } + + try { + await runWizard({ + integration: flags.integration ?? envValue("SENTRY_WIZARD_INTEGRATION"), + debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", + wizardOptions: { + telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), + promoCode: flags["promo-code"], + url: flags.url ?? envValue("SENTRY_WIZARD_URL"), + orgSlug: flags.org, + projectSlug: flags.project, + saas: flags.saas, + forceInstall: flags["force-install"], + comingFrom: flags["coming-from"], + ignoreGitChanges: flags["ignore-git-changes"], + spotlight: flags.spotlight, + }, + }); + } catch (error) { + if (!(error instanceof WizardExitError)) { + throw error; + } + // The wizard already explained why it stopped. + process.exitCode = error.exitCode; + } + }, +}); diff --git a/packages/cli/src/lib/env-registry.ts b/packages/cli/src/lib/env-registry.ts index 581c0c0a9c..b9b5edb556 100644 --- a/packages/cli/src/lib/env-registry.ts +++ b/packages/cli/src/lib/env-registry.ts @@ -139,6 +139,24 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ selfHosted: true, devGuide: "Sentry OAuth app client ID", }, + { + name: "SENTRY_WIZARD_INTEGRATION", + description: + "Integration for `sentry wizard` to set up when `-i` is not passed, such as `nextjs`. Kept from `@sentry/wizard`.", + example: "nextjs", + }, + { + name: "SENTRY_WIZARD_URL", + description: + "URL of the self-hosted Sentry instance for `sentry wizard` when `--url` is not passed. Kept from `@sentry/wizard`.", + example: "https://sentry.example.com", + }, + { + name: "SENTRY_WIZARD_DEBUG", + description: + "Set to `true` to print the debug output of `sentry wizard`, like `--debug`. Kept from `@sentry/wizard`.", + example: "true", + }, { name: "SENTRY_HANDOFF", description: diff --git a/packages/cli/src/lib/errors.ts b/packages/cli/src/lib/errors.ts index 37bdcbd010..54bc169566 100644 --- a/packages/cli/src/lib/errors.ts +++ b/packages/cli/src/lib/errors.ts @@ -791,6 +791,21 @@ export class VerifyFailedError extends CliError { } } +/** + * A setup wizard stopped: the user declined or cancelled a prompt (exit + * code 0), or the wizard can't continue (1). The wizard has already told the + * user why in its own output, so `sentry wizard` exits with `exitCode` + * without printing this error. + * + * @param exitCode - 0 when the user chose to stop, else the failure's code + */ +export class WizardExitError extends CliError { + constructor(exitCode: number) { + super("The setup wizard stopped.", exitCode); + this.name = "WizardExitError"; + } +} + /** * OAuth device flow errors (RFC 8628). * diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index 2467c3f349..b4e32c1640 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -176,6 +176,19 @@ export function isTelemetryEnabled(): boolean { return computeTelemetryEffective().enabled; } +/** + * Stop sending telemetry for the rest of this run, after `withTelemetry` + * already started it: the client drops every envelope from now on, including + * the command's own transaction. For flags such as `sentry wizard + * --disable-telemetry` that opt out of one run. + */ +export function disableTelemetryForRun(): void { + const client = Sentry.getClient(); + if (client) { + client.getOptions().enabled = false; + } +} + /** * Attributes a Snake score metric may carry. Everything else the SDK adds * (user.*, replay ids, ...) is dropped so a score cannot be linked to a user. diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts new file mode 100644 index 0000000000..ef8e11b357 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -0,0 +1,1325 @@ +/** + * The Next.js setup wizard: installs `@sentry/nextjs`, wraps the Next.js + * config with `withSentryConfig`, and writes the SDK init files, an example + * page, and the auth token for source map uploads. + */ + +import { clack } from "../utils/clack/prompts.js"; +import chalk from "chalk"; +import { + existsSync, + lstatSync, + mkdirSync, + promises, + readFileSync, + unlinkSync, +} from "node:fs"; +import { parseModule } from "magicast"; +import path from "node:path"; + +import { Sentry } from "../telemetry.js"; + +import { setupCI } from "../sourcemaps/ci.js"; +import { traceStep, withTelemetry } from "../telemetry.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + createNewConfigFile, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + isUsingTypeScript, + printWelcome, + runFormatters, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { SentryProjectData, WizardOptions } from "../utils/types.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { + getFullUnderscoreErrorCopyPasteSnippet, + getGlobalErrorCopyPasteSnippet, + getInstrumentationHookContent, + getInstrumentationHookCopyPasteSnippet, + getNextjsConfigCjsAppendix, + getNextjsConfigCjsTemplate, + getNextjsConfigEsmCopyPasteSnippet, + getNextjsConfigMjsTemplate, + getRootLayout, + getSentryServersideConfigContents, + getInstrumentationClientFileContents, + getSentryDefaultGlobalErrorPage, + getSentryDefaultUnderscoreErrorPage, + getSentryExampleAppDirApiRoute, + getSentryExamplePageContents, + getSentryExamplePagesDirApiRoute, + getSimpleUnderscoreErrorCopyPasteSnippet, + getWithSentryConfigOptionsTemplate, + getInstrumentationClientHookCopyPasteSnippet, + getRootLayoutWithGenerateMetadata, + getGenerateMetadataSnippet, +} from "./templates.js"; +import { + getMaybeAppDirLocation, + getNextJsVersionBucket, + hasRootLayoutFile, + unwrapSentryConfigAst, + wrapWithSentryConfig, + addWithSentryConfigImport, + isNextJsVersionSupported, + MIN_SUPPORTED_NEXTJS_MAJOR, + MIN_SDK_VERSION_WITH_CONFIG_SUBPATH, + getExampleApiRouteDynamicStrategy, + getWithSentryConfigImportPath, +} from "./utils.js"; +import { SENTRY_NEXTJS_ROOT_IMPORT_PATH } from "./templates.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { debug } from "../utils/debug.js"; + +export function runNextjsWizard(options: WizardOptions) { + return withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "nextjs", + wizardOptions: options, + }, + () => runNextjsWizardWithTelemetry(options), + ); +} + +export async function runNextjsWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Next.js Wizard", + promoCode, + telemetryEnabled, + }); + + const typeScriptDetected = isUsingTypeScript(); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "next", "Next.js"); + + const nextVersion = getPackageVersion("next", packageJson); + Sentry.setTag("nextjs-version", getNextJsVersionBucket(nextVersion)); + + if (!isNextJsVersionSupported(nextVersion)) { + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry Next.js SDK requires Next.js ${MIN_SUPPORTED_NEXTJS_MAJOR} or newer, but this project uses ${chalk.bold( + `next@${nextVersion ?? "unknown"}`, + )}.`, + )} +The wizard will continue, but you may need to upgrade Next.js for the SDK to work.`, + ); + } + + const projectData = await getOrAskForProjectData( + options, + "javascript-nextjs", + ); + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/nextjs", + packageJson, + ); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", packageJson); + + const { packageManager: packageManagerFromInstallStep } = + await installPackage({ + packageName: "@sentry/nextjs@^11", + packageNameDisplayLabel: "@sentry/nextjs", + alreadyInstalled: !!packageJson.dependencies?.["@sentry/nextjs"], + forceInstall, + }); + + // `installPackage` may have skipped the install if the user declined the + // update prompt, so re-read package.json to learn which SDK is actually there. + const installedSdkVersion = getPackageVersion( + "@sentry/nextjs", + await getPackageDotJson(), + ); + const withSentryConfigImportPath = + getWithSentryConfigImportPath(installedSdkVersion); + if (withSentryConfigImportPath === SENTRY_NEXTJS_ROOT_IMPORT_PATH) { + clack.log.warn( + `${chalk.yellow( + `Your project uses ${chalk.bold( + `@sentry/nextjs@${installedSdkVersion ?? "unknown"}`, + )}, which predates ${MIN_SDK_VERSION_WITH_CONFIG_SUBPATH}.`, + )} +The wizard will import ${chalk.cyan( + "withSentryConfig", + )} from the root package for now. Once you upgrade the SDK (required for v11), change the import in your Next.js config to ${chalk.cyan( + "@sentry/nextjs/config", + )}.`, + ); + } + + // From v11 on, the SDK collects rich context by default, so offer to + // reduce collection of data that can identify users. + const reduceDataCollection = + sdkSupportsDataCollection(installedSdkVersion, "^10.73.0") && + (await askShouldReduceDataCollection()); + + let selectedProject: SentryProjectData; + let authToken: string; + let selfHosted: boolean; + let sentryUrl: string; + let spotlight: boolean; + + if (projectData.spotlight) { + // Spotlight mode: use empty DSN and skip auth + spotlight = true; + selfHosted = false; + sentryUrl = ""; + authToken = ""; + // Create a minimal project structure for type compatibility + selectedProject = { + id: "", + slug: "", + organization: { id: "", slug: "", name: "" }, + keys: [{ dsn: { public: "" } }], + }; + } else { + spotlight = false; + ({ selectedProject, authToken, selfHosted, sentryUrl } = projectData); + } + + await traceStep("configure-sdk", async () => { + const tunnelRoute = await askShouldSetTunnelRoute(); + + return await createOrMergeNextJsFiles( + selectedProject, + selfHosted, + sentryUrl, + { + tunnelRoute, + withSentryConfigImportPath, + reduceDataCollection, + spotlight, + }, + ); + }); + + await traceStep("create-underscoreerror-page", async () => { + const srcDir = path.join(process.cwd(), "src"); + const maybePagesDirPath = path.join(process.cwd(), "pages"); + const maybeSrcPagesDirPath = path.join(srcDir, "pages"); + + const pagesLocation = + existsSync(maybePagesDirPath) && + lstatSync(maybePagesDirPath).isDirectory() + ? ["pages"] + : existsSync(maybeSrcPagesDirPath) && + lstatSync(maybeSrcPagesDirPath).isDirectory() + ? ["src", "pages"] + : undefined; + + if (!pagesLocation) { + return; + } + + const underscoreErrorPageFile = existsSync( + path.join(process.cwd(), ...pagesLocation, "_error.tsx"), + ) + ? "_error.tsx" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.ts")) + ? "_error.ts" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.jsx")) + ? "_error.jsx" + : existsSync(path.join(process.cwd(), ...pagesLocation, "_error.js")) + ? "_error.js" + : undefined; + + if (!underscoreErrorPageFile) { + const underscoreErrorFileName = `_error.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesLocation, underscoreErrorFileName), + getSentryDefaultUnderscoreErrorPage(), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorFileName), + )}.`, + ); + } else if ( + readFileSync( + path.join(process.cwd(), ...pagesLocation, underscoreErrorPageFile), + "utf8", + ).includes("getInitialProps") + ) { + clack.log.info( + `It seems like you already have a custom error page.\n\nPlease put the following function call in the ${chalk.bold( + "getInitialProps", + )}\nmethod of your custom error page at ${chalk.bold( + path.join(...pagesLocation, underscoreErrorPageFile), + )}:`, + ); + clack.rawOutput(getSimpleUnderscoreErrorCopyPasteSnippet()); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you modify your ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } else { + clack.log.info( + `It seems like you already have a custom error page.\n\nPlease add the following code to your custom error page\nat ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )}:`, + ); + clack.rawOutput( + getFullUnderscoreErrorCopyPasteSnippet( + underscoreErrorPageFile === "_error.ts" || + underscoreErrorPageFile === "_error.tsx", + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you add the code to your ${chalk.cyan( + path.join(...pagesLocation, underscoreErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + }); + + await traceStep("create-global-error-page", async () => { + const appDirLocation = getMaybeAppDirLocation(); + + if (!appDirLocation) { + return; + } + + const globalErrorPageFile = existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.tsx"), + ) + ? "global-error.tsx" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.ts"), + ) + ? "global-error.ts" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.jsx"), + ) + ? "global-error.jsx" + : existsSync( + path.join(process.cwd(), ...appDirLocation, "global-error.js"), + ) + ? "global-error.js" + : undefined; + + if (!globalErrorPageFile) { + const newGlobalErrorFileName = `global-error.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...appDirLocation, newGlobalErrorFileName), + getSentryDefaultGlobalErrorPage(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appDirLocation, newGlobalErrorFileName), + )}.`, + ); + } else { + clack.log.info( + `It seems like you already have a custom error page for your app directory.\n\nPlease add the following code to your custom error page\nat ${chalk.cyan( + path.join(...appDirLocation, globalErrorPageFile), + )}:\n`, + ); + clack.rawOutput( + getGlobalErrorCopyPasteSnippet( + globalErrorPageFile === "global-error.ts" || + globalErrorPageFile === "global-error.tsx", + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Did you add the code to your ${chalk.cyan( + path.join(...appDirLocation, globalErrorPageFile), + )} file as described above?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + }); + + await traceStep("add-generate-metadata-function", async () => { + const isNext14 = getNextJsVersionBucket(nextVersion) === "14.x"; + const appDirLocation = getMaybeAppDirLocation(); + + // We only need this specific change for app router on next@14 + if (!appDirLocation || !isNext14) { + return; + } + + const appDirPath = path.join(process.cwd(), ...appDirLocation); + const hasRootLayout = hasRootLayoutFile(appDirPath); + + if (!hasRootLayout) { + const newRootLayoutFilename = `layout.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(appDirPath, newRootLayoutFilename), + getRootLayoutWithGenerateMetadata(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appDirLocation, newRootLayoutFilename), + )}.`, + ); + } else { + clack.log.info( + `It seems like you already have a root layout component. Please add or modify your generateMetadata function.`, + ); + + await showCopyPasteInstructions({ + filename: `layout.${typeScriptDetected ? "tsx" : "jsx"}`, + codeSnippet: getGenerateMetadataSnippet(typeScriptDetected), + }); + } + }); + + const shouldCreateExamplePage = await askShouldCreateExamplePage(); + if (shouldCreateExamplePage) { + await traceStep( + "create-example-page", + async () => + await createExamplePage( + selfHosted, + selectedProject, + sentryUrl, + typeScriptDetected, + nextVersion, + ), + ); + } + + if (!spotlight) { + await addDotEnvSentryBuildPluginFile(authToken); + } + + const isLikelyUsingTurbopack = await checkIfLikelyIsUsingTurbopack(); + if (isLikelyUsingTurbopack || isLikelyUsingTurbopack === null) { + await abortIfCancelled( + clack.select({ + message: + "Warning: The Sentry SDK is only compatible with Turbopack on Next.js version 15.4.1 or later.", + options: [ + { + label: "I understand.", + hint: "press enter", + value: true, + }, + ], + initialValue: true, + }), + ); + } + + const mightBeUsingVercel = existsSync( + path.join(process.cwd(), "vercel.json"), + ); + + if (mightBeUsingVercel && !options.comingFrom) { + clack.log.info( + "▲ It seems like you're using Vercel. We recommend using the Sentry Vercel \ + integration to set up an auth token for Vercel deployments: https://vercel.com/integrations/sentry", + ); + } else if (!spotlight) { + await setupCI("nextjs", authToken, options.comingFrom); + } + + const packageManagerForOutro = + packageManagerFromInstallStep ?? (await getPackageManager()); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + // Run formatters as the last step to fix any formatting issues in generated/modified files + await runFormatters({ cwd: undefined }); + + clack.outro(` +${chalk.green("Successfully installed the Sentry Next.js SDK!")} ${ + shouldCreateExamplePage + ? `\n\nYou can validate your setup by (re)starting your dev environment (e.g. ${chalk.cyan( + `${packageManagerForOutro.runScriptCommand} dev`, + )}) and visiting ${chalk.cyan('"/sentry-example-page"')}` + : "" + } + +${chalk.dim( + "If you encounter any issues, let us know here: https://github.com/getsentry/sentry-javascript/issues", +)}`); +} + +type SDKConfigOptions = { + tunnelRoute: boolean; + /** Module `withSentryConfig` is imported from; depends on the installed SDK version. */ + withSentryConfigImportPath: string; + /** Write the reduced-PII `dataCollection` option into `Sentry.init()`. */ + reduceDataCollection: boolean; + /** Set up Spotlight only, without a Sentry project. */ + spotlight: boolean; +}; + +async function createOrMergeNextJsFiles( + selectedProject: SentryProjectData, + selfHosted: boolean, + sentryUrl: string, + sdkConfigOptions: SDKConfigOptions, +): Promise { + const { reduceDataCollection, spotlight } = sdkConfigOptions; + const dsn = selectedProject.keys[0].dsn.public; + const selectedFeatures = await featureSelectionPrompt([ + { + id: "performance", + prompt: `Do you want to enable ${chalk.bold( + "Tracing", + )} to track the performance of your application?`, + enabledHint: "recommended", + }, + { + id: "replay", + prompt: `Do you want to enable ${chalk.bold( + "Session Replay", + )} to get a video-like reproduction of errors during a user session?`, + enabledHint: "recommended, but increases bundle size", + }, + ] as const); + + const typeScriptDetected = isUsingTypeScript(); + + const configVariants = ["server", "edge"] as const; + + for (const configVariant of configVariants) { + await traceStep(`create-sentry-${configVariant}-config`, async () => { + const jsConfig = `sentry.${configVariant}.config.js`; + const tsConfig = `sentry.${configVariant}.config.ts`; + + const jsConfigExists = existsSync(path.join(process.cwd(), jsConfig)); + const tsConfigExists = existsSync(path.join(process.cwd(), tsConfig)); + + let shouldWriteFile = true; + + if (jsConfigExists || tsConfigExists) { + const existingConfigs = []; + + if (jsConfigExists) { + existingConfigs.push(jsConfig); + } + + if (tsConfigExists) { + existingConfigs.push(tsConfig); + } + + const overwriteExistingConfigs = await abortIfCancelled( + clack.confirm({ + message: `Found existing Sentry ${configVariant} config (${existingConfigs.join( + ", ", + )}). Overwrite ${existingConfigs.length > 1 ? "them" : "it"}?`, + }), + ); + Sentry.setTag( + `overwrite-${configVariant}-config`, + overwriteExistingConfigs, + ); + + shouldWriteFile = overwriteExistingConfigs; + + if (overwriteExistingConfigs) { + if (jsConfigExists) { + unlinkSync(path.join(process.cwd(), jsConfig)); + clack.log.warn(`Removed existing ${chalk.cyan(jsConfig)}.`); + } + if (tsConfigExists) { + unlinkSync(path.join(process.cwd(), tsConfig)); + clack.log.warn(`Removed existing ${chalk.cyan(tsConfig)}.`); + } + } + } + + if (shouldWriteFile) { + await promises.writeFile( + path.join(process.cwd(), typeScriptDetected ? tsConfig : jsConfig), + getSentryServersideConfigContents( + dsn, + configVariant, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + { encoding: "utf8", flag: "w" }, + ); + clack.log.success( + `Created fresh ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )}.`, + ); + Sentry.setTag(`created-${configVariant}-config`, true); + } + }); + } + + await traceStep("setup-instrumentation-hook", async () => { + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + + let instrumentationHookLocation: "src" | "root" | "does-not-exist"; + + const instrumentationTsExists = existsSync( + path.join(process.cwd(), "instrumentation.ts"), + ); + const instrumentationJsExists = existsSync( + path.join(process.cwd(), "instrumentation.js"), + ); + const srcInstrumentationTsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation.ts"), + ); + const srcInstrumentationJsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation.js"), + ); + + // https://nextjs.org/docs/app/building-your-application/configuring/src-directory + // https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation + // The logic for where Next.js picks up the instrumentation file is as follows: + // - If there is either an `app` folder or a `pages` folder in the root directory of your Next.js app, Next.js looks + // for an `instrumentation.ts` file in the root of the Next.js app. + // - Otherwise, if there is neither an `app` folder or a `pages` folder in the rood directory of your Next.js app, + // AND if there is an `src` folder, Next.js will look for the `instrumentation.ts` file in the `src` folder. + if (hasRootPagesDirectory || hasRootAppDirectory) { + if (instrumentationJsExists || instrumentationTsExists) { + instrumentationHookLocation = "root"; + } else { + instrumentationHookLocation = "does-not-exist"; + } + } else { + if (srcInstrumentationTsExists || srcInstrumentationJsExists) { + instrumentationHookLocation = "src"; + } else { + instrumentationHookLocation = "does-not-exist"; + } + } + + const newInstrumentationFileName = `instrumentation.${ + typeScriptDetected ? "ts" : "js" + }`; + + if (instrumentationHookLocation === "does-not-exist") { + let newInstrumentationHookLocation: "root" | "src"; + if (hasRootPagesDirectory || hasRootAppDirectory) { + newInstrumentationHookLocation = "root"; + } else if (hasSrcDirectory) { + newInstrumentationHookLocation = "src"; + } else { + newInstrumentationHookLocation = "root"; + } + + const newInstrumentationHookPath = + newInstrumentationHookLocation === "root" + ? path.join(process.cwd(), newInstrumentationFileName) + : path.join(process.cwd(), "src", newInstrumentationFileName); + + const successfullyCreated = await createNewConfigFile( + newInstrumentationHookPath, + getInstrumentationHookContent(newInstrumentationHookLocation), + ); + + if (!successfullyCreated) { + await showCopyPasteInstructions({ + filename: newInstrumentationFileName, + codeSnippet: getInstrumentationHookCopyPasteSnippet( + newInstrumentationHookLocation, + ), + hint: "create the file if it doesn't already exist", + }); + } + } else { + await showCopyPasteInstructions({ + filename: + srcInstrumentationTsExists || instrumentationTsExists + ? "instrumentation.ts" + : srcInstrumentationJsExists || instrumentationJsExists + ? "instrumentation.js" + : newInstrumentationFileName, + codeSnippet: getInstrumentationHookCopyPasteSnippet( + instrumentationHookLocation, + ), + }); + } + }); + + await traceStep("setup-instrumentation-client-hook", async () => { + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + + let instrumentationClientHookLocation: "src" | "root" | "does-not-exist"; + + const instrumentationClientTsExists = existsSync( + path.join(process.cwd(), "instrumentation-client.ts"), + ); + const instrumentationClientJsExists = existsSync( + path.join(process.cwd(), "instrumentation-client.js"), + ); + const srcInstrumentationClientTsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation-client.ts"), + ); + const srcInstrumentationClientJsExists = existsSync( + path.join(process.cwd(), "src", "instrumentation-client.js"), + ); + + // https://nextjs.org/docs/app/building-your-application/configuring/src-directory + // https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation + // The logic for where Next.js picks up the instrumentation file is as follows: + // - If there is either an `app` folder or a `pages` folder in the root directory of your Next.js app, Next.js looks + // for an `instrumentation.ts` file in the root of the Next.js app. + // - Otherwise, if there is neither an `app` folder or a `pages` folder in the rood directory of your Next.js app, + // AND if there is an `src` folder, Next.js will look for the `instrumentation.ts` file in the `src` folder. + if (hasRootPagesDirectory || hasRootAppDirectory) { + if (instrumentationClientJsExists || instrumentationClientTsExists) { + instrumentationClientHookLocation = "root"; + } else { + instrumentationClientHookLocation = "does-not-exist"; + } + } else { + if ( + srcInstrumentationClientTsExists || + srcInstrumentationClientJsExists + ) { + instrumentationClientHookLocation = "src"; + } else { + instrumentationClientHookLocation = "does-not-exist"; + } + } + + const newInstrumentationClientFileName = `instrumentation-client.${ + typeScriptDetected ? "ts" : "js" + }`; + + if (instrumentationClientHookLocation === "does-not-exist") { + let newInstrumentationClientHookLocation: "root" | "src"; + if (hasRootPagesDirectory || hasRootAppDirectory) { + newInstrumentationClientHookLocation = "root"; + } else if (hasSrcDirectory) { + newInstrumentationClientHookLocation = "src"; + } else { + newInstrumentationClientHookLocation = "root"; + } + + const newInstrumentationClientHookPath = + newInstrumentationClientHookLocation === "root" + ? path.join(process.cwd(), newInstrumentationClientFileName) + : path.join(process.cwd(), "src", newInstrumentationClientFileName); + + const successfullyCreated = await createNewConfigFile( + newInstrumentationClientHookPath, + getInstrumentationClientFileContents( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + ); + + if (!successfullyCreated) { + await showCopyPasteInstructions({ + filename: newInstrumentationClientFileName, + codeSnippet: getInstrumentationClientHookCopyPasteSnippet( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + hint: "create the file if it doesn't already exist", + }); + } + } else { + await showCopyPasteInstructions({ + filename: + srcInstrumentationClientTsExists || instrumentationClientTsExists + ? "instrumentation-client.ts" + : srcInstrumentationClientJsExists || instrumentationClientJsExists + ? "instrumentation-client.js" + : newInstrumentationClientFileName, + codeSnippet: getInstrumentationClientHookCopyPasteSnippet( + dsn, + selectedFeatures, + reduceDataCollection, + spotlight, + ), + }); + } + }); + + await traceStep("setup-next-config", async () => { + const withSentryConfigOptionsTemplate = getWithSentryConfigOptionsTemplate({ + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + selfHosted, + sentryUrl, + tunnelRoute: sdkConfigOptions.tunnelRoute, + }); + + const nextConfigPossibleFilesMap = { + js: "next.config.js", + mjs: "next.config.mjs", + cjs: "next.config.cjs", + ts: "next.config.ts", + mts: "next.config.mts", + cts: "next.config.cts", + }; + + const foundNextConfigFile = Object.entries(nextConfigPossibleFilesMap).find( + ([, fileName]) => existsSync(path.join(process.cwd(), fileName)), + ); + + if (!foundNextConfigFile) { + Sentry.setTag("next-config-strategy", "create"); + + // Try to figure out whether the user prefers ESM + let isTypeModule = false; + try { + const packageJsonText = await promises.readFile( + path.join(process.cwd(), "package.json"), + "utf8", + ); + const packageJson = JSON.parse(packageJsonText); + if (packageJson.type === "module") { + isTypeModule = true; + } + } catch (error) { + debug(error); + // noop + } + + // We are creating `next.config.(m)js` files by default as they are supported by the most Next.js versions + const configFilename = isTypeModule + ? nextConfigPossibleFilesMap.mjs + : nextConfigPossibleFilesMap.js; + const configContent = isTypeModule + ? getNextjsConfigMjsTemplate( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ) + : getNextjsConfigCjsTemplate( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ); + + await promises.writeFile( + path.join(process.cwd(), configFilename), + configContent, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan(configFilename)} with Sentry configuration.`, + ); + + return; + } + + const [foundNextConfigFileType, foundNextConfigFileFilename] = + foundNextConfigFile; + + if (foundNextConfigFileType === "js" || foundNextConfigFileType === "cjs") { + Sentry.setTag("next-config-strategy", "modify"); + + const nextConfigCjsContent = readFileSync( + path.join(process.cwd(), foundNextConfigFileFilename), + "utf8", + ); + + const probablyIncludesSdk = + nextConfigCjsContent.includes("@sentry/nextjs") && + nextConfigCjsContent.includes("withSentryConfig"); + + let shouldInject = true; + + if (probablyIncludesSdk) { + const injectAnyhow = await abortIfCancelled( + clack.confirm({ + message: `${chalk.cyan( + foundNextConfigFileFilename, + )} already contains Sentry SDK configuration. Should the wizard modify it anyways?`, + }), + ); + + shouldInject = injectAnyhow; + } + + if (shouldInject) { + await promises.appendFile( + path.join(process.cwd(), foundNextConfigFileFilename), + getNextjsConfigCjsAppendix( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ), + "utf8", + ); + + clack.log.success( + `Added Sentry configuration to ${chalk.cyan( + foundNextConfigFileFilename, + )}. ${chalk.dim("(you probably want to clean this up a bit!)")}`, + ); + } + + Sentry.setTag("next-config-mod-result", "success"); + } + + if ( + foundNextConfigFileType === "mjs" || + foundNextConfigFileType === "mts" || + foundNextConfigFileType === "cts" || + foundNextConfigFileType === "ts" + ) { + const nextConfigMjsContent = readFileSync( + path.join(process.cwd(), foundNextConfigFileFilename), + "utf8", + ); + + const probablyIncludesSdk = + nextConfigMjsContent.includes("@sentry/nextjs") && + nextConfigMjsContent.includes("withSentryConfig"); + + let shouldInject = true; + + if (probablyIncludesSdk) { + const injectAnyhow = await abortIfCancelled( + clack.confirm({ + message: `${chalk.cyan( + foundNextConfigFileFilename, + )} already contains Sentry SDK configuration. Should the wizard modify it anyways?`, + }), + ); + + shouldInject = injectAnyhow; + } + + try { + if (shouldInject) { + const mod = parseModule(nextConfigMjsContent); + addWithSentryConfigImport( + mod, + sdkConfigOptions.withSentryConfigImportPath, + ); + + if (probablyIncludesSdk) { + // Prevent double wrapping like: withSentryConfig(withSentryConfig(nextConfig), { ... }) + // Use AST manipulation instead of string parsing for better reliability + mod.exports["default"].$ast = unwrapSentryConfigAst( + mod.exports["default"].$ast, + ); + } + + // Use the shared utility function for wrapping + mod.exports["default"] = wrapWithSentryConfig( + mod.exports["default"], + withSentryConfigOptionsTemplate, + ); + + let newCode = mod.generate().code; + + // Post-process to fix formatting issues that magicast doesn't handle + // (needed for Biome/ESLint compatibility): + // 1. Add spaces inside import braces for various import patterns + // Single named import: {Foo} -> { Foo } + newCode = newCode.replace( + /import\s*{(\w+)}\s*from/g, + "import { $1 } from", + ); + // Multiple named imports: {Foo,Bar} or {Foo, Bar} -> { Foo, Bar } + newCode = newCode.replace( + /import\s*{([^}]+)}\s*from/g, + (_match: string, imports: string) => { + const formatted = imports + .split(",") + .map((i: string) => i.trim()) + .join(", "); + return `import { ${formatted} } from`; + }, + ); + // Default + named imports: Foo,{Bar} -> Foo, { Bar } + newCode = newCode.replace( + /import\s+(\w+)\s*,\s*{([^}]+)}\s*from/g, + (_match: string, defaultImport: string, namedImports: string) => { + const formatted = namedImports + .split(",") + .map((i: string) => i.trim()) + .join(", "); + return `import ${defaultImport}, { ${formatted} } from`; + }, + ); + // 2. Fix trailing comma and closing format for withSentryConfig call + // Biome wants: automaticVercelMonitors: true,\n }); + newCode = newCode.replace( + /automaticVercelMonitors:\s*true,?\s*},?\s*\);/g, + "automaticVercelMonitors: true,\n });\n", + ); + // 3. Ensure trailing newline + if (!newCode.endsWith("\n")) { + newCode += "\n"; + } + + await promises.writeFile( + path.join(process.cwd(), foundNextConfigFileFilename), + newCode, + { + encoding: "utf8", + flag: "w", + }, + ); + clack.log.success( + `${ + probablyIncludesSdk ? "Updated" : "Added" + } Sentry configuration ${ + probablyIncludesSdk ? "in" : "to" + } ${chalk.cyan(foundNextConfigFileFilename)}. ${chalk.dim( + "(you probably want to clean this up a bit!)", + )}`, + ); + + Sentry.setTag("next-config-mod-result", "success"); + } + } catch { + Sentry.setTag("next-config-mod-result", "fail"); + clack.log.warn( + chalk.yellow( + `Something went wrong writing to ${chalk.cyan( + foundNextConfigFileFilename, + )}.`, + ), + ); + clack.log.info( + `Please put the following code snippet into ${chalk.cyan( + foundNextConfigFileFilename, + )}: ${chalk.dim("You probably have to clean it up a bit.")}\n`, + ); + clack.rawOutput( + getNextjsConfigEsmCopyPasteSnippet( + withSentryConfigOptionsTemplate, + sdkConfigOptions.withSentryConfigImportPath, + ), + ); + + const shouldContinue = await abortIfCancelled( + clack.confirm({ + message: `Are you done putting the snippet above into ${chalk.cyan( + foundNextConfigFileFilename, + )}?`, + active: "Yes", + inactive: "No, get me out of here", + }), + ); + + if (!shouldContinue) { + await abort(); + } + } + } + }); +} + +function hasDirectoryPathFromRoot(dirnameOrDirs: string | string[]): boolean { + const dirPath = Array.isArray(dirnameOrDirs) + ? path.join(process.cwd(), ...dirnameOrDirs) + : path.join(process.cwd(), dirnameOrDirs); + + return existsSync(dirPath) && lstatSync(dirPath).isDirectory(); +} + +async function createExamplePage( + selfHosted: boolean, + selectedProject: SentryProjectData, + sentryUrl: string, + typeScriptDetected: boolean, + nextVersion: string | undefined, +): Promise { + const hasSrcDirectory = hasDirectoryPathFromRoot("src"); + const hasRootAppDirectory = hasDirectoryPathFromRoot("app"); + const hasRootPagesDirectory = hasDirectoryPathFromRoot("pages"); + const hasSrcAppDirectory = hasDirectoryPathFromRoot(["src", "app"]); + const hasSrcPagesDirectory = hasDirectoryPathFromRoot(["src", "pages"]); + + Sentry.setTag("nextjs-app-dir", hasRootAppDirectory || hasSrcAppDirectory); + + // If `pages` or an `app` directory exists in the root, we'll put the example page there. + // `app` directory takes priority over `pages` directory when they coexist, so we prioritize that. + // https://nextjs.org/docs/app/building-your-application/routing#the-app-router + + const appFolderLocation = hasRootAppDirectory + ? ["app"] + : hasSrcAppDirectory + ? ["src", "app"] + : undefined; + + let pagesFolderLocation = hasRootPagesDirectory + ? ["pages"] + : hasSrcPagesDirectory + ? ["src", "pages"] + : undefined; + + // If the user has neither pages nor app directory we create a pages folder for them + if (!appFolderLocation && !pagesFolderLocation) { + const newPagesFolderLocation = hasSrcDirectory + ? ["src", "pages"] + : ["pages"]; + mkdirSync(path.join(process.cwd(), ...newPagesFolderLocation), { + recursive: true, + }); + + pagesFolderLocation = newPagesFolderLocation; + } + + if (appFolderLocation) { + const appFolderPath = path.join(process.cwd(), ...appFolderLocation); + + const hasRootLayout = hasRootLayoutFile(appFolderPath); + + if (!hasRootLayout) { + // In case no root layout file exists, we create a simple one so that + // the example page can be rendered correctly. + const newRootLayoutFilename = `layout.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(appFolderPath, newRootLayoutFilename), + getRootLayout(typeScriptDetected), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appFolderLocation, newRootLayoutFilename), + )}.`, + ); + } + + const examplePageContents = getSentryExamplePageContents({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + sentryUrl, + useClient: true, + isTypeScript: typeScriptDetected, + }); + + mkdirSync(path.join(appFolderPath, "sentry-example-page"), { + recursive: true, + }); + + const newPageFileName = `page.${typeScriptDetected ? "tsx" : "jsx"}`; + + await promises.writeFile( + path.join(appFolderPath, "sentry-example-page", newPageFileName), + examplePageContents, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...appFolderLocation, "sentry-example-page", newPageFileName), + )}.`, + ); + + mkdirSync(path.join(appFolderPath, "api", "sentry-example-api"), { + recursive: true, + }); + + const newRouteFileName = `route.${typeScriptDetected ? "ts" : "js"}`; + + await promises.writeFile( + path.join(appFolderPath, "api", "sentry-example-api", newRouteFileName), + getSentryExampleAppDirApiRoute({ + isTypeScript: typeScriptDetected, + dynamicStrategy: getExampleApiRouteDynamicStrategy(nextVersion), + }), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join( + ...appFolderLocation, + "api", + "sentry-example-api", + newRouteFileName, + ), + )}.`, + ); + } else if (pagesFolderLocation) { + const examplePageContents = getSentryExamplePageContents({ + selfHosted, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + sentryUrl, + useClient: false, + isTypeScript: typeScriptDetected, + }); + + const examplePageFileName = `sentry-example-page.${ + typeScriptDetected ? "tsx" : "jsx" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesFolderLocation, examplePageFileName), + examplePageContents, + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesFolderLocation, examplePageFileName), + )}.`, + ); + + mkdirSync(path.join(process.cwd(), ...pagesFolderLocation, "api"), { + recursive: true, + }); + + const apiRouteFileName = `sentry-example-api.${ + typeScriptDetected ? "ts" : "js" + }`; + + await promises.writeFile( + path.join(process.cwd(), ...pagesFolderLocation, "api", apiRouteFileName), + getSentryExamplePagesDirApiRoute({ + isTypeScript: typeScriptDetected, + }), + { encoding: "utf8", flag: "w" }, + ); + + clack.log.success( + `Created ${chalk.cyan( + path.join(...pagesFolderLocation, "api", apiRouteFileName), + )}.`, + ); + } +} + +/** + * Ask users if they want to set the tunnelRoute option. + * We can't set this by default because it potentially increases hosting bills. + * It's valuable enough to for users to justify asking the additional question. + */ +async function askShouldSetTunnelRoute() { + return await traceStep("ask-tunnelRoute-option", async (span) => { + const shouldSetTunnelRoute = await abortIfCancelled( + clack.select({ + message: + "Do you want to route Sentry requests in the browser through your Next.js server to avoid ad blockers?", + options: [ + { + label: "Yes", + value: true, + hint: "Can increase your server load and hosting bill", + }, + { + label: "No", + value: false, + hint: "Browser errors and events might be blocked by ad blockers before being sent to Sentry", + }, + ], + initialValue: true, + }), + ); + + if (!shouldSetTunnelRoute) { + clack.log.info( + "Sounds good! We'll leave the option commented for later, just in case :)", + ); + } + + span?.setAttribute("tunnelRoute", shouldSetTunnelRoute); + Sentry.setTag("tunnelRoute", shouldSetTunnelRoute); + + return shouldSetTunnelRoute; + }); +} + +/** + * Returns true or false depending on whether we think the user is using Turbopack. May return null in case we aren't sure. + */ +async function checkIfLikelyIsUsingTurbopack(): Promise { + let packageJsonContent: string; + try { + packageJsonContent = await promises.readFile( + path.join(process.cwd(), "package.json"), + "utf8", + ); + } catch (error) { + debug(error); + return null; + } + + return packageJsonContent.includes("--turbo"); +} diff --git a/packages/cli/src/lib/wizard/nextjs/templates.ts b/packages/cli/src/lib/wizard/nextjs/templates.ts new file mode 100644 index 0000000000..b9ce82f9d8 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/templates.ts @@ -0,0 +1,910 @@ +/** + * File and snippet templates the Next.js wizard writes or shows. + */ + +import chalk from "chalk"; +import { makeCodeSnippet } from "../utils/clack/index.js"; +import { getDataCollectionSnippet } from "../utils/data-collection.js"; + +const DATA_COLLECTION_HINT = ` dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + },`; + +/** + * The active PII-reducing preset when the user opted in, the commented-out + * hint otherwise. + */ +function getDataCollectionBlock(reduceDataCollection: boolean): string { + return reduceDataCollection + ? getDataCollectionSnippet(" ") + : DATA_COLLECTION_HINT; +} + +/** Root export of the Next.js SDK. Exposes `withSentryConfig` up to SDK v10 only. */ +export const SENTRY_NEXTJS_ROOT_IMPORT_PATH = "@sentry/nextjs"; + +/** Subpath that exposes `withSentryConfig` since SDK 10.73.0 and is the only location in v11. */ +export const SENTRY_NEXTJS_CONFIG_IMPORT_PATH = "@sentry/nextjs/config"; + +type WithSentryConfigOptions = { + orgSlug: string; + projectSlug: string; + selfHosted: boolean; + sentryUrl: string; + tunnelRoute: boolean; +}; + +export function getWithSentryConfigOptionsTemplate({ + orgSlug, + projectSlug, + selfHosted, + tunnelRoute, + sentryUrl, +}: WithSentryConfigOptions): string { + return `{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "${orgSlug}", + project: "${projectSlug}",${ + selfHosted ? `\n sentryUrl: "${sentryUrl}",` : "" + } + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // ${ + tunnelRoute ? "Route" : "Uncomment to route" + } browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + ${tunnelRoute ? "" : "// "}tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, +}`; +} + +export function getNextjsConfigCjsTemplate( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return `const { withSentryConfig } = require("${withSentryConfigImportPath}"); + +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +module.exports = withSentryConfig(nextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigMjsTemplate( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return `import { withSentryConfig } from "${withSentryConfigImportPath}"; + +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +export default withSentryConfig(nextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigCjsAppendix( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return ` + +// Injected content via Sentry wizard below + +const { withSentryConfig } = require("${withSentryConfigImportPath}"); + +module.exports = withSentryConfig(module.exports, ${withSentryConfigOptionsTemplate}); +`; +} + +export function getNextjsConfigEsmCopyPasteSnippet( + withSentryConfigOptionsTemplate: string, + withSentryConfigImportPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): string { + return ` + +// next.config.mjs +import { withSentryConfig } from "${withSentryConfigImportPath}"; + +export default withSentryConfig(yourNextConfig, ${withSentryConfigOptionsTemplate}); +`; +} + +function getClientIntegrationsSnippet(features: { replay: boolean }) { + if (features.replay) { + return ` + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()],`; + } + + return ""; +} + +function getSpotlightOption(spotlight: boolean): string { + if (!spotlight) { + return ""; + } + + return ` + + // Spotlight enabled for local development (https://spotlightjs.com) + spotlight: true,`; +} + +export function getSentryServersideConfigContents( + dsn: string, + config: "server" | "edge", + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +): string { + let primer = ""; + if (config === "server") { + primer = `// This file configures the initialization of Sentry on the server. +// The config you add here will be used whenever the server handles a request. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/`; + } else { + primer = `// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). +// The config you add here will be used whenever one of the edge features is loaded. +// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/`; + } + + let performanceOptions = ""; + if (selectedFeaturesMap.performance) { + performanceOptions += ` + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1,`; + } + + const spotlightOptions = getSpotlightOption(spotlight); + return `${primer} + +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "${dsn}",${performanceOptions} + +${getDataCollectionBlock(reduceDataCollection)}${spotlightOptions} +}); +`; +} + +export function getInstrumentationClientFileContents( + dsn: string, + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +): string { + const integrationsOptions = getClientIntegrationsSnippet({ + replay: selectedFeaturesMap.replay, + }); + + let replayOptions = ""; + + if (selectedFeaturesMap.replay) { + replayOptions += ` + + // Define how likely Replay events are sampled. + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0,`; + } + + let performanceOptions = ""; + if (selectedFeaturesMap.performance) { + performanceOptions += ` + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1,`; + } + + const spotlightOptions = getSpotlightOption(spotlight); + + return `// This file configures the initialization of Sentry on the client. +// The added config here will be used whenever a users loads a page in their browser. +// https://docs.sentry.io/platforms/javascript/guides/nextjs/ + +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "${dsn}",${integrationsOptions}${performanceOptions}${replayOptions} + +${getDataCollectionBlock(reduceDataCollection)}${spotlightOptions} +}); + +export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; +`; +} + +export function getSentryExamplePageContents(options: { + selfHosted: boolean; + sentryUrl: string; + orgSlug: string; + projectId: string; + useClient: boolean; + isTypeScript?: boolean | undefined; +}): string { + const issuesPageLink = options.selfHosted + ? `${options.sentryUrl}organizations/${options.orgSlug}/issues/?project=${options.projectId}` + : `https://${options.orgSlug}.sentry.io/issues/?project=${options.projectId}`; + + const loggerPageLoad = ` + Sentry.logger.info("Sentry example page loaded");`; + + const loggerUserAction = ` + Sentry.logger.info("User clicked the button, throwing a sample error");`; + + return `${ + options.useClient ? '"use client";\n\n' : "" + }import * as Sentry from "@sentry/nextjs"; +import Head from "next/head"; +import { useEffect, useState } from "react"; + +class SentryExampleFrontendError extends Error { + constructor(message${options.isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleFrontendError"; + } +} + +export default function Page() { + const [hasSentError, setHasSentError] = useState(false); + const [isConnected, setIsConnected] = useState(true); + + useEffect(() => {${loggerPageLoad} + async function checkConnectivity() { + const result = await Sentry.diagnoseSdkConnectivity(); + setIsConnected(result !== "sentry-unreachable"); + } + checkConnectivity(); + }, []); + + return ( +
+ + sentry-example-page + + + +
+
+ + + +

sentry-example-page

+ +

+ Click the button below, and view the sample error on the Sentry{" "} + + Issues Page + + . For more details about setting up Sentry,{" "} + + read our docs + + . +

+ + + + {hasSentError ? ( +

Error sent to Sentry.

+ ) : !isConnected ? ( +
+

+ It looks like network requests to Sentry are being blocked, which + will prevent errors from being captured. Try disabling your + ad-blocker to complete the test. +

+
+ ) : ( +
+ )} + +
+
+ + +
+ ); +} +`; +} + +export function getSentryExamplePagesDirApiRoute({ + isTypeScript, +}: { + isTypeScript: boolean; +}) { + const sentryImport = `import * as Sentry from "@sentry/nextjs"; + +`; + + const loggerCall = ` Sentry.logger.info("Sentry example API called"); +`; + + return `${sentryImport}// Custom error class for Sentry testing +class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} +// A faulty API route to test Sentry's error monitoring +export default function handler(_req, res) { +${loggerCall}throw new SentryExampleAPIError("This error is raised on the backend called by the example page."); +res.status(200).json({ name: "John Doe" }); +} +`; +} + +export type ExampleApiRouteDynamicStrategy = "force-dynamic" | "connection"; + +export function getSentryExampleAppDirApiRoute({ + isTypeScript, + dynamicStrategy, +}: { + isTypeScript: boolean; + /** + * How the route opts out of static rendering so the throwing handler runs at + * request time instead of during the build: + * - `force-dynamic`: `export const dynamic = "force-dynamic"`. Needed on Next.js 14, + * where GET route handlers are cached by default. + * - `connection`: `await connection()` from `next/server` (Next.js 15+). Required on + * Next.js 16 with `cacheComponents`, which rejects route segment config. + */ + dynamicStrategy: ExampleApiRouteDynamicStrategy; +}) { + const useConnection = dynamicStrategy === "connection"; + + const sentryImport = `import * as Sentry from "@sentry/nextjs"; +${useConnection ? 'import { connection } from "next/server";\n' : ""}`; + + const forceDynamicExport = useConnection + ? "" + : `export const dynamic = "force-dynamic"; + +`; + + const connectionCall = useConnection + ? ` + // Opt out of prerendering so the error is thrown at request time + await connection();` + : ""; + + const loggerCall = ` + Sentry.logger.info("Sentry example API called");`; + + // Note: We intentionally don't have a return statement after throw - it would be unreachable code + // We also don't import NextResponse since we don't use it (Biome noUnusedImports rule) + return `${sentryImport}${forceDynamicExport}class SentryExampleAPIError extends Error { + constructor(message${isTypeScript ? ": string | undefined" : ""}) { + super(message); + this.name = "SentryExampleAPIError"; + } +} + +// A faulty API route to test Sentry's error monitoring +export ${ + useConnection ? "async " : "" + }function GET() {${connectionCall}${loggerCall} + throw new SentryExampleAPIError( + "This error is raised on the backend called by the example page.", + ); +} +`; +} + +export function getSentryDefaultUnderscoreErrorPage() { + return `import * as Sentry from "@sentry/nextjs"; +import Error from "next/error"; + +const CustomErrorComponent = (props) => { + return ; +}; + +CustomErrorComponent.getInitialProps = async (contextData) => { + // In case this is running in a serverless function, await this in order to give Sentry + // time to send the error before the lambda exits + await Sentry.captureUnderscoreErrorException(contextData); + + // This will contain the status code of the response + return Error.getInitialProps(contextData); +}; + +export default CustomErrorComponent; +`; +} + +export function getSimpleUnderscoreErrorCopyPasteSnippet() { + return ` +${chalk.green(`import * as Sentry from '@sentry/nextjs';`)} +${chalk.green(`import Error from "next/error";`)} + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (${chalk.green( + "contextData", + )}) => { + ${chalk.green("await Sentry.captureUnderscoreErrorException(contextData);")} + + ${chalk.dim("// ...other getInitialProps code")} + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getGenerateMetadataSnippet(isTs: boolean) { + return makeCodeSnippet(true, (unchanged, plus) => { + return plus(` + import * as Sentry from '@sentry/nextjs'; + ${isTs ? `import type { Metadata } from 'next';` : ""} + + ${unchanged( + '// Add or edit your "generateMetadata" to include the Sentry trace data:', + )} + export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +`); + }); +} + +export function getFullUnderscoreErrorCopyPasteSnippet(isTs: boolean) { + return ` +import * as Sentry from '@sentry/nextjs';${ + isTs ? '\nimport type { NextPageContext } from "next";' : "" + } +import Error from "next/error"; + +${chalk.dim( + '// Replace "YourCustomErrorComponent" with your custom error component!', +)} +YourCustomErrorComponent.getInitialProps = async (contextData${ + isTs ? ": NextPageContext" : "" + }) => { + await Sentry.captureUnderscoreErrorException(contextData); + + return Error.getInitialProps(contextData); +}; +`; +} + +export function getInstrumentationHookContent( + instrumentationHookLocation: "src" | "root", +) { + return `import * as Sentry from "@sentry/nextjs"; + +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError; +`; +} + +export function getInstrumentationHookCopyPasteSnippet( + instrumentationHookLocation: "src" | "root", +) { + return makeCodeSnippet(true, (unchanged, plus) => { + return unchanged(`${plus("import * as Sentry from '@sentry/nextjs';")} + +export ${plus("async")} function register() { + ${plus(`if (process.env.NEXT_RUNTIME === 'nodejs') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.server.config'); + } + + if (process.env.NEXT_RUNTIME === 'edge') { + await import('${ + instrumentationHookLocation === "root" ? "." : ".." + }/sentry.edge.config'); + }`)} +} + +${plus("export const onRequestError = Sentry.captureRequestError;")} +`); + }); +} + +export function getInstrumentationClientHookCopyPasteSnippet( + dsn: string, + selectedFeaturesMap: { + replay: boolean; + performance: boolean; + }, + reduceDataCollection: boolean, + spotlight = false, +) { + return makeCodeSnippet(true, (_unchanged, plus) => { + return plus( + getInstrumentationClientFileContents( + dsn, + selectedFeaturesMap, + reduceDataCollection, + spotlight, + ), + ); + }); +} + +export function getSentryDefaultGlobalErrorPage(isTs: boolean) { + return isTs + ? `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ + error, +}: { + error: Error & { digest?: string }; +}) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +` + : `"use client"; + +import * as Sentry from "@sentry/nextjs"; +import NextError from "next/error"; +import { useEffect } from "react"; + +export default function GlobalError({ error }) { + useEffect(() => { + Sentry.captureException(error); + }, [error]); + + return ( + + + {/* \`NextError\` is the default Next.js error page component. Its type + definition requires a \`statusCode\` prop. However, since the App Router + does not expose status codes for errors, we simply pass 0 to render a + generic error message. */} + + + + ); +} +`; +} + +export function getGlobalErrorCopyPasteSnippet(isTs: boolean) { + if (isTs) { + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green( + "{ error }: { error: Error }", + )}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; + } + return `"use client"; + +${chalk.green('import * as Sentry from "@sentry/nextjs";')} +${chalk.green('import Error from "next/error";')} +${chalk.green('import { useEffect } from "react";')} + +export default function GlobalError(${chalk.green("{ error }")}) { + ${chalk.green(`useEffect(() => { + Sentry.captureException(error); + }, [error]);`)} + + return ( + + + {/* Your Error component here... */} + + + ); +} +`; +} + +export const getRootLayout = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +// You can delete this file at any time. + +export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', +} + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; + +export const getRootLayoutWithGenerateMetadata = ( + isTs: boolean, +) => `// This file was generated by the Sentry wizard because we couldn't find a root layout file. +import * as Sentry from '@sentry/nextjs'; +${isTs ? `import type { Metadata } from 'next';` : ""} + +export function generateMetadata()${isTs ? ": Metadata" : ""} { + return { + other: { + ...Sentry.getTraceData(), + } + } +}; + +export default function RootLayout({ + children, +}${ + isTs + ? `: { + children: React.ReactNode +}` + : "" +}) { + return ( + + {children} + + ) +} +`; diff --git a/packages/cli/src/lib/wizard/nextjs/utils.ts b/packages/cli/src/lib/wizard/nextjs/utils.ts new file mode 100644 index 0000000000..c99e6ecc25 --- /dev/null +++ b/packages/cli/src/lib/wizard/nextjs/utils.ts @@ -0,0 +1,182 @@ +/** + * Helpers of the Next.js wizard: SDK versions, project layout, and + * config-file detection. + */ + +import { existsSync, lstatSync } from "node:fs"; +import path from "node:path"; +import { lt, major, minVersion } from "semver"; +import { type ASTNode, builders, type ProxifiedModule } from "magicast"; +import { + SENTRY_NEXTJS_CONFIG_IMPORT_PATH, + SENTRY_NEXTJS_ROOT_IMPORT_PATH, + type ExampleApiRouteDynamicStrategy, +} from "./templates.js"; +import { debug } from "../utils/debug.js"; + +/** First `@sentry/nextjs` release that exposes `withSentryConfig` on the `/config` subpath. */ +export const MIN_SDK_VERSION_WITH_CONFIG_SUBPATH = "10.73.0"; + +/** + * Returns the module `withSentryConfig` should be imported from for the + * installed SDK version. The wizard installs `^11`, but a user can keep an + * older SDK by declining the update prompt. Those releases only expose + * `withSentryConfig` on the root export, so fall back to it there. Unknown or + * unparseable versions get the subpath, which is the only option on v11. + */ +export function getWithSentryConfigImportPath( + sdkVersion: string | undefined, +): string { + if (!sdkVersion) { + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; + } + + try { + const minVer = minVersion(sdkVersion); + if (minVer && lt(minVer, MIN_SDK_VERSION_WITH_CONFIG_SUBPATH)) { + return SENTRY_NEXTJS_ROOT_IMPORT_PATH; + } + } catch (error) { + debug(error); + // fall through + } + + return SENTRY_NEXTJS_CONFIG_IMPORT_PATH; +} + +/** Minimum Next.js major supported by the Sentry Next.js SDK (v11 dropped Next.js 13). */ +export const MIN_SUPPORTED_NEXTJS_MAJOR = 14; + +/** + * Returns `false` when the given Next.js version range is definitely below the + * minimum the SDK supports. Unknown or unparseable versions are treated as supported. + */ +export function isNextJsVersionSupported(version: string | undefined): boolean { + if (!version) { + return true; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return true; + } + return major(minVer) >= MIN_SUPPORTED_NEXTJS_MAJOR; + } catch (error) { + debug(error); + return true; + } +} + +/** + * Picks how the generated example API route opts out of static rendering. + * Next.js 14 caches GET route handlers by default, so the route needs + * `export const dynamic = "force-dynamic"` or the build evaluates (and fails on) + * the throwing handler. Next.js 15+ ships `connection()` from `next/server`, + * which also works on Next.js 16 with `cacheComponents`, where route segment + * config is rejected. Unknown versions keep the previous `force-dynamic` behavior. + */ +export function getExampleApiRouteDynamicStrategy( + version: string | undefined, +): ExampleApiRouteDynamicStrategy { + if (!version) { + return "force-dynamic"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "force-dynamic"; + } + return major(minVer) >= 15 ? "connection" : "force-dynamic"; + } catch (error) { + debug(error); + return "force-dynamic"; + } +} + +/** + * Adds `import { withSentryConfig } from ` to the module. + * If the module already imports `withSentryConfig` (e.g. from the root + * `@sentry/nextjs` export used by SDK v10 and earlier), the existing import is + * rewritten to the given path instead of adding a duplicate binding. + */ +export function addWithSentryConfigImport( + mod: ProxifiedModule, + importPath: string = SENTRY_NEXTJS_CONFIG_IMPORT_PATH, +): void { + mod.imports.$add({ + from: importPath, + imported: "withSentryConfig", + local: "withSentryConfig", + }); +} + +export function getNextJsVersionBucket(version: string | undefined) { + if (!version) { + return "none"; + } + + try { + const minVer = minVersion(version); + if (!minVer) { + return "invalid"; + } + const majorVersion = major(minVer); + if (majorVersion >= 11) { + return `${majorVersion}.x`; + } + return "<11.0.0"; + } catch (error) { + debug(error); + return "unknown"; + } +} + +export function getMaybeAppDirLocation() { + const maybeAppDirPath = path.join(process.cwd(), "app"); + const maybeSrcAppDirPath = path.join(process.cwd(), "src", "app"); + + return existsSync(maybeAppDirPath) && lstatSync(maybeAppDirPath).isDirectory() + ? ["app"] + : existsSync(maybeSrcAppDirPath) && + lstatSync(maybeSrcAppDirPath).isDirectory() + ? ["src", "app"] + : undefined; +} + +export function hasRootLayoutFile(appFolderPath: string) { + return ["jsx", "tsx", "js"].some((ext) => + existsSync(path.join(appFolderPath, `layout.${ext}`)), + ); +} + +/** + * Unwraps a withSentryConfig call expression using magicast. + */ +export function unwrapSentryConfigAst(astNode: ASTNode): ASTNode { + if ( + astNode.type === "CallExpression" && + astNode.callee.type === "Identifier" && + astNode.callee.name === "withSentryConfig" + ) { + // Return the first argument (the config being wrapped) + return astNode.arguments[0] ?? astNode; + } + + return astNode; +} + +/** + * Wraps a magicast module export with withSentryConfig using magicast + */ +export function wrapWithSentryConfig( + moduleExport: unknown, + optionsTemplate: string, +): ReturnType { + return builders.functionCall( + "withSentryConfig", + moduleExport, + builders.raw(optionsTemplate), + ); +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts new file mode 100644 index 0000000000..8bd377980b --- /dev/null +++ b/packages/cli/src/lib/wizard/run.ts @@ -0,0 +1,128 @@ +/** + * Pick and run a setup wizard for `sentry wizard`. + * + * Each integration's flow lives in its own directory and loads with a + * dynamic `import()`, so a run loads only the flow it needs (and its heavy + * dependencies, such as magicast). + */ + +import { ValidationError } from "../errors.js"; +import { abortIfCancelled } from "./utils/clack/index.js"; +import { clack } from "./utils/clack/prompts.js"; +import { enableDebugLogs } from "./utils/debug.js"; +import type { WizardOptions } from "./utils/types.js"; +import { CLI_VERSION } from "../constants.js"; + +/** + * The integrations `sentry wizard -i` accepts, in the order the picker lists + * them. The ids are the ones `@sentry/wizard -i` took. + */ +export const WIZARD_INTEGRATIONS = [ + { id: "reactNative", label: "React Native" }, + { id: "flutter", label: "Flutter" }, + { id: "ios", label: "iOS" }, + { id: "appleSnapshots", label: "Apple Snapshots" }, + { id: "angular", label: "Angular" }, + { id: "android", label: "Android" }, + { id: "nextjs", label: "Next.js" }, + { id: "nuxt", label: "Nuxt" }, + { id: "remix", label: "Remix" }, + { id: "reactRouter", label: "React Router" }, + { id: "sveltekit", label: "SvelteKit" }, + { id: "cloudflare", label: "Cloudflare" }, + { id: "sourcemaps", label: "Configure Source Maps Upload" }, +] as const; + +/** An integration id `sentry wizard -i` accepts. */ +export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; + +/** + * Every value `-i` accepts. The Cordova and Electron wizards of + * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + */ +export const INTEGRATION_IDS: readonly WizardIntegration[] = + WIZARD_INTEGRATIONS.map((integration) => integration.id); + +/** Runs the wizard of one integration. */ +type WizardRunner = (options: WizardOptions) => Promise; + +/** + * The flow of each integration. Integrations without one are still being + * moved over from sentry-wizard. + */ +const WIZARD_RUNNERS: Partial> = { + nextjs: async (options) => { + const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); + await runNextjsWizard(options); + }, +}; + +/** What `sentry wizard` passes to {@link runWizard}. */ +export type RunWizardArgs = { + /** `-i`: the integration to set up; prompts for one when unset. */ + integration?: string | undefined; + /** `--debug`: print the wizard's debug output. */ + debug: boolean; + /** The options every wizard flow takes. */ + wizardOptions: WizardOptions; +}; + +/** + * Run the wizard of `args.integration`, after asking for one when it is + * unset. + * + * @throws {ValidationError} For an unknown integration, or one that has no + * flow in this version yet + */ +export async function runWizard(args: RunWizardArgs): Promise { + if (args.debug) { + enableDebugLogs(); + } + + const integration = args.integration + ? toWizardIntegration(args.integration) + : await askForIntegration(); + + const runner = WIZARD_RUNNERS[integration]; + if (!runner) { + throw new ValidationError( + `The ${integration} wizard is not available in this version yet.`, + "integration", + ); + } + await runner(args.wizardOptions); +} + +/** + * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its + * value; `SENTRY_WIZARD_INTEGRATION` is checked here. + * + * @throws {ValidationError} When `id` names no integration + */ +function toWizardIntegration(id: string): WizardIntegration { + const match = WIZARD_INTEGRATIONS.find( + (integration) => integration.id === id, + ); + if (!match) { + throw new ValidationError( + `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, + "integration", + ); + } + return match.id; +} + +/** Ask which integration to set up, out of the ones that have a flow. */ +async function askForIntegration(): Promise { + clack.intro(`Sentry Wizard ${CLI_VERSION}`); + const integration = await abortIfCancelled( + clack.select({ + message: "What do you want to set up?", + options: WIZARD_INTEGRATIONS.filter(({ id }) => id in WIZARD_RUNNERS).map( + ({ id, label }) => ({ value: id, label }), + ), + }), + ); + clack.outro(`Starting ${integration} setup`); + return integration; +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts new file mode 100644 index 0000000000..e725f44a51 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -0,0 +1,130 @@ +/** + * Help the user make the source map upload auth token available in CI. + * + * Shared by the framework wizards and the source maps wizard. Ported from + * sentry-wizard's `src/sourcemaps/sourcemaps-wizard.ts`. + */ + +import chalk from "chalk"; +import { Sentry, traceStep } from "../telemetry.js"; +import { + abortIfCancelled, + SENTRY_CLI_RC_FILE, + SENTRY_DOT_ENV_FILE, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { WizardOptions } from "../utils/types.js"; + +/** Tools that upload with `sentry` commands and read `.sentryclirc`. */ +const CLI_BASED_FLOW_TOOLS: readonly string[] = [ + "sentry-cli", + "tsc", + "angular", + "create-react-app", +]; + +/** + * Ask whether the user builds in CI and, if so, show the auth token to set + * there. Skipped for partner flows (Vercel) that already set the token. + * + * @param selectedTool - The build tool the wizard configured, such as `nextjs` + * @param authToken - The token written to the local config file + * @param comingFrom - The partner the command came from (`--coming-from`) + */ +export async function setupCI( + selectedTool: string, + authToken: string, + comingFrom: WizardOptions["comingFrom"], +): Promise { + if (comingFrom === "vercel") { + clack.log.info( + "Sentry Vercel integration is already configured. Skipping CI setup.", + ); + Sentry.setTag("using-ci", true); + } else { + await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + } +} + +/** Ask about CI and show the auth token to set there. */ +async function configureCI( + selectedTool: string, + authToken: string, +): Promise { + const isUsingCI = await abortIfCancelled( + clack.select({ + message: `Are you using a CI/CD tool to build and deploy your application?`, + options: [ + { + label: "Yes", + hint: "I use a tool like GitHub Actions, GitLab, CircleCI, TravisCI, Jenkins, Vercel, ...", + value: true, + }, + { + label: "No", + hint: "I build and deploy my application manually", + value: false, + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("using-ci", isUsingCI); + + const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + ? SENTRY_CLI_RC_FILE + : SENTRY_DOT_ENV_FILE; + + if (!isUsingCI) { + clack.log.info( + `No Problem! Just make sure that the Sentry auth token from ${chalk.cyan( + authTokenFile, + )} is available whenever you build and deploy your app.`, + ); + return; + } + + await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); +} + +/** Show the auth token to add to the CI environment. */ +async function setupAuthTokenInCI(authToken: string): Promise { + clack.log.step( + "Add the Sentry authentication token as an environment variable to your CI setup:", + ); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput( + chalk.greenBright(` +SENTRY_AUTH_TOKEN=${authToken} +`), + ); + + clack.log.warn( + chalk.yellow("DO NOT commit this auth token to your repository!"), + ); + + const addedEnvVarToCI = await abortIfCancelled( + clack.select({ + message: "Did you configure CI as shown above?", + options: [ + { label: "Yes, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + "You need to set the auth token to upload source maps in CI", + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-env-var-to-ci", addedEnvVarToCI); + + if (!addedEnvVarToCI) { + clack.log.info("Don't forget! :)"); + } +} diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts new file mode 100644 index 0000000000..09a39e330d --- /dev/null +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -0,0 +1,78 @@ +/** + * Telemetry for the setup wizards, recorded through the CLI's own Sentry + * client. + * + * `sentry wizard` already runs inside the CLI's command transaction, so a + * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` + * span under that. Tags go on the same scope as the CLI's. Telemetry is off + * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or + * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it + * off for the run. + * + * The old wizard sent its telemetry to a project of its own; the tag names + * stay the same so its dashboards can move over. + */ + +import { type Span, setTag, setUser, startSpan } from "@sentry/node"; +import type { WizardOptions } from "./utils/types.js"; + +/** + * The scope helpers the wizard flows call as `Sentry.setTag(…)`. + * + * Report errors with `reportCliError` from `lib/error-reporting.js`, never a + * raw `captureException`. + */ +export const Sentry = { setTag, setUser }; + +/** + * Run a wizard flow in a `wizard.flow` span, tagged with the integration and + * which of `--org`, `--project`, and `--saas` were passed. + */ +export async function withTelemetry( + options: { + /** Unused: the CLI decides whether telemetry is on. Kept for the flows' call sites. */ + enabled?: boolean | undefined; + integration: string; + wizardOptions: WizardOptions; + }, + callback: () => F | Promise, +): Promise { + setTag("integration", options.integration); + setTag("args.project", Boolean(options.wizardOptions.projectSlug)); + setTag("args.org", Boolean(options.wizardOptions.orgSlug)); + setTag("args.saas", Boolean(options.wizardOptions.saas)); + + return await startSpan( + { + name: "sentry-wizard-execution", + op: "wizard.flow", + onlyIfParent: true, + }, + async () => { + updateProgress("start"); + const result = await callback(); + updateProgress("finished"); + return result; + }, + ); +} + +/** + * Run one wizard step in a `wizard.step` span and record it as the latest + * `progress` tag, so an aborted run shows where it stopped. + */ +export function traceStep( + step: string, + callback: (span: Span | undefined) => T, +): T { + updateProgress(step); + return startSpan( + { name: step, op: "wizard.step", onlyIfParent: true }, + (span) => callback(span), + ); +} + +/** Record `step` as the furthest step the wizard reached. */ +export function updateProgress(step: string): void { + setTag("progress", step); +} diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts new file mode 100644 index 0000000000..fd740e4b6e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -0,0 +1,1781 @@ +/** + * Shared prompts and project helpers of the setup wizards: aborting, git + * checks, package installs, Sentry CLI config files, formatters, and + * copy/paste instructions. Ported from sentry-wizard's `src/utils/clack`. + * + * The wizards never exit the process: {@link abort} and + * {@link abortIfCancelled} throw a {@link WizardExitError}, which + * `sentry wizard` turns into its exit code. + */ + +import { execSync, spawn } from "node:child_process"; +import { + accessSync, + existsSync, + promises, + readFileSync, + writeFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import path, { basename, dirname, isAbsolute, join, relative } from "node:path"; +import chalk from "chalk"; +import { gte, minVersion, validRange } from "semver"; +import { sentry } from "../../../app-identity.js"; +import { CLI_VERSION } from "../../../constants.js"; +import { reportCliError } from "../../../error-reporting.js"; +import { WizardExitError } from "../../../errors.js"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { debug } from "../debug.js"; +import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; +import { + getPackageVersion, + hasPackageInstalled, + type PackageDotJson, +} from "../package-json.js"; +import { + _detectPackageManger, + NPM, + type PackageManager, + packageManagers, +} from "../package-manager.js"; +import { fulfillsVersionRange } from "../semver.js"; +import type { Feature } from "../types.js"; +import { clack } from "./prompts.js"; + +export { getOrAskForProjectData } from "../project-data.js"; + +export const SENTRY_DOT_ENV_FILE = ".env.sentry-build-plugin"; +export const SENTRY_CLI_RC_FILE = ".sentryclirc"; +export const SENTRY_PROPERTIES_FILE = "sentry.properties"; + +export interface CliSetupConfig { + filename: string; + name: string; + gitignore: boolean; + + likelyAlreadyHasAuthToken(contents: string): boolean; + tokenContent(authToken: string): string; + + likelyAlreadyHasOrgAndProject(contents: string): boolean; + orgAndProjContent(org: string, project: string): string; + + likelyAlreadyHasUrl?(contents: string): boolean; + urlContent?(url: string): string; +} + +export interface CliSetupConfigContent { + authToken: string; + org?: string | undefined; + project?: string | undefined; + url?: string | undefined; +} + +export const rcCliSetupConfig: CliSetupConfig = { + filename: SENTRY_CLI_RC_FILE, + name: "source maps", + gitignore: true, + likelyAlreadyHasAuthToken: function (contents: string): boolean { + return !!(contents.includes("[auth]") && contents.match(/token=./g)); + }, + tokenContent: function (authToken: string): string { + return `[auth]\ntoken=${authToken}`; + }, + likelyAlreadyHasOrgAndProject: function (contents: string): boolean { + return !!( + contents.includes("[defaults]") && + contents.match(/org=./g) && + contents.match(/project=./g) + ); + }, + orgAndProjContent: function (org: string, project: string): string { + return `[defaults]\norg=${org}\nproject=${project}`; + }, +}; + +export const propertiesCliSetupConfig: Required = { + filename: SENTRY_PROPERTIES_FILE, + gitignore: true, + name: "debug files", + likelyAlreadyHasAuthToken(contents: string): boolean { + return !!contents.match(/auth\.token=./g); + }, + tokenContent(authToken: string): string { + return `auth.token=${authToken}`; + }, + likelyAlreadyHasOrgAndProject(contents: string): boolean { + return !!( + contents.match(/defaults\.org=./g) && + contents.match(/defaults\.project=./g) + ); + }, + orgAndProjContent(org: string, project: string): string { + return `defaults.org=${org}\ndefaults.project=${project}`; + }, + likelyAlreadyHasUrl(contents: string): boolean { + return !!contents.match(/defaults\.url=./g); + }, + urlContent(url: string): string { + return `defaults.url=${url}`; + }, +}; + +/** + * Stop the wizard with `message`. `status` 0 means the user chose to stop; + * anything else is a failure. Throws, so code after it never runs. + * + * @param message - Shown as the outro. Defaults to "Wizard setup cancelled." + * @param status - Exit code of `sentry wizard`. Defaults to 1. + */ +export async function abort(message?: string, status?: number): Promise { + clack.outro(message ?? "Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", status === 0 ? "cancelled" : "aborted"); + throw new WizardExitError(status ?? 1); +} + +/** + * Resolve `input`, or stop the wizard with exit code 0 when the user + * cancelled the prompt (Ctrl+C). + */ +export async function abortIfCancelled( + input: T | Promise, +): Promise> { + const value = await input; + if (clack.isCancel(value)) { + clack.cancel("Wizard setup cancelled."); + Sentry.setTag("wizard.outcome", "cancelled"); + throw new WizardExitError(0); + } + return value as Exclude; +} + +/** Print the intro banner and welcome note of a wizard. */ +export function printWelcome(options: { + wizardName: string; + promoCode?: string | undefined; + message?: string | undefined; + telemetryEnabled?: boolean | undefined; +}): void { + clack.rawOutput(""); + clack.intro(chalk.inverse(` ${options.wizardName} `)); + + let welcomeText = + options.message || + `The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`; + + if (options.promoCode) { + welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`; + } + + welcomeText = `${welcomeText}\n\nVersion: ${CLI_VERSION}`; + + if (options.telemetryEnabled) { + welcomeText = `${welcomeText} + +This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. +You can turn this off at any time by running ${chalk.cyanBright( + sentry`wizard --disable-telemetry`, + )}.`; + } + + clack.note(welcomeText); +} + +/** + * Confirms if the user wants to continue with the wizard if the project is not a git repository. + * + * @param options.ignoreGitChanges If true, the wizard will not check if the project is a git repository. + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges, + cwd, + nonInteractive = false, +}: { + ignoreGitChanges: boolean | undefined; + cwd: string | undefined; + nonInteractive?: boolean | undefined; +}): Promise { + return await traceStep("check-git-status", async () => { + if ( + !isInGitRepo({ + cwd: cwd, + }) && + ignoreGitChanges !== true + ) { + if (nonInteractive) { + clack.log.error( + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-without-git", false); + await abort(); + } + + const continueWithoutGit = await abortIfCancelled( + clack.confirm({ + message: + "You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-without-git", continueWithoutGit); + + if (!continueWithoutGit) { + await abort(undefined, 0); + } + // return early to avoid checking for uncommitted files + return; + } + + const uncommittedOrUntrackedFilePaths = getUncommittedOrUntrackedFilePaths({ + cwd: cwd, + }); + + if (uncommittedOrUntrackedFilePaths.length && ignoreGitChanges !== true) { + clack.log.warn( + `You have uncommitted or untracked files in your repo: + +${uncommittedOrUntrackedFilePaths.map((file) => `- ${file}`).join("\n")} + +The wizard will create and update files.`, + ); + + if (nonInteractive) { + clack.log.error( + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + ); + Sentry.setTag("continue-with-dirty-repo", false); + await abort(); + } + + const continueWithDirtyRepo = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + + Sentry.setTag("continue-with-dirty-repo", continueWithDirtyRepo); + + if (!continueWithDirtyRepo) { + await abort(undefined, 0); + } + } + }); +} + +export async function askToInstallSentryCLI(): Promise { + return await abortIfCancelled( + clack.confirm({ + message: + "You don't have Sentry CLI installed. Do you want to install it?", + }), + ); +} + +export async function askForItemSelection( + items: string[], + message: string, +): Promise<{ value: string; index: number }> { + const selection: { value: string; index: number } | symbol = + await abortIfCancelled( + clack.select({ + maxItems: 12, + message: message, + options: items.map((item, index) => { + return { + value: { value: item, index: index }, + label: item, + }; + }), + }), + ); + + return selection; +} + +export async function confirmContinueIfPackageVersionNotSupported({ + packageId, + packageName, + packageVersion, + acceptableVersions, + note, +}: { + packageId: string; + packageName: string; + packageVersion: string; + acceptableVersions: string; + note?: string | undefined; +}): Promise { + return await traceStep(`check-package-version`, async () => { + Sentry.setTag(`${packageName.toLowerCase()}-version`, packageVersion); + const isSupportedVersion = fulfillsVersionRange({ + acceptableVersions, + version: packageVersion, + canBeLatest: true, + }); + + if (isSupportedVersion) { + Sentry.setTag(`${packageName.toLowerCase()}-supported`, true); + return; + } + + clack.log.warn( + `You have an unsupported version of ${packageName} installed: + + ${packageId}@${packageVersion}`, + ); + + clack.note( + note ?? + `Please upgrade to ${acceptableVersions} if you wish to use the Sentry Wizard.`, + ); + const continueWithUnsupportedVersion = await abortIfCancelled( + clack.confirm({ + message: "Do you want to continue anyway?", + }), + ); + Sentry.setTag( + `${packageName.toLowerCase()}-continue-with-unsupported-version`, + continueWithUnsupportedVersion, + ); + + if (!continueWithUnsupportedVersion) { + await abort(undefined, 0); + } + }); +} + +const JS_SDK_V11_MIGRATION_GUIDE_URL = + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/"; + +/** Docs guide slugs of the SDKs that have a platform-specific migration guide. */ +const JS_SDK_V11_MIGRATION_GUIDE_SLUGS: Record = { + "@sentry/angular": "angular", + "@sentry/cloudflare": "cloudflare", + "@sentry/nextjs": "nextjs", + "@sentry/nuxt": "nuxt", + "@sentry/react-router": "react-router", + "@sentry/remix": "remix", + "@sentry/sveltekit": "sveltekit", +}; + +function getSdkV11MigrationGuideUrl(packageName: string): string { + const slug = JS_SDK_V11_MIGRATION_GUIDE_SLUGS[packageName]; + + return slug + ? `https://docs.sentry.io/platforms/javascript/guides/${slug}/migration/v10-to-v11/` + : JS_SDK_V11_MIGRATION_GUIDE_URL; +} + +/** + * Logs a link to the v10 to v11 migration guide if @param packageName is + * already installed at a version below v11. The wizard updates the SDK to v11, + * which contains breaking changes the user must apply to their code. + */ +export function printSdkV11MigrationGuideIfOutdated( + packageName: string, + packageJson: PackageDotJson, +): void { + const installedRange = getPackageVersion(packageName, packageJson); + const installedVersion = + installedRange && validRange(installedRange) + ? minVersion(installedRange) + : null; + + if (!installedVersion || gte(installedVersion, "11.0.0")) { + return; + } + + clack.log.warn( + `The wizard updates ${chalk.cyan( + packageName, + )} to version 11, which has ${chalk.bold("breaking changes")}. +Follow the migration guide to update your code: ${chalk.cyan( + getSdkV11MigrationGuideUrl(packageName), + )}`, + ); +} + +type InstallPackageOptions = { + /** The string that is passed to the package manager CLI as identifier to install (e.g. `@sentry/nextjs`, or `@sentry/nextjs@^8`) */ + packageName: string; + alreadyInstalled: boolean; + askBeforeUpdating?: boolean | undefined; + /** Overrides what is shown in the installation logs in place of the `packageName` option. Useful if the `packageName` is ugly (e.g. `@sentry/nextjs@^8`) */ + packageNameDisplayLabel?: string | undefined; + packageManager?: PackageManager | undefined; + /** Add force install flag to command to skip install precondition fails */ + forceInstall?: boolean | undefined; + /** Install as a dev dependency (@default: false) */ + devDependency?: boolean | undefined; +}; + +/** + * Installs or updates a package with the user's package manager. + * + * IMPORTANT: This function modifies the `package.json`! Be sure to re-read + * it if you make additional modifications to it after calling this function! + */ +export async function installPackage({ + packageName, + alreadyInstalled, + askBeforeUpdating = true, + packageNameDisplayLabel, + packageManager, + forceInstall = false, + devDependency = false, +}: InstallPackageOptions): Promise<{ packageManager?: PackageManager }> { + return await traceStep("install-package", async () => { + if (alreadyInstalled && askBeforeUpdating) { + const shouldUpdatePackage = await abortIfCancelled( + clack.confirm({ + message: `The ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} package is already installed. Do you want to update it to the latest version?`, + }), + ); + + if (!shouldUpdatePackage) { + return {}; + } + } + + const sdkInstallSpinner = clack.spinner(); + + const pkgManager = packageManager || (await getPackageManager()); + + if (pkgManager.name === "pnpm") { + clack.log.info( + `If you use pnpm 11, dependency build scripts require explicit approval. If installation fails with ${chalk.cyan( + "ERR_PNPM_IGNORED_BUILDS", + )}, review the pending packages, run ${chalk.cyan( + "pnpm approve-builds", + )}, and then rerun the wizard.`, + ); + } + + sdkInstallSpinner.start( + `${alreadyInstalled ? "Updating" : "Installing"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + try { + await new Promise((resolve, reject) => { + const installArgs = [ + pkgManager.installCommand, + ...(devDependency ? ["-D"] : []), + pkgManager.registry + ? `${pkgManager.registry}:${packageName}` + : packageName, + ...(pkgManager.flags ? pkgManager.flags.split(" ") : []), + ...(forceInstall ? [pkgManager.forceInstallFlag] : []), + ]; + + const stringifiedInstallCmd = `${pkgManager.name} ${installArgs.join( + " ", + )}`; + + function handleErrorAndReject( + code: number | null, + cause: Error | string, + type: "spawn_error" | "process_error", + ) { + const output = [stdout, stderr].filter(Boolean).join("\n"); + // Write a log file so we can better troubleshoot issues + writeFileSync( + join( + process.cwd(), + `sentry-wizard-installation-error-${Date.now()}.log`, + ), + output, + { encoding: "utf8" }, + ); + + reportCliError(new Error("Package Installation Error"), { + tags: { + "install-command": stringifiedInstallCmd, + "package-manager": pkgManager.name, + "package-name": packageName, + "error-type": type, + }, + }); + + reject( + new Error( + `Installation command ${chalk.cyan( + stringifiedInstallCmd, + )} exited with code ${code ?? "null"}.`, + { + cause, + }, + ), + ); + } + + const installProcess = spawn(pkgManager.name, installArgs, { + shell: true, + // Ignoring Yarn `stdout` to prevent certain node + yarn v4 (observed on ubuntu + snap) + // combinations from crashing here. See #851 + stdio: [ + "pipe", + pkgManager.name === "yarn" ? "ignore" : "pipe", + "pipe", + ], + }); + + let stdout = ""; + let stderr = ""; + + // Defining data as unknown to avoid TS and ESLint errors because of `any` type + installProcess.stdout?.on("data", (data: unknown) => { + stdout += String(data); + }); + installProcess.stderr?.on("data", (data: unknown) => { + stderr += String(data); + }); + + installProcess.on("error", (err) => { + handleErrorAndReject(null, err, "spawn_error"); + }); + + installProcess.on("close", (code) => { + if (code !== 0) { + handleErrorAndReject(code, stderr, "process_error"); + } else { + resolve(); + } + }); + }); + } catch (e) { + sdkInstallSpinner.stop("Installation failed."); + clack.log.error( + `${chalk.red( + "Encountered the following error during installation:", + )}\n\n${String(e)}\n\n${chalk.dim( + "The wizard has created a `sentry-wizard-installation-error-*.log` file. Review it for sensitive information before sharing it. If you think this issue is caused by the Sentry wizard, create an issue on GitHub and include the redacted log file's content:\nhttps://github.com/getsentry/toolkit/issues", + )}`, + ); + await abort(); + } + + sdkInstallSpinner.stop( + `${alreadyInstalled ? "Updated" : "Installed"} ${chalk.bold.cyan( + packageNameDisplayLabel ?? packageName, + )} with ${chalk.bold(pkgManager.label)}.`, + ); + + return { packageManager: pkgManager }; + }); +} + +export async function addSentryCliConfig( + { authToken, org, project, url }: CliSetupConfigContent, + setupConfig: CliSetupConfig = rcCliSetupConfig, +): Promise { + return await traceStep("add-sentry-cli-config", async () => { + const configPath = join(process.cwd(), setupConfig.filename); + const configExists = existsSync(configPath); + + let configContents = + (configExists && readFileSync(configPath, "utf8")) || ""; + configContents = addAuthTokenToSentryConfig( + configContents, + authToken, + setupConfig, + ); + configContents = addOrgAndProjectToSentryConfig( + configContents, + org, + project, + setupConfig, + ); + configContents = addUrlToSentryConfig(configContents, url, setupConfig); + + try { + await promises.writeFile(configPath, configContents, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `${configExists ? "Saved" : "Created"} ${chalk.cyan( + setupConfig.filename, + )}.`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.cyan( + setupConfig.filename, + )}. Uploading ${ + setupConfig.name + } during build will likely not work locally.`, + ); + } + + if (setupConfig.gitignore) { + await addCliConfigFileToGitIgnore(setupConfig.filename); + } else { + clack.log.warn( + chalk.yellow("DO NOT commit auth token to your repository!"), + ); + } + }); +} + +function addAuthTokenToSentryConfig( + configContents: string, + authToken: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!authToken) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasAuthToken(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has auth token. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.tokenContent( + authToken, + )}\n`; + clack.log.success( + `Added auth token to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addOrgAndProjectToSentryConfig( + configContents: string, + org: string | undefined, + project: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!org || !project) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasOrgAndProject(configContents)) { + clack.log.warn( + `${chalk.cyan( + setupConfig.filename, + )} already has org and project. Will not add them.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.orgAndProjContent( + org, + project, + )}\n`; + clack.log.success( + `Added default org and project to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +function addUrlToSentryConfig( + configContents: string, + url: string | undefined, + setupConfig: CliSetupConfig, +): string { + if (!url || !setupConfig.urlContent || !setupConfig.likelyAlreadyHasUrl) { + return configContents; + } + + if (setupConfig.likelyAlreadyHasUrl(configContents)) { + clack.log.warn( + `${chalk.cyan(setupConfig.filename)} already has url. Will not add one.`, + ); + return configContents; + } + + const newContents = `${configContents}\n${setupConfig.urlContent(url)}\n`; + clack.log.success( + `Added default url to ${chalk.cyan( + setupConfig.filename, + )} for you to test uploading ${setupConfig.name} locally.`, + ); + return newContents; +} + +export async function addDotEnvSentryBuildPluginFile( + authToken: string, +): Promise { + const envVarContent = `# DO NOT commit this file to your repository! +# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin. +# It's used for authentication when uploading source maps. +# You can also set this env variable in your own \`.env\` files and remove this file. +SENTRY_AUTH_TOKEN=${authToken} +`; + + const dotEnvFilePath = join(process.cwd(), SENTRY_DOT_ENV_FILE); + const dotEnvFileExists = existsSync(dotEnvFilePath); + + if (dotEnvFileExists) { + const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); + + const hasAuthToken = !!dotEnvFileContent.match( + /^\s*SENTRY_AUTH_TOKEN\s*=/g, + ); + + if (hasAuthToken) { + clack.log.warn( + `${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} already has auth token. Will not add one.`, + ); + } else { + try { + await promises.writeFile( + dotEnvFilePath, + `${dotEnvFileContent}\n${envVarContent}`, + { + encoding: "utf8", + flag: "w", + }, + ); + clack.log.success( + `Added auth token to ${chalk.bold.cyan(SENTRY_DOT_ENV_FILE)}`, + ); + } catch { + clack.log.warning( + `Failed to add auth token to ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )}. Uploading source maps during build will likely not work locally.`, + ); + } + } + } else { + try { + await promises.writeFile(dotEnvFilePath, envVarContent, { + encoding: "utf8", + flag: "w", + }); + clack.log.success( + `Created ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token for you to test source map uploading locally.`, + ); + } catch { + clack.log.warning( + `Failed to create ${chalk.bold.cyan( + SENTRY_DOT_ENV_FILE, + )} with auth token. Uploading source maps during build will likely not work locally.`, + ); + } + } + + await addCliConfigFileToGitIgnore(SENTRY_DOT_ENV_FILE); +} + +async function addCliConfigFileToGitIgnore(filename: string): Promise { + const gitignorePath = join(process.cwd(), ".gitignore"); + + try { + const gitignoreContent = await promises.readFile(gitignorePath, "utf8"); + if (gitignoreContent.split(/\r?\n/).includes(filename)) { + clack.log.info( + `${chalk.bold(".gitignore")} already has ${chalk.bold( + filename, + )}. Will not add it again.`, + ); + return; + } + + await promises.appendFile( + gitignorePath, + `\n# Sentry Config File\n${filename}\n`, + { encoding: "utf8" }, + ); + clack.log.success( + `Added ${chalk.cyan(filename)} to ${chalk.cyan(".gitignore")}.`, + ); + } catch { + clack.log.error( + `Failed adding ${chalk.cyan(filename)} to ${chalk.cyan( + ".gitignore", + )}. Please add it manually!`, + ); + } +} + +/** + * Returns the changed or untracked files for the formatter step, or null if not + * in a git repo or nothing changed. + */ +function getFormatterTargetFiles(): string[] | null { + if (!isInGitRepo({ cwd: undefined })) { + return null; + } + + const changedOrUntrackedFiles = + getUncommittedOrUntrackedFilePaths().filter(Boolean); + + return changedOrUntrackedFiles.length ? changedOrUntrackedFiles : null; +} + +/** Resolves a package's bin entry point from the target project, or null. */ +function resolveFormatterBinary( + packageName: string, + binName: string, +): string | null { + const requireFromProject = createRequire(join(process.cwd(), "package.json")); + + const packageJsonCandidates: string[] = []; + try { + packageJsonCandidates.push( + requireFromProject.resolve(`${packageName}/package.json`), + ); + } catch (error) { + debug(error); + // Package may not expose package.json via exports; fall through. + } + packageJsonCandidates.push( + join(process.cwd(), "node_modules", packageName, "package.json"), + ); + + for (const packageJsonPath of packageJsonCandidates) { + try { + const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8")) as { + bin?: string | Record | undefined; + }; + const relativeBin = + typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[binName]; + if (relativeBin) { + return join(dirname(packageJsonPath), relativeBin); + } + } catch (error) { + debug(error); + // Try the next candidate. + } + } + + return null; +} + +/** + * Runs a formatter without passing file names through a shell (command + * injection) and with a `--` separator (option injection). POSIX runs `npx` + * directly; Windows resolves the bin and runs it via Node, since `npx.cmd` + * would otherwise need a shell. + * + * @param packageName The npm package that provides the formatter. + * @param binName The bin entry to run from that package (Windows only). + * @param subArgs The formatter flags and subcommands. + * @param files The file paths to format. + * @param options.ignoreExitCode When true, a non-zero exit or unresolved binary resolves instead of rejecting. + */ +function runFormatterCommand( + packageName: string, + binName: string, + subArgs: string[], + files: string[], + { ignoreExitCode }: { ignoreExitCode: boolean }, +): Promise { + let command: string; + let args: string[]; + + if (process.platform === "win32") { + const binPath = resolveFormatterBinary(packageName, binName); + if (!binPath) { + return ignoreExitCode + ? Promise.resolve() + : Promise.reject( + new Error(`Could not resolve the ${packageName} binary.`), + ); + } + command = process.execPath; + args = [binPath, ...subArgs, "--", ...files]; + } else { + command = "npx"; + args = [packageName, ...subArgs, "--", ...files]; + } + + return new Promise((resolve, reject) => { + const child = spawn(command, args, { + shell: false, + stdio: "ignore", + }); + + child.on("error", (err) => { + if (ignoreExitCode) { + resolve(); + } else { + reject(err); + } + }); + + child.on("close", (code) => { + if (code !== 0 && !ignoreExitCode) { + reject(new Error(`Formatter exited with code ${code ?? "null"}.`)); + } else { + resolve(); + } + }); + }); +} + +/** + * Runs available formatters (Prettier and/or Biome) on the changed or untracked files in the project. + * This function provides a unified interface for running multiple formatters with a single user prompt. + * + * @param _opts The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runFormatters(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-formatters", async () => { + const targetFiles = getFormatterTargetFiles(); + if (!targetFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + Sentry.setTag("biome-installed", biomeInstalled); + + if (!prettierInstalled && !biomeInstalled) { + return; + } + + // Determine prompt message based on what's installed + const formattersAvailable = []; + if (prettierInstalled) formattersAvailable.push("Prettier"); + if (biomeInstalled) formattersAvailable.push("Biome"); + + const message = + formattersAvailable.length === 1 + ? `Looks like you have ${formattersAvailable[0]} in your project. Do you want to run it on your files?` + : `Looks like you have ${formattersAvailable.join( + " and ", + )} in your project. Do you want to run them on your files?`; + + const shouldRun = await abortIfCancelled(clack.confirm({ message })); + + if (!shouldRun) { + return; + } + + const spinner = clack.spinner(); + spinner.start("Running formatters on your files."); + + try { + // Run Prettier first if installed (handles general formatting) + if (prettierInstalled) { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + targetFiles, + { ignoreExitCode: false }, + ); + } + + // Run Biome if installed (handles linting + additional formatting) + if (biomeInstalled) { + // Format first + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + targetFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + // Then lint with fixes (using --unsafe for auto-fixable issues) + // See: https://biomejs.dev/linter/#unsafe-fixes + // The --unsafe flag applies potentially behavior-changing fixes like removing unused imports. + // This is acceptable for wizard-generated code which may have fixable issues. + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + targetFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } + + spinner.stop("Formatters have processed your files."); + } catch (e) { + spinner.stop("Formatting encountered an issue."); + clack.log.warn( + "Formatting encountered an issue. There may be formatting or linting issues in your updated files.", + ); + } + }); +} + +/** + * Runs prettier on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runPrettierIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-prettier", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const prettierInstalled = hasPackageInstalled("prettier", packageJson); + + Sentry.setTag("prettier-installed", prettierInstalled); + + if (!prettierInstalled) { + return; + } + + // prompt the user if they want to run prettier + const shouldRunPrettier = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Prettier in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunPrettier) { + return; + } + + const prettierSpinner = clack.spinner(); + prettierSpinner.start("Running Prettier on your files."); + + try { + await runFormatterCommand( + "prettier", + "prettier", + ["--ignore-unknown", "--write"], + changedOrUntrackedFiles, + { ignoreExitCode: false }, + ); + } catch (e) { + prettierSpinner.stop("Prettier failed to run."); + clack.log.warn( + "Prettier failed to run. There may be formatting issues in your updated files.", + ); + return; + } + + prettierSpinner.stop("Prettier has formatted your files."); + }); +} + +/** + * Runs Biome on the changed or untracked files in the project. + * + * @param options.cwd The directory of the project. If undefined, the current process working directory will be used. + */ +export async function runBiomeIfInstalled(_opts: { + cwd: string | undefined; +}): Promise { + return await traceStep("run-biome", async () => { + const changedOrUntrackedFiles = getFormatterTargetFiles(); + if (!changedOrUntrackedFiles) { + return; + } + + const packageJson = await getPackageDotJson(); + const biomeInstalled = hasPackageInstalled("@biomejs/biome", packageJson); + + Sentry.setTag("biome-installed", biomeInstalled); + + if (!biomeInstalled) { + return; + } + + // prompt the user if they want to run biome + const shouldRunBiome = await abortIfCancelled( + clack.confirm({ + message: + "Looks like you have Biome in your project. Do you want to run it on your files?", + }), + ); + + if (!shouldRunBiome) { + return; + } + + const biomeSpinner = clack.spinner(); + biomeSpinner.start("Running Biome on your files."); + + try { + // Use biome format --write for formatting (always succeeds if it can format) + // Then biome check --write for lint fixes + // We ignore exit codes because Biome exits non-zero if there are unfixable issues + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["format", "--write"], + changedOrUntrackedFiles, + // Ignore errors, just continue + { ignoreExitCode: true }, + ); + + await runFormatterCommand( + "@biomejs/biome", + "biome", + ["check", "--write", "--unsafe"], + changedOrUntrackedFiles, + // Ignore errors, Biome exits non-zero if there are remaining issues + { ignoreExitCode: true }, + ); + } catch (e) { + biomeSpinner.stop("Biome encountered an issue."); + clack.log.warn( + "Biome encountered an issue. There may be formatting or linting issues in your updated files.", + ); + return; + } + + biomeSpinner.stop("Biome has formatted your files."); + }); +} + +/** + * Checks if @param packageId is listed as a dependency in @param packageJson. + * If not, it will ask users if they want to continue without the package. + * + * Use this function to check if e.g. a the framework of the SDK is installed + * + * @param packageJson the package.json object + * @param packageId the npm name of the package + * @param packageName a human readable name of the package + */ +export async function ensurePackageIsInstalled( + packageJson: PackageDotJson, + packageId: string, + packageName: string, +): Promise { + return await traceStep("ensure-package-installed", async () => { + const installed = hasPackageInstalled(packageId, packageJson); + + Sentry.setTag(`${packageName.toLowerCase()}-installed`, installed); + + if (!installed) { + Sentry.setTag(`${packageName.toLowerCase()}-installed`, false); + const continueWithoutPackage = await abortIfCancelled( + clack.confirm({ + message: `${packageName} does not seem to be installed. Do you still want to continue?`, + initialValue: false, + }), + ); + + if (!continueWithoutPackage) { + await abort(undefined, 0); + } + } + }); +} + +export async function getPackageDotJson(): Promise { + const packageJsonFileContents = await promises + .readFile(join(process.cwd(), "package.json"), "utf8") + .catch(() => { + clack.log.error( + "Could not find package.json. Make sure to run the wizard in the root of your app!", + ); + return abort(); + }); + + let packageJson: PackageDotJson | undefined = undefined; + + try { + packageJson = JSON.parse(packageJsonFileContents); + } catch { + clack.log.error( + `Unable to parse your ${chalk.cyan( + "package.json", + )}. Make sure it has a valid format!`, + ); + + await abort(); + } + + return packageJson || {}; +} + +export async function updatePackageDotJson( + packageDotJson: PackageDotJson, +): Promise { + try { + await promises.writeFile( + join(process.cwd(), "package.json"), + // TODO: maybe figure out the original indentation + JSON.stringify(packageDotJson, null, 2), + { + encoding: "utf8", + flag: "w", + }, + ); + } catch { + clack.log.error(`Unable to update your ${chalk.cyan("package.json")}.`); + + await abort(); + } +} + +/** + * Use this function to get the used JS Package manager. + * + * This function: + * - attempts to auto-detect the used package manager and return it + * - if unsuccessful, returns the passed fallback package manager + * - if no fallback is passed, it asks the user to select a package manager + * + * The result is cached on the first invocation to avoid asking the user multiple times. + * + * @param fallback the package manager to use if auto-detection fails and you don't want to + * ask the user. This is useful in cases where asking users would be too intrusive/low in value + * and where it's okay to fall back to a default package manager. Use this with caution. + */ +export async function getPackageManager( + fallback?: PackageManager, +): Promise { + const globalWithSentryWizard: typeof global & { + __sentry_wizard_cached_package_manager?: PackageManager | undefined; + } = global; + + if (globalWithSentryWizard.__sentry_wizard_cached_package_manager) { + return globalWithSentryWizard.__sentry_wizard_cached_package_manager; + } + + const detectedPackageManager = _detectPackageManger(); + + if (detectedPackageManager) { + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + detectedPackageManager; + return detectedPackageManager; + } + + if (fallback) { + // explicitly avoiding to cache the fallback in case this function + // gets called again without a fallback (or a different fallback) + // later on in the wizard flow. + return fallback; + } + + const selectedPackageManager: PackageManager | symbol = + await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); + + globalWithSentryWizard.__sentry_wizard_cached_package_manager = + selectedPackageManager; + + Sentry.setTag("package-manager", selectedPackageManager.name); + + return selectedPackageManager; +} + +export function isUsingTypeScript() { + try { + return existsSync(join(process.cwd(), "tsconfig.json")); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Asks users if they have a config file for @param tool (e.g. Vite). + * If yes, asks users to specify the path to their config file. + * + * Use this helper function as a fallback mechanism if the lookup for + * a config file with its most usual location/name fails. + * + * @param toolName Name of the tool for which we're looking for the config file + * @param configFileName Name of the most common config file name (e.g. vite.config.js) + * + * @returns a user path to the config file or undefined if the user doesn't have a config file + */ +export async function askForToolConfigPath( + toolName: string, + configFileName: string, +): Promise { + const hasConfig = await abortIfCancelled( + clack.confirm({ + message: `Do you have a ${toolName} config file (e.g. ${chalk.cyan( + configFileName, + )})?`, + initialValue: true, + }), + ); + + if (!hasConfig) { + return undefined; + } + + return await abortIfCancelled( + clack.text({ + message: `Please enter the path to your ${toolName} config file:`, + placeholder: join(".", configFileName), + validate: (value) => { + if (!value) { + return "Please enter a path."; + } + + try { + accessSync(value); + } catch (error) { + debug(error); + return "Could not access the file at this path."; + } + return undefined; + }, + }), + ); +} + +type ShowCopyPasteInstructionsOptions = { codeSnippet: string } & ( + | { + filename: string; + hint?: string | undefined; + } + | { + instructions: string; + } +); + +/** + * Prints copy/paste-able instructions to the console. + * Afterwards asks the user if they added the code snippet to their file. + * + * While there's no point in providing a "no" answer here, it gives users time to fulfill the + * task before the wizard continues with additional steps. + * + * Use this function if you want to show users instructions on how to add/modify + * code in their file. This is helpful if automatic insertion failed or is not possible/feasible. + * + * @param filename the name of the file to which the code snippet should be applied. + * If a path is provided, only the filename will be used. + * + * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the + * diff-like format for visually highlighting unchanged or modified lines of code. + * + * @param hint (optional) a hint to be printed after the main instruction to add + * the code from @param codeSnippet to their @param filename. + * + * More guidelines on copy/paste instructions: + * @see {@link https://develop.sentry.dev/sdk/setup-wizards/#copy--paste-snippets} + * + * TODO: refactor copy paste instructions across different wizards to use this function. + * this might require adding a custom message parameter to the function + */ +export async function showCopyPasteInstructions( + opts: ShowCopyPasteInstructionsOptions, +): Promise { + if ("instructions" in opts) { + clack.log.step(opts.instructions); + } else { + const defaultInstructions = `Add the following code to your ${chalk.cyan( + basename(opts.filename), + )} file:${opts.hint ? chalk.dim(` (${chalk.dim(opts.hint)})`) : ""}`; + + clack.log.step(defaultInstructions); + } + + // Padding the code snippet to be printed with a \n at the beginning and end + // This makes it easier to distinguish the snippet from the rest of the output + // Printed outside clack's gutter so that the code can be copied/pasted directly + clack.rawOutput(`\n${opts.codeSnippet}\n`); + + await abortIfCancelled( + clack.select({ + message: "Did you apply the snippet above?", + options: [{ label: "Yes, continue!", value: true }], + initialValue: true, + }), + ); +} + +/** + * Callback that exposes formatting helpers for a code snippet. + * @param unchanged - Formats text as old code. + * @param plus - Formats text as new code. + * @param minus - Formats text as removed code. + */ +type CodeSnippetFormatter = ( + unchanged: (txt: string) => string, + plus: (txt: string) => string, + minus: (txt: string) => string, +) => string; + +/** + * Crafts a code snippet that can be used to e.g. + * - print copy/paste instructions to the console + * - create a new config file. + * + * @param colors set this to true if you want the final snippet to be colored. + * This is useful for printing the snippet to the console as part of copy/paste instructions. + * + * @param callback the callback that returns the formatted code snippet. + * It exposes takes the helper functions for marking code as unchanged, new or removed. + * These functions no-op if no special formatting should be applied + * and otherwise apply the appropriate formatting/coloring. + * (@see {@link CodeSnippetFormatter}) + * + * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console. + * + * @returns a string containing the final, formatted code snippet. + */ +export function makeCodeSnippet( + colors: boolean, + callback: CodeSnippetFormatter, +): string { + const unchanged = (txt: string) => (colors ? chalk.grey(txt) : txt); + const plus = (txt: string) => (colors ? chalk.greenBright(txt) : txt); + const minus = (txt: string) => (colors ? chalk.redBright(txt) : txt); + + return callback(unchanged, plus, minus); +} + +/** + * Creates a new config file with the given @param filepath and @param codeSnippet. + * + * Use this function to create a new config file for users. This is useful + * when users answered that they don't yet have a config file for a tool. + * + * (This doesn't mean that they don't yet have some other way of configuring + * their tool but we can leave it up to them to figure out how to merge configs + * here.) + * + * @param filepath absolute path to the new config file + * @param codeSnippet the snippet to be inserted into the file + * @param moreInformation (optional) the message to be printed after the file was created + * For example, this can be a link to more information about configuring the tool. + * + * @returns true on success, false otherwise + */ +export async function createNewConfigFile( + filepath: string, + codeSnippet: string, + moreInformation?: string, +): Promise { + if (!isAbsolute(filepath)) { + debug(`createNewConfigFile: filepath is not absolute: ${filepath}`); + return false; + } + + const prettyFilename = chalk.cyan(relative(process.cwd(), filepath)); + + try { + await promises.writeFile(filepath, codeSnippet); + + clack.log.success(`Added new ${prettyFilename} file.`); + + if (moreInformation) { + clack.log.info(chalk.gray(moreInformation)); + } + + return true; + } catch (e) { + debug(e); + clack.log.warn( + `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`, + ); + } + + return false; +} + +export async function askShouldCreateExamplePage( + customRoute?: string, +): Promise { + const route = chalk.cyan(customRoute ?? "/sentry-example-page"); + + const createExamplePage = await traceStep("ask-create-example-page", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example page ("${route}") to test your Sentry setup?`, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); + + Sentry.setTag("create-example-page", createExamplePage); + return createExamplePage; +} + +export async function askShouldCreateExampleComponent(): Promise { + return await traceStep("ask-create-example-component", () => + abortIfCancelled( + clack.select({ + message: `Do you want to create an example component to test your Sentry setup?`, + options: [ + { + value: true, + label: "Yes", + hint: "Recommended - Check your git status before committing!", + }, + { value: false, label: "No" }, + ], + }), + ), + ); +} + +export async function featureSelectionPrompt>( + features: F, +): Promise> { + return await traceStep("feature-selection", async () => { + const selectedFeatures: Record = {}; + + for (const feature of features) { + const selected = await abortIfCancelled( + clack.select({ + message: feature.prompt, + initialValue: true, + options: [ + { + value: true, + label: "Yes", + ...(feature.enabledHint ? { hint: feature.enabledHint } : {}), + }, + { + value: false, + label: "No", + ...(feature.disabledHint ? { hint: feature.disabledHint } : {}), + }, + ], + }), + ); + + selectedFeatures[feature.id] = selected; + } + + return selectedFeatures; + }); +} + +export async function askShouldInstallPackage( + pkgName: string, +): Promise { + return await traceStep(`ask-install-package`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to install ${chalk.cyan(pkgName)}?`, + }), + ), + ); +} + +export async function askShouldAddPackageOverride( + pkgName: string, + pkgVersion: string, +): Promise { + return await traceStep(`ask-add-package-override`, () => + abortIfCancelled( + clack.confirm({ + message: `Do you want to add an override for ${chalk.cyan( + pkgName, + )} version ${chalk.cyan(pkgVersion)}?`, + }), + ), + ); +} + +async function getBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + return typeof packageDotJson.scripts?.["build"] === "string" ? "build" : null; +} + +export function artifactsExist(relativePath: string): boolean { + return existsSync(path.join(process.cwd(), relativePath)); +} + +export async function askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, +}: { + relativeArtifactPath: string; +}): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const options: { label: string; value: string }[] = []; + + const buildCommand = await getBuildCommand(); + + if (buildCommand) { + options.push({ + label: "Let the wizard run the build command", + value: "run-build", + }); + } + + options.push( + { + label: "Enter a different path manually", + value: "manual", + }, + { + label: "Proceed anyway — I believe the path is correct", + value: "proceed", + }, + ); + + const whatToDo = await abortIfCancelled( + clack.select({ + message: `We couldn't find build artifacts at "${relativeArtifactPath}". What would you like to do?`, + options, + initialValue: buildCommand ? "run-build" : "manual", + }), + ); + + if (whatToDo === "proceed") { + return { + validPath: true, + }; + } + + if (whatToDo === "run-build" && buildCommand) { + const ranBuildAndCheckArtifacts = await runBuildAndCheckArtifacts( + buildCommand, + relativeArtifactPath, + ); + + if (!ranBuildAndCheckArtifacts.validPath) { + return await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath }); + } + + return ranBuildAndCheckArtifacts; + } + + return { + validPath: false, + }; +} + +function getPossibleBuildFolders(): string[] { + const commonBuildFolders = ["build", "dist", "out", ".next"]; + + return commonBuildFolders.filter((folder) => + existsSync(path.join(process.cwd(), folder)), + ); +} + +async function promptForAlternativeArtifactPath(): Promise { + const folders = getPossibleBuildFolders(); + + if (!folders.length) { + return undefined; + } + + if (folders.length === 1) { + const [onlyFolder] = folders; + + const confirmed = await abortIfCancelled( + clack.select({ + message: `Detected one possible build folder. Use "${onlyFolder}" as your build artifacts folder?`, + options: [ + { + value: true, + label: "Yes", + }, + { value: false, label: "No" }, + ], + }), + ); + + return confirmed ? onlyFolder : undefined; + } + + const selected = await abortIfCancelled( + clack.select({ + message: `Detected multiple possible build folders. Is one of these your build artifacts folder?`, + options: [ + ...folders.map((f) => ({ value: f, label: f })), + { value: false, label: "No" }, + ], + }), + ); + + if (selected) { + return String(selected); + } + + return undefined; +} + +async function runBuildCommand(buildCommand: string): Promise { + const packageManager = await getPackageManager(NPM); + const command = `${packageManager.runScriptCommand} ${buildCommand}`; + const spinner = clack.spinner(); + + spinner.start(`Running ${chalk.cyan(command)}...`); + try { + execSync(command, { + stdio: "inherit", + cwd: process.cwd(), + }); + spinner.stop("Build finished running."); + return true; + } catch (error) { + spinner.stop( + `Build failed: ${error instanceof Error ? error.message : String(error)}`, + ); + clack.log.error( + "Failed to run your build command. Please run it manually and try again.", + ); + return false; + } +} + +async function runBuildAndCheckArtifacts( + buildCommand: string, + relativeArtifactPath: string, +): Promise<{ validPath: boolean; relativeArtifactPath?: string }> { + const buildRan = await runBuildCommand(buildCommand); + + if (!buildRan) { + return { validPath: false }; + } + + const found = artifactsExist(relativeArtifactPath); + + if (found) { + clack.log.success("Build completed and build artifacts folder found!"); + return { validPath: true }; + } + + clack.log.warn( + `Build ran, but build artifacts folder still not found at ${relativeArtifactPath}.`, + ); + + const fallbackPath = await promptForAlternativeArtifactPath(); + + if (!fallbackPath) { + return { validPath: false }; + } + + return { + validPath: artifactsExist(fallbackPath), + relativeArtifactPath: fallbackPath, + }; +} diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts new file mode 100644 index 0000000000..867c9c0140 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -0,0 +1,639 @@ +/** + * Offer to add a project-scoped Sentry MCP server to the user's editors + * (Cursor, VS Code, Claude Code) at the end of a wizard run. + */ + +import { mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { Sentry } from "../../telemetry.js"; +import chalk from "chalk"; +import { clack } from "./prompts.js"; +import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { debug } from "../debug.js"; + +const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; + +// Type definitions for MCP configurations +interface CursorMcpConfig { + mcpServers?: Record | undefined; +} + +interface VsCodeMcpConfig { + servers?: Record | undefined; +} + +interface ClaudeCodeMcpConfig { + mcpServers?: Record | undefined; +} + +interface OpenCodeMcpConfig { + $schema?: string | undefined; + mcp?: + | Record + | undefined; +} + +/** + * Constructs the MCP URL with optional org and project slugs + */ +function getMcpUrl(orgSlug?: string, projectSlug?: string): string { + if (orgSlug && projectSlug) { + return `${SENTRY_MCP_BASE_URL}/${orgSlug}/${projectSlug}`; + } + return SENTRY_MCP_BASE_URL; +} + +function ensureDir(dirpath: string): void { + mkdirSync(dirpath, { recursive: true }); +} + +async function readJsonIfExists(filepath: string): Promise { + try { + const txt = await promises.readFile(filepath, "utf8"); + return JSON.parse(txt) as unknown; + } catch (error) { + debug(error); + return null; + } +} + +async function writeJson(filepath: string, obj: unknown): Promise { + ensureDir(path.dirname(filepath)); + await promises.writeFile(filepath, JSON.stringify(obj, null, 2), "utf8"); +} + +function getCursorMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getVsCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + servers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getClaudeCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getJetBrainsMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getOpenCodeMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + $schema: "https://opencode.ai/config.json", + mcp: { + Sentry: { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +function getGenericMcpJsonSnippet( + orgSlug?: string, + projectSlug?: string, +): string { + const obj = { + mcpServers: { + Sentry: { + url: getMcpUrl(orgSlug, projectSlug), + }, + }, + } as const; + return JSON.stringify(obj, null, 2); +} + +async function addCursorMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".cursor", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getCursorMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".cursor", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as CursorMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .cursor/mcp.json"); + } catch { + throw new Error("Failed to update .cursor/mcp.json"); + } +} + +async function addVsCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".vscode", "mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getVsCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success( + chalk.cyan(path.join(".vscode", "mcp.json")) + " created.", + ); + return; + } + try { + const updated = { ...existing } as VsCodeMcpConfig; + updated.servers = updated.servers || {}; + updated.servers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + type: "http", + }; + await writeJson(file, updated); + clack.log.success("Updated .vscode/mcp.json"); + } catch { + throw new Error("Failed to update .vscode/mcp.json"); + } +} + +async function addClaudeCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), ".mcp.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan(".mcp.json") + " created."); + return; + } + try { + const updated = { ...existing } as ClaudeCodeMcpConfig; + updated.mcpServers = updated.mcpServers || {}; + updated.mcpServers["Sentry"] = { + url: getMcpUrl(orgSlug, projectSlug), + }; + await writeJson(file, updated); + clack.log.success("Updated .mcp.json"); + } catch { + throw new Error("Failed to update .mcp.json"); + } +} + +async function addOpenCodeMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const file = path.join(process.cwd(), "opencode.json"); + const existing = await readJsonIfExists(file); + if (!existing) { + await writeJson( + file, + JSON.parse(getOpenCodeMcpJsonSnippet(orgSlug, projectSlug)), + ); + clack.log.success(chalk.cyan("opencode.json") + " created."); + return; + } + try { + const updated = { ...existing } as OpenCodeMcpConfig; + updated.$schema ||= "https://opencode.ai/config.json"; + updated.mcp = updated.mcp || {}; + updated.mcp["Sentry"] = { + type: "remote", + url: getMcpUrl(orgSlug, projectSlug), + oauth: {}, + }; + await writeJson(file, updated); + clack.log.success("Updated opencode.json"); + } catch { + throw new Error("Failed to update opencode.json"); + } +} + +/** + * Copies text to clipboard across different platforms + */ +async function copyToClipboard(text: string): Promise { + try { + const platform = process.platform; + let command: string; + + if (platform === "darwin") { + command = "pbcopy"; + } else if (platform === "win32") { + command = "clip"; + } else { + // Linux + command = "xclip -selection clipboard"; + } + + const proc = spawn(command, [], { shell: true }); + proc.stdin.write(text); + proc.stdin.end(); + + return await new Promise((resolve) => { + proc.on("close", (code) => { + resolve(code === 0); + }); + proc.on("error", () => { + resolve(false); + }); + }); + } catch (error) { + debug(error); + return false; + } +} + +/** + * Shows MCP configuration for JetBrains IDEs with copy-to-clipboard option + */ +async function showJetBrainsMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getJetBrainsMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info( + chalk.cyan("For JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm, etc.):"), + ); + clack.log.info( + chalk.dim( + "Add the following configuration to your IDE's MCP settings.\n" + + "See: https://www.jetbrains.com/help/webstorm/mcp-server.html", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: You may need to restart your IDE for MCP changes to take effect.", + ), + ); +} + +/** + * Shows generic MCP configuration for unsupported IDEs with copy-to-clipboard option + */ +async function showGenericMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + const configSnippet = getGenericMcpJsonSnippet(orgSlug, projectSlug); + + clack.log.info(chalk.cyan("Generic MCP configuration for your IDE:")); + clack.log.info( + chalk.dim( + "If your IDE supports MCP servers, you can use the following configuration.\n" + + "Please consult your IDE's documentation for how to add MCP server configurations.", + ), + ); + + // Display the configuration + clack.rawOutput("\n" + chalk.green(configSnippet) + "\n"); + + // Ask if user wants to copy to clipboard + const shouldCopy: boolean = await abortIfCancelled( + clack.select({ + message: "Copy configuration to clipboard?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + if (shouldCopy) { + const copied = await copyToClipboard(configSnippet); + + if (copied) { + clack.log.success("Configuration copied to clipboard!"); + Sentry.setTag("mcp-clipboard-copy", "success"); + } else { + clack.log.warn( + "Failed to copy to clipboard. Please copy the configuration above manually.", + ); + Sentry.setTag("mcp-clipboard-copy", "failed"); + } + } else { + Sentry.setTag("mcp-clipboard-copy", "declined"); + } + + clack.log.info( + chalk.dim( + "Note: The exact configuration format may vary depending on your IDE.\n" + + "If your IDE doesn't support MCP yet, please check back later or open an issue at:\n" + + "https://github.com/getsentry/toolkit/issues", + ), + ); +} + +/** + * Explains what MCP is and its benefits for Sentry users + */ +async function explainMCP(): Promise { + clack.log.info(chalk.cyan("What is MCP (Model Context Protocol)?")); + + clack.log.info( + chalk.dim( + "MCP is a protocol that allows AI assistants in your IDE to interact with external tools and services.\n\n" + + "The Sentry MCP server enables AI assistants to:\n" + + " • Query and analyze your Sentry issues directly from your IDE\n" + + " • Get context about errors and performance problems\n" + + " • Help debug issues with production data insights\n" + + " • Suggest fixes based on real error patterns\n\n" + + "This makes it easier to fix bugs by bringing Sentry's insights directly into your development workflow.\n\n" + + "Learn more: " + + chalk.cyan("https://docs.sentry.io/product/sentry-mcp/"), + ), + ); + + // Ask again after explanation + const shouldAddAfterExplanation: boolean = await abortIfCancelled( + clack.select({ + message: "Would you like to configure MCP for your IDE now?", + options: [ + { label: "Yes", value: true }, + { label: "No", value: false, hint: "You can add it later anytime" }, + ], + initialValue: true, + }), + ); + + return shouldAddAfterExplanation; +} + +/** + * Offers to add a project-scoped MCP server configuration for the Sentry MCP. + * Supports Cursor, VS Code, and Claude Code. + * @param orgSlug - Optional organization slug to include in the MCP URL + * @param projectSlug - Optional project slug to include in the MCP URL + */ +export async function offerProjectScopedMcpConfig( + orgSlug?: string, + projectSlug?: string, +): Promise { + type InitialChoice = "yes" | "no" | "explain"; + + const initialChoice: InitialChoice = await abortIfCancelled( + clack.select({ + message: + "Optionally add a project-scoped MCP server configuration for the Sentry MCP?", + options: [ + { label: "Yes", value: "yes" }, + { label: "No", value: "no", hint: "You can add it later anytime" }, + { + label: "What is MCP?", + value: "explain", + hint: "Learn about MCP benefits", + }, + ], + initialValue: "yes", + }), + ); + + let shouldAdd: boolean; + + if (initialChoice === "explain") { + Sentry.setTag("mcp-choice", "explain"); + shouldAdd = await explainMCP(); + Sentry.setTag("mcp-configured-after-explain", shouldAdd); + } else { + shouldAdd = initialChoice === "yes"; + Sentry.setTag("mcp-choice", initialChoice); + } + + if (!shouldAdd) { + Sentry.setTag("mcp-configured", false); + return; + } + + Sentry.setTag("mcp-configured", true); + + type EditorChoice = + | "cursor" + | "vscode" + | "claudeCode" + | "openCode" + | "jetbrains" + | "other"; + const editors: EditorChoice[] = await abortIfCancelled( + clack.multiselect({ + message: "Which editor(s) do you want to configure?", + options: [ + { value: "cursor", label: "Cursor (project .cursor/mcp.json)" }, + { value: "vscode", label: "VS Code (project .vscode/mcp.json)" }, + { value: "claudeCode", label: "Claude Code (project .mcp.json)" }, + { value: "openCode", label: "OpenCode (project opencode.json)" }, + { + value: "jetbrains", + label: "JetBrains IDE (WebStorm, IntelliJ IDEA, PyCharm, etc.)", + hint: "Manual configuration required", + }, + { + value: "other", + label: "I use a different IDE", + hint: "We'll show you the configuration to copy", + }, + ], + required: false, + }), + ); + + // If no editors were selected, return early + if (editors.length === 0) { + clack.log.info("No editors selected. You can add MCP configuration later."); + Sentry.setTag("mcp-configured", false); + return; + } + + // Track number of editors selected + Sentry.setTag("mcp-editors-count", editors.length); + + // Configure each selected editor + for (const editor of editors) { + // Track which editor is being configured + Sentry.setTag("mcp-editor", editor); + + try { + switch (editor) { + case "cursor": + await addCursorMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "vscode": + await addVsCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "claudeCode": + await addClaudeCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to reload your editor for MCP changes to take effect.", + ), + ); + break; + case "openCode": + await addOpenCodeMcpConfig(orgSlug, projectSlug); + clack.log.success( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + clack.log.info( + chalk.dim( + "Note: You may need to restart OpenCode for MCP changes to take effect.", + ), + ); + break; + case "jetbrains": + await showJetBrainsMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + case "other": + await showGenericMcpConfig(orgSlug, projectSlug); + Sentry.setTag("mcp-config-manual", true); + break; + } + Sentry.setTag(`mcp-config-${editor}-success`, true); + } catch (e) { + Sentry.setTag(`mcp-config-${editor}-success`, false); + Sentry.setTag("mcp-config-fallback", true); + clack.log.warn( + chalk.yellow( + `Failed to write MCP config for ${editor} automatically. Please copy/paste the snippet below into your project config file.`, + ), + ); + + // Fallback: show per-editor instructions + if (editor === "cursor") { + await showCopyPasteInstructions({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: getCursorMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "vscode") { + await showCopyPasteInstructions({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: getVsCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "claudeCode") { + await showCopyPasteInstructions({ + filename: ".mcp.json", + codeSnippet: getClaudeCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } else if (editor === "openCode") { + await showCopyPasteInstructions({ + filename: "opencode.json", + codeSnippet: getOpenCodeMcpJsonSnippet(orgSlug, projectSlug), + hint: "create the file if it does not exist", + }); + } + } + } +} diff --git a/packages/cli/src/lib/wizard/utils/clack/prompts.ts b/packages/cli/src/lib/wizard/utils/clack/prompts.ts new file mode 100644 index 0000000000..3e969a1c52 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/clack/prompts.ts @@ -0,0 +1,71 @@ +/** + * The `@clack/prompts` functions the setup wizards use, gathered on one + * object so the ported flows keep their `clack.log.info(…)` call sites. + * + * The wizards run only under `sentry wizard`, whose chunk loads on demand, so + * importing clack here does not reach other commands or the completion bundle. + * + * `rawOutput` prints text the user copies as-is (code snippets, tokens): + * outside clack's gutter, so nothing gets prefixed to the copied lines. + * + * Each member is a getter, so a test that mocks `@clack/prompts` with only + * the functions its code path calls (as the sentry-wizard tests do) still + * loads this module. + */ + +import { + cancel, + confirm, + intro, + isCancel, + log, + multiselect, + note, + outro, + select, + spinner, + text, +} from "@clack/prompts"; + +/** Print `value` to stdout on its own lines, outside clack's gutter. */ +function rawOutput(value: string): void { + process.stdout.write(`${value}\n`); +} + +/** The clack prompts and log helpers the wizards call. */ +export const clack = { + get cancel() { + return cancel; + }, + get confirm() { + return confirm; + }, + get intro() { + return intro; + }, + get isCancel() { + return isCancel; + }, + get log() { + return log; + }, + get multiselect() { + return multiselect; + }, + get note() { + return note; + }, + get outro() { + return outro; + }, + rawOutput, + get select() { + return select; + }, + get spinner() { + return spinner; + }, + get text() { + return text; + }, +}; diff --git a/packages/cli/src/lib/wizard/utils/data-collection.ts b/packages/cli/src/lib/wizard/utils/data-collection.ts new file mode 100644 index 0000000000..8c157c1cf7 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/data-collection.ts @@ -0,0 +1,122 @@ +/** + * Ask whether the SDK should collect less personal data, for the + * `dataCollection` option the wizards write into `Sentry.init()`. + */ + +import { clack } from "./clack/prompts.js"; +import { Sentry } from "../telemetry.js"; +import chalk from "chalk"; + +import { traceStep } from "../telemetry.js"; +import { abortIfCancelled } from "./clack/index.js"; +import { getMajorVersion } from "./semver.js"; + +export const DATA_COLLECTION_DOCS_URL = + "https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection"; + +/** + * Keys that commonly reveal user identity in HTTP headers, cookies, and URL + * query parameters (forwarding chains, IP addresses, user hints). + */ +const PII_KEY_DENYLIST = ["forwarded", "-ip", "remote-", "via", "-user"]; + +const PII_KEY_DENYLIST_SNIPPET = `[${PII_KEY_DENYLIST.map( + (key) => `"${key}"`, +).join(", ")}]`; + +/** + * `dataCollection` value the wizard writes when the user opts to reduce data + * collection. Kept as an object so magicast-based wizards can insert it as an + * AST node; `getDataCollectionSnippet` renders the same preset for + * template-string-based wizards. + */ +export const DATA_COLLECTION_PII_PRESET = { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: [...PII_KEY_DENYLIST] }, + cookies: { deny: [...PII_KEY_DENYLIST] }, + urlQueryParams: { deny: [...PII_KEY_DENYLIST] }, +}; + +export const DATA_COLLECTION_COMMENT_LINES = [ + "Turns off collection of data that could identify users. Adjust per category:", + DATA_COLLECTION_DOCS_URL, +]; + +/** + * Renders the PII preset (with its explanatory comment) as code to embed in a + * generated `Sentry.init` options object. Every line is prefixed with + * `indent`; the result ends without a trailing newline. + */ +export function getDataCollectionSnippet(indent = " "): string { + const lines = [ + ...DATA_COLLECTION_COMMENT_LINES.map((line) => `// ${line}`), + "dataCollection: {", + " userInfo: false,", + " graphQL: { document: false, variables: false },", + " genAI: { inputs: false, outputs: false },", + " databaseQueryData: false,", + " queues: false,", + " httpBodies: [],", + ` httpHeaders: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` cookies: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + ` urlQueryParams: { deny: ${PII_KEY_DENYLIST_SNIPPET} },`, + "},", + ]; + + return lines.map((line) => `${indent}${line}`).join("\n"); +} + +/** + * The `dataCollection` option only makes sense to offer from SDK v11 on, + * where the SDK collects rich context by default. Unknown or unparseable + * installed versions fall back to the major of the range the wizard installs. + */ +export function sdkSupportsDataCollection( + installedSdkVersion: string | undefined, + wizardInstallRange: string, +): boolean { + const sdkMajor = + getMajorVersion(installedSdkVersion) ?? + getMajorVersion(wizardInstallRange) ?? + 0; + + return sdkMajor >= 11; +} + +/** + * Asks whether the wizard should write the PII-reducing `dataCollection` + * preset. Call this only when `sdkSupportsDataCollection` returned `true`. + */ +export async function askShouldReduceDataCollection(): Promise { + return await traceStep("data-collection", async () => { + const reduceDataCollection: boolean = await abortIfCancelled( + clack.select({ + message: + "Sentry collects request data, user info, and other context by default. Do you want to reduce this to avoid sending personally identifiable information (PII)?\n" + + `More info: ${chalk.cyan(DATA_COLLECTION_DOCS_URL)}`, + initialValue: false, + options: [ + { + value: true, + label: "Yes", + hint: "Add a dataCollection config to Sentry.init() that turns off PII-heavy categories", + }, + { + value: false, + label: "No", + hint: "Keep the SDK defaults", + }, + ], + }), + ); + + Sentry.setTag("data-collection-reduced", reduceDataCollection); + + return reduceDataCollection; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts new file mode 100644 index 0000000000..c8668c78ce --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -0,0 +1,32 @@ +/** + * Debug output of the setup wizards, shown with `sentry wizard --debug`. + */ + +import chalk from "chalk"; +import { clack } from "./clack/prompts.js"; + +let debugEnabled = false; + +/** Render one debug argument: strings as-is, errors with their stack. */ +function prepareMessage(msg: unknown): string { + if (typeof msg === "string") { + return msg; + } + if (msg instanceof Error) { + return msg.stack ?? msg.message; + } + return JSON.stringify(msg, null, "\t"); +} + +/** Log `args` in the wizard's output when `--debug` is on. */ +export function debug(...args: unknown[]): void { + if (!debugEnabled) { + return; + } + clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); +} + +/** Turn on {@link debug} output for the rest of the run. */ +export function enableDebugLogs(): void { + debugEnabled = true; +} diff --git a/packages/cli/src/lib/wizard/utils/git.ts b/packages/cli/src/lib/wizard/utils/git.ts new file mode 100644 index 0000000000..193d67460d --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/git.ts @@ -0,0 +1,75 @@ +/** + * Git checks the wizards run before they change a project's files. + */ + +import { execSync } from "node:child_process"; +import { debug } from "./debug.js"; + +/** + * Checks if the current working directory is a git repository. + * + * @param opts.cwd The directory of the project. If undefined, the current process working directory will be used. + * + * @returns true if the current working directory is a git repository, false otherwise. + */ +export function isInGitRepo(opts: { cwd: string | undefined }) { + try { + execSync("git rev-parse --is-inside-work-tree", { + stdio: "ignore", + cwd: opts.cwd, + }); + return true; + } catch (error) { + debug(error); + return false; + } +} + +/** + * Returns the exact paths of uncommitted or untracked files. + * + * Uses `git status --porcelain=v1 -z` so paths are NUL-terminated and verbatim, + * preserving spaces and unusual characters. Pass results as argv entries to a + * non-shell child process; do not interpolate them into a shell string. + * + * @param opts.cwd The project directory. Defaults to the current working directory. + */ +export function getUncommittedOrUntrackedFilePaths(opts?: { + cwd: string | undefined; +}): string[] { + try { + const gitStatus = execSync("git status --porcelain=v1 -z", { + // we only care about stdout + stdio: ["ignore", "pipe", "ignore"], + cwd: opts?.cwd, + }).toString(); + + const fields = gitStatus.split("\0"); + const files: string[] = []; + + for (let i = 0; i < fields.length; i++) { + const entry = fields[i]; + if (!entry) { + continue; + } + + // Entry is `XY `. Renames/copies (R/C) store the source in the + // next field, which we skip. + const status = entry.slice(0, 2); + const filePath = entry.slice(3); + + if (status[0] === "R" || status[0] === "C") { + i++; + } + + if (filePath) { + files.push(filePath); + } + } + + return files; + } catch (error) { + debug(error); + return []; + } +} diff --git a/packages/cli/src/lib/wizard/utils/node-version.ts b/packages/cli/src/lib/wizard/utils/node-version.ts new file mode 100644 index 0000000000..723b7d17fe --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/node-version.ts @@ -0,0 +1,50 @@ +/** + * Check the Node.js version a framework's SDK needs. + */ + +import { clack } from "./clack/prompts.js"; +import chalk from "chalk"; +import { coerce, satisfies } from "semver"; + +/** + * Node.js versions supported by version 11 of the Sentry JavaScript SDKs. + * See https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/#nodejs + */ +export const NODE_VERSION_RANGE_FOR_SDK_V11 = + ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0"; + +/** + * Returns `false` when the given Node.js version is definitely not supported by + * SDK v11. Unparseable versions are treated as supported. + */ +export function isNodeVersionSupportedBySdkV11( + version: string = process.version, +): boolean { + const parsed = coerce(version); + if (!parsed) { + return true; + } + return satisfies(parsed, NODE_VERSION_RANGE_FOR_SDK_V11); +} + +/** + * Warns when the wizard runs on a Node.js version that SDK v11 does not + * support. The wizard continues either way: the project may be built and run + * on a different Node.js than the one the wizard runs on. + */ +export function warnIfNodeVersionUnsupportedBySdkV11( + version: string = process.version, +): void { + if (isNodeVersionSupportedBySdkV11(version)) { + return; + } + + clack.log.warn( + `${chalk.yellow( + `Version 11 of the Sentry JavaScript SDKs requires Node.js 20.19.0 or newer (22.12.0 on Node.js 22, 23.2.0 on Node.js 23), but this wizard is running on Node.js ${chalk.bold( + version, + )}.`, + )} +The wizard will continue. Make sure your project builds and runs on a supported Node.js version before moving to SDK v11.`, + ); +} diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts new file mode 100644 index 0000000000..1de6728d35 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -0,0 +1,186 @@ +/** + * Read dependencies from a project's `package.json`, including versions + * pnpm resolves from a `pnpm-workspace.yaml` catalog. + */ + +import { clack } from "./clack/prompts.js"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +export type PackageDotJson = { + version?: string | undefined; + scripts?: Record; + dependencies?: Record | undefined; + devDependencies?: Record | undefined; + resolutions?: Record | undefined; + overrides?: Record | undefined; + pnpm?: { + overrides?: Record | undefined; + }; +}; + +type NpmPackage = { + name: string; + version: string; +}; + +type PnpmCatalogs = Record>; + +type PnpmWorkspace = { + catalog?: Record | undefined; + catalogs?: PnpmCatalogs | undefined; +}; + +/** Strip quotes and a trailing comment from a YAML scalar. */ +function yamlScalar(raw: string): string { + const value = raw.replace(/\s+#.*$/, "").trim(); + const quoted = /^(['"])(.*)\1$/.exec(value); + return quoted?.[2] ?? value; +} + +/** + * Read the `catalog` and `catalogs` sections of a `pnpm-workspace.yaml`. + * + * Only block mappings are read: `catalog:` with `name: version` entries, and + * `catalogs:` with a mapping of such catalogs. Everything else in the file is + * skipped, so the wizard needs no YAML parser. + */ +export function parsePnpmWorkspaceCatalogs(content: string): PnpmWorkspace { + const workspace: PnpmWorkspace = {}; + let section: "catalog" | "catalogs" | undefined; + let catalogName: string | undefined; + let namedIndent = -1; + + for (const line of content.split(/\r?\n/)) { + if (!line.trim() || line.trim().startsWith("#")) { + continue; + } + const indent = line.length - line.trimStart().length; + const entry = /^\s*(['"]?)([^'":]+)\1\s*:\s*(.*)$/.exec(line); + if (indent === 0) { + section = + entry?.[2] === "catalog" || entry?.[2] === "catalogs" + ? entry[2] + : undefined; + catalogName = undefined; + namedIndent = -1; + continue; + } + if (!(section && entry?.[2])) { + continue; + } + const key = entry[2].trim(); + const value = yamlScalar(entry[3] ?? ""); + if (section === "catalog") { + workspace.catalog = { ...workspace.catalog, [key]: value }; + } else if (namedIndent < 0 || indent <= namedIndent) { + namedIndent = indent; + catalogName = key; + } else if (catalogName) { + const catalogs = workspace.catalogs ?? {}; + catalogs[catalogName] = { ...catalogs[catalogName], [key]: value }; + workspace.catalogs = catalogs; + } + } + return workspace; +} + +/** + * Finds and parses the pnpm-workspace.yaml file to extract catalog definitions. + * Searches up to 10 parent directories from the current working directory. + * Returns null if the file doesn't exist or can't be parsed. + */ +function getPnpmWorkspace(): PnpmWorkspace | null { + let currentDir = process.cwd(); + const maxLevels = 10; + + for (let i = 0; i < maxLevels; i++) { + const workspaceFile = path.join(currentDir, "pnpm-workspace.yaml"); + + if (existsSync(workspaceFile)) { + const content = readFileSync(workspaceFile, "utf-8"); + + return parsePnpmWorkspaceCatalogs(content); + } + + const parentDir = path.dirname(currentDir); + + // Stop if we've reached the root directory + if (parentDir === currentDir) { + break; + } + + currentDir = parentDir; + } + + clack.log.error("Could not find pnpm-workspace.yaml."); + + return null; +} + +/** + * Resolves a catalog reference (e.g., "catalog:" or "catalog:sveltekit") to the actual version. + * - "catalog:" refers to the default catalog (workspace.catalog) + * - "catalog:customcatalog" refers to a named catalog (workspace.catalogs.customcatalog) + * Returns the actual version if found, or undefined if the catalog or package doesn't exist. + */ +function resolveCatalogVersion( + catalogRef: string, + packageName: string, +): string | undefined { + const catalogName = catalogRef.replace(/^catalog:/, ""); + const workspace = getPnpmWorkspace(); + + if (!workspace) { + return undefined; + } + + const catalog = + catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; + + return catalog?.[packageName]; +} + +/** + * Checks if @param packageJson has any of the @param packageNamesList package names + * listed as a dependency or devDependency. + * If so, it returns the first package name that is found, including the + * version (range) specified in the package.json. + */ +export function findInstalledPackageFromList( + packageNamesList: string[], + packageJson: PackageDotJson, +): NpmPackage | undefined { + return packageNamesList + .map((packageName) => ({ + name: packageName, + version: getPackageVersion(packageName, packageJson), + })) + .find((sdkPackage): sdkPackage is NpmPackage => !!sdkPackage.version); +} + +export function hasPackageInstalled( + packageName: string, + packageJson: PackageDotJson, +): boolean { + return getPackageVersion(packageName, packageJson) !== undefined; +} + +export function getPackageVersion( + packageName: string, + packageJson: PackageDotJson, +): string | undefined { + const rawVersion = + packageJson.dependencies?.[packageName] || + packageJson.devDependencies?.[packageName]; + + if (!rawVersion) { + return undefined; + } + + const version = rawVersion.startsWith("catalog:") + ? resolveCatalogVersion(rawVersion, packageName) + : rawVersion; + + return version; +} diff --git a/packages/cli/src/lib/wizard/utils/package-manager.ts b/packages/cli/src/lib/wizard/utils/package-manager.ts new file mode 100644 index 0000000000..a772f768f6 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/package-manager.ts @@ -0,0 +1,239 @@ +/** + * Detect the project's package manager and the commands it runs. + */ + +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { Sentry } from "../telemetry.js"; +import { traceStep } from "../telemetry.js"; +import { getPackageDotJson, updatePackageDotJson } from "./clack/index.js"; +import { debug } from "./debug.js"; + +export interface PackageManager { + name: string; + label: string; + installCommand: string; + buildCommand: string; + /* The command that the package manager uses to run a script from package.json */ + runScriptCommand: string; + flags: string; + forceInstallFlag: string; + registry?: string | undefined; + detect: () => boolean; + addOverride: (pkgName: string, pkgVersion: string) => Promise; +} + +export const BUN: PackageManager = { + name: "bun", + label: "Bun", + installCommand: "add", + buildCommand: "bun run build", + runScriptCommand: "bun run", + flags: "", + forceInstallFlag: "--force", + detect: () => + ["bun.lockb", "bun.lock"].some((lockFile) => { + try { + return existsSync(path.join(process.cwd(), lockFile)); + } catch (e) { + debug(e); + return false; + } + }), + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const DENO: PackageManager = { + name: "deno", + label: "Deno", + installCommand: "install", + buildCommand: "deno task build", + runScriptCommand: "deno task", + flags: "", + forceInstallFlag: "--force", + registry: "npm", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "deno.lock")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const YARN_V1: PackageManager = { + name: "yarn", + label: "Yarn V1", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("yarn lockfile v1"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +/** YARN V2/3/4 */ +export const YARN_V2: PackageManager = { + name: "yarn", + label: "Yarn V2/3/4", + installCommand: "add", + buildCommand: "yarn build", + runScriptCommand: "yarn", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return readFileSync(path.join(process.cwd(), "yarn.lock"), "utf-8") + .slice(0, 500) + .includes("__metadata"); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const resolutions = packageDotJson.resolutions || {}; + + await updatePackageDotJson({ + ...packageDotJson, + resolutions: { + ...resolutions, + [pkgName]: pkgVersion, + }, + }); + }, +}; +export const PNPM: PackageManager = { + name: "pnpm", + label: "PNPM", + installCommand: "add", + buildCommand: "pnpm build", + runScriptCommand: "pnpm", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "pnpm-lock.yaml")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const pnpm = packageDotJson.pnpm || {}; + const overrides = pnpm.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + pnpm: { + ...pnpm, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }, + }); + }, +}; +export const NPM: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: () => { + try { + return existsSync(path.join(process.cwd(), "package-lock.json")); + } catch (e) { + debug(e); + return false; + } + }, + addOverride: async (pkgName, pkgVersion): Promise => { + const packageDotJson = await getPackageDotJson(); + const overrides = packageDotJson.overrides || {}; + + await updatePackageDotJson({ + ...packageDotJson, + overrides: { + ...overrides, + [pkgName]: pkgVersion, + }, + }); + }, +}; + +export const packageManagers = [NPM, YARN_V1, YARN_V2, PNPM, BUN, DENO]; + +/** + * Exported only for testing. + * DO NOT call this function directly! + * Use `getPackageManger` instead. + */ +export function _detectPackageManger( + managers?: PackageManager[], +): PackageManager | null { + return traceStep("detect-package-manager", () => { + const foundPackageMangers = (managers ?? packageManagers).filter( + (packageManager) => packageManager.detect(), + ); + + // Only consider a package manager detected if we found exactly one. + // If we find more than one, we should not make any assumptions. + const [found] = foundPackageMangers; + if (found && foundPackageMangers.length === 1) { + Sentry.setTag("package-manager", found.name); + return found; + } + + Sentry.setTag("package-manager", "not-detected"); + return null; + }); +} diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts new file mode 100644 index 0000000000..87718dcbb9 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -0,0 +1,479 @@ +/** + * Pick the Sentry project a setup wizard configures, with the CLI's login. + * + * The old wizard opened `account/settings/wizard//` in a browser and + * polled for the projects and an auth token. This module uses what the rest + * of the CLI uses instead: + * + * - The stored `sentry auth login` account, or a new device-flow login (or an + * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks + * for `org:tokens` and `org:ci` too, so the auth token below needs no second + * approval. + * - The org from `--org`, the handoff, or a prompt; then the project from + * `--project` or a prompt that can also create one for the wizard's + * platform, like the old browser page could. + * - The project's DSN from its client keys. + * - A new org auth token for the build plugins and `sentry` commands that + * upload source maps and debug files. When the token can't be created, a + * placeholder goes in its place and the user is told where to make one. + */ + +import chalk from "chalk"; +import { completeAgentHandoff } from "../../agent-handoff.js"; +import { + getProject, + getProjectKeys, + listProjects, +} from "../../api/projects.js"; +import { createOrgAuthToken } from "../../api/org-auth-tokens.js"; +import { listOrganizations } from "../../api/organizations.js"; +import { + createProjectWithAutoTeam, + createProjectWithDsn, + MEMBER_PROJECT_CREATION_DISABLED_DETAIL, +} from "../../api/projects.js"; +import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; +import { DEFAULT_SENTRY_URL } from "../../constants.js"; +import { getAuthConfig } from "../../db/auth.js"; +import { getEnv } from "../../env.js"; +import { ApiError } from "../../errors.js"; +import { runInteractiveLogin } from "../../interactive-login.js"; +import { logger } from "../../logger.js"; +import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrCreateTeam } from "../../resolve-team.js"; +import { ensureScopesForAction } from "../../scope-recovery.js"; +import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; +import { registerLoginTrustAnchor } from "../../token-host.js"; +import { slugify } from "../../utils.js"; +import { sentry } from "../../app-identity.js"; +import type { + SentryOrganization, + SentryProject, +} from "../../../types/sentry.js"; +import { Sentry, traceStep } from "../telemetry.js"; +import { abort, abortIfCancelled } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; +import type { SentryProjectData, WizardOptions } from "./types.js"; + +const log = logger.withTag("wizard"); + +/** Written in place of an auth token that couldn't be created. */ +export const DUMMY_AUTH_TOKEN = "_YOUR_SENTRY_AUTH_TOKEN_"; + +/** Scopes an org auth token request needs from the CLI's OAuth grant. */ +const TOKEN_SCOPES = ["org:tokens", "org:read", "org:ci"] as const; + +/** `value` of the project picker's "create a new project" option. */ +const CREATE_PROJECT = Symbol("create-project"); + +/** Sentry platform identifiers of the wizards, used for new projects. */ +export type WizardPlatform = + | "javascript-angular" + | "javascript-nextjs" + | "javascript-nuxt" + | "javascript-react-router" + | "javascript-remix" + | "javascript-sveltekit" + | "node-cloudflare-workers" + | "apple-ios" + | "android" + | "react-native" + | "flutter"; + +/** The project a wizard sets up, or Spotlight mode, which needs none. */ +export type WizardProjectData = + | { + /** Web URL of the Sentry instance, ending in `/`. */ + sentryUrl: string; + selfHosted: boolean; + selectedProject: SentryProjectData; + /** Org auth token, or {@link DUMMY_AUTH_TOKEN}. */ + authToken: string; + spotlight: false; + } + | { + spotlight: true; + }; + +/** + * Get the Sentry project for a wizard run: the one passed in + * `options.preSelectedProject`, or one the user picks (or creates) after + * logging in. + * + * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param platform - Platform for a project the user creates + */ +export async function getOrAskForProjectData( + options: WizardOptions, + platform?: WizardPlatform, +): Promise { + if (options.spotlight) { + clack.log.info( + `Spotlight mode enabled! Setting up for local development without Sentry account needed.\n + Note: Your app will only send data to the local Spotlight debugger, not to Sentry.`, + ); + return { spotlight: true }; + } + + if (options.preSelectedProject) { + return { + selfHosted: options.preSelectedProject.selfHosted, + sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + authToken: options.preSelectedProject.authToken, + selectedProject: options.preSelectedProject.project, + spotlight: false, + }; + } + + await traceStep("ask-self-hosted", () => + selectSentryUrl(options.url, options.saas), + ); + const handoffOrg = await traceStep("login", ensureLoggedIn); + + const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + const selfHosted = !isSentrySaasUrl(sentryUrl); + Sentry.setTag("url", sentryUrl); + Sentry.setTag("self-hosted", selfHosted); + + const org = await traceStep("select-org", () => + selectOrganization(options.orgSlug ?? handoffOrg), + ); + const project = await traceStep("select-project", () => + selectProject(org, options.projectSlug, platform), + ); + Sentry.setTag("project", project.slug); + Sentry.setUser({ id: org.slug }); + + const dsn = await getDsn(org.slug, project.slug); + const authToken = await traceStep("create-auth-token", () => + createAuthToken(org.slug, sentryUrl), + ); + + return { + sentryUrl, + selfHosted, + authToken, + selectedProject: { + id: project.id, + slug: project.slug, + organization: { id: org.id, name: org.name, slug: org.slug }, + keys: [{ dsn: { public: dsn } }], + }, + spotlight: false, + }; +} + +/** + * Point this run at the Sentry instance the user chose: SaaS for `--saas`, + * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without + * any of them and with a stored login, the login's instance is used. + * + * An instance the user names here (flag or prompt) is trusted for login, the + * same as `sentry auth login --url`. + */ +async function selectSentryUrl( + urlFromArgs: string | undefined, + saas: boolean | undefined, +): Promise { + if (saas) { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + if (!urlFromArgs && getAuthConfig()) { + return; + } + + if (!urlFromArgs) { + const choice = await abortIfCancelled( + clack.select({ + message: "Are you using Sentry SaaS or self-hosted Sentry?", + options: [ + { value: "saas", label: "Sentry SaaS (sentry.io)" }, + { + value: "self-hosted", + label: "Self-hosted/on-premise/single-tenant", + }, + ], + }), + ); + if (choice === "saas") { + useSentryUrl(DEFAULT_SENTRY_URL); + return; + } + } + + let pending = urlFromArgs; + for (;;) { + const url = + pending || + (await abortIfCancelled( + clack.text({ + message: `Please enter the URL of your ${ + urlFromArgs ? "" : "self-hosted " + }Sentry instance.`, + placeholder: "https://sentry.io/", + }), + )); + pending = undefined; + const origin = parseOrigin(url); + if (origin) { + useSentryUrl(origin); + return; + } + clack.log.error( + `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, + ); + } +} + +/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ +function parseOrigin(url: string): string | undefined { + try { + const parsed = new URL(url); + return parsed.protocol === "https:" || parsed.protocol === "http:" + ? parsed.origin + : undefined; + } catch (error) { + log.debug(`Invalid Sentry URL ${url}`, error); + return; + } +} + +/** Send this run's API requests and login to `url`, trusted as user input. */ +function useSentryUrl(url: string): void { + const env = getEnv(); + env["SENTRY_HOST"] = url; + env["SENTRY_URL"] = url; + registerLoginTrustAnchor(url); +} + +/** + * Make sure the CLI has a login for the selected instance: claim the agent + * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. + * + * @returns The org slug of a claimed handoff + */ +async function ensureLoggedIn(): Promise { + const handoffCode = getEnv()["SENTRY_HANDOFF"]?.trim(); + if (handoffCode) { + const handoff = await completeAgentHandoff(handoffCode); + Sentry.setTag("login-method", "handoff"); + return handoff.organizationSlug; + } + + if (getAuthConfig()) { + Sentry.setTag("login-method", "stored"); + return; + } + + assertAutoLoginHostTrusted(); + clack.log.info( + `${chalk.bold("Log in to Sentry")} to pick the project to set up. No account yet? You can sign up on the page that opens.`, + ); + const login = await runInteractiveLogin({ + scope: resolveOAuthScopeString({ + scopes: [...OAUTH_SCOPES, ...TOKEN_SCOPES], + }), + }); + if (!login) { + Sentry.setTag("login-method", "failed"); + return await abort( + `Please restart the wizard and log in to complete the setup. You can also log in first with ${chalk.cyan(sentry`auth login`)}.`, + ); + } + Sentry.setTag("login-method", "device-flow"); + return; +} + +/** + * The organization to set up: `slug` when given, the only one the user + * belongs to, or the one they pick. + */ +async function selectOrganization( + slug: string | undefined, +): Promise>> { + const orgs = await listOrganizations(); + if (slug) { + const match = orgs.find((org) => org.slug === slug); + if (match) { + clack.log.step(`Selected organization ${chalk.cyan(match.slug)}`); + return match; + } + clack.log.warn( + `Could not find an organization with the slug ${chalk.cyan(slug)}.`, + ); + } + + const [only] = orgs; + if (orgs.length === 1 && only) { + clack.log.step(`Selected organization ${chalk.cyan(only.slug)}`); + return only; + } + if (!only) { + Sentry.setTag("no-orgs-found", true); + return await abort( + "Your Sentry account has no organizations. Create one in Sentry and run the wizard again.", + ); + } + + return await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry organization.", + options: [...orgs] + .sort((a, b) => a.slug.localeCompare(b.slug)) + .map((org) => ({ value: org, label: org.slug, hint: org.name })), + }), + ); +} + +/** + * The project to set up: `slug` when given and found, else the one the user + * picks from the org's projects or creates. + */ +async function selectProject( + org: { slug: string }, + slug: string | undefined, + platform: WizardPlatform | undefined, +): Promise { + if (slug) { + try { + const project = await getProject(org.slug, slug); + clack.log.step( + `Selected project ${chalk.cyan(`${org.slug}/${project.slug}`)}`, + ); + return project; + } catch (error) { + if (!(error instanceof ApiError && error.status === 404)) { + throw error; + } + clack.log.warn("Could not find a project with the provided slugs."); + } + } + + const projects = (await listProjects(org.slug)).sort((a, b) => + a.slug.localeCompare(b.slug), + ); + const selection = await abortIfCancelled( + clack.select({ + maxItems: 12, + message: "Select your Sentry project.", + options: [ + { value: CREATE_PROJECT, label: "Create a new project" }, + ...projects.map((project) => ({ + value: project, + label: `${org.slug}/${project.slug}`, + ...(project.platform ? { hint: project.platform } : {}), + })), + ], + ...(projects.length > 0 ? { initialValue: projects[0] } : {}), + }), + ); + if (typeof selection !== "symbol") { + return selection; + } + Sentry.setTag("created-project", true); + return await createProject(org.slug, platform); +} + +/** + * Ask for a name and create a project for `platform` in `orgSlug`, on the + * team the CLI's `project create` would pick. Members who can't use that + * team get a project on their personal team. + */ +async function createProject( + orgSlug: string, + platform: WizardPlatform | undefined, +): Promise { + const name = await abortIfCancelled( + clack.text({ + message: "What should the new project be called?", + initialValue: slugify(process.cwd().split(/[\\/]/).pop() ?? ""), + validate: (value) => + value.trim() ? undefined : "Please enter a project name.", + }), + ); + const body = { name: name.trim(), ...(platform ? { platform } : {}) }; + + const spinner = clack.spinner(); + spinner.start("Creating your Sentry project"); + try { + const team = await resolveOrCreateTeam(orgSlug, { + usageHint: sentry`wizard --org `, + autoCreateSlug: slugify(body.name), + }); + const { project } = await createProjectWithDsn(orgSlug, team.slug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } catch (error) { + if ( + !(error instanceof ApiError && error.status === 403) || + error.detail?.includes(MEMBER_PROJECT_CREATION_DISABLED_DETAIL) + ) { + spinner.stop("Could not create the project."); + throw error; + } + log.debug("403 on the team-based flow, using the org-scoped endpoint"); + const { project } = await createProjectWithAutoTeam(orgSlug, body); + spinner.stop(`Created project ${chalk.cyan(`${orgSlug}/${project.slug}`)}`); + return project; + } +} + +/** The public DSN of the project's first active client key. */ +async function getDsn(orgSlug: string, projectSlug: string): Promise { + const keys = await getProjectKeys(orgSlug, projectSlug); + const key = keys.find((k) => k.isActive) ?? keys[0]; + if (!key) { + return await abort( + `The project ${orgSlug}/${projectSlug} has no client keys (DSNs). Create one in its settings and run the wizard again.`, + ); + } + return key.dsn.public; +} + +/** + * Create an org auth token for uploading source maps and debug files, or + * return {@link DUMMY_AUTH_TOKEN} with instructions when that isn't possible + * (an old login without `org:tokens` in a non-interactive run, no permission, + * or a server that can't create tokens). + */ +async function createAuthToken( + orgSlug: string, + sentryUrl: string, +): Promise { + try { + const elevation = await ensureScopesForAction( + TOKEN_SCOPES, + "Creating an auth token for uploading source maps", + runInteractiveLogin, + ); + if (elevation !== "declined" && elevation !== "unavailable") { + const token = await createOrgAuthToken( + orgSlug, + `Sentry Wizard ${new Date().toISOString().slice(0, 10)}`, + ); + if (token.token) { + return token.token; + } + } + } catch (error) { + log.debug("Could not create an org auth token", error); + } + + Sentry.setTag("auth-token-created", false); + const settingsUrl = isSentrySaasUrl(sentryUrl) + ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` + : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + clack.log.warn( + `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( + `"${DUMMY_AUTH_TOKEN}"`, + )}) for you to replace later.\nCreate your auth token here:\n${chalk.cyan(settingsUrl)}`, + ); + return DUMMY_AUTH_TOKEN; +} + +/** `url` with exactly one trailing `/`, the form the wizards expect. */ +function withTrailingSlash(url: string): string { + return url.endsWith("/") ? url : `${url}/`; +} diff --git a/packages/cli/src/lib/wizard/utils/semver.ts b/packages/cli/src/lib/wizard/utils/semver.ts new file mode 100644 index 0000000000..da0fe41424 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/semver.ts @@ -0,0 +1,65 @@ +/** + * Version range checks for installed SDK and framework versions. + */ + +import { + major, + minVersion, + satisfies, + subset, + valid, + validRange, +} from "semver"; +import { debug } from "./debug.js"; + +/** + * Returns the major version of an exact version or the lowest version that a + * range permits (e.g. `^10` -> 10, `~11.2.0` -> 11). Returns `undefined` for + * missing or unparseable input. + */ +export function getMajorVersion( + version: string | undefined, +): number | undefined { + if (!version) { + return undefined; + } + try { + const minVer = minVersion(version); + return minVer ? major(minVer) : undefined; + } catch (error) { + debug(error); + return undefined; + } +} + +export function fulfillsVersionRange({ + version, + acceptableVersions, + canBeLatest, +}: { + version: string; + acceptableVersions: string; + canBeLatest: boolean; +}): boolean { + if (version === "latest") { + return canBeLatest; + } + + let cleanedUserVersion, isRange; + + if (valid(version)) { + cleanedUserVersion = valid(version); + isRange = false; + } else if (validRange(version)) { + cleanedUserVersion = validRange(version); + isRange = true; + } + + return ( + // If the given version is a bogus format, this will still be undefined and we'll automatically reject it + !!cleanedUserVersion && + (isRange + ? subset(cleanedUserVersion, acceptableVersions) + : satisfies(cleanedUserVersion, acceptableVersions)) + ); +} diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts new file mode 100644 index 0000000000..b7b267c44e --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -0,0 +1,104 @@ +/** + * Types shared by the setup wizards: the options `sentry wizard` passes to a + * flow, the Sentry project a flow sets up, and feature prompts. + */ + +export interface SentryProjectData { + id: string; + slug: string; + organization: { + id: string; + name: string; + slug: string; + }; + keys: [{ dsn: { public: string } }]; +} + +export type PreselectedProject = { + project: SentryProjectData; + authToken: string; + selfHosted: boolean; +}; + +export type WizardOptions = { + /** + * Controls whether the wizard should send telemetry data to Sentry. + */ + telemetryEnabled: boolean; + + /** + * The promo code to use while signing up for Sentry. + * This can be passed via the --promo-code arg. + */ + promoCode?: string | undefined; + + /** + * The url of the Sentry instance to use. + * This can be passed via the `-u` or `--url` arg. + */ + url?: string | undefined; + + /** + * The org to pre-select in the wizard. + * This can be passed via the `--org` arg. + * Example: `--org my-org` + */ + orgSlug?: string | undefined; + + /** + * Project slug to pre-select in the wizard. + * This can be passed via the `--project` arg. + * Example: `--project my-project` + */ + projectSlug?: string | undefined; + + /** + * If this option is set, the wizard will skip the self-hosted or SaaS + * selection step and directly assume that the wizard is used for Sentry SaaS. + */ + saas?: boolean | undefined; + + /** + * If this is set, the wizard will skip the login and project selection step. + */ + preSelectedProject?: PreselectedProject | undefined; + + /** + * Force-install the SDK package to continue with the installation in case + * any package manager checks are failing (e.g. peer dependency versions). + * + * Use with caution and only if you know what you're doing. + * + * Does not apply to all wizard flows (currently NPM only) + */ + forceInstall?: boolean | undefined; + + /** + * Used when the wizard command is copied from partner sites (e.g. Vercel) + * to display login/signup instructions specific to organizations provisioned + * through the partner. + */ + comingFrom?: string | undefined; + + /** + * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + */ + ignoreGitChanges?: boolean | undefined; + + /** + * Enable Spotlight mode for local development without Sentry authentication. + * When enabled: + * - Skips login and project selection + * - Uses empty DSN + * - Skips auth token file creation + * This can be passed via the `--spotlight` arg. + */ + spotlight?: boolean | undefined; +}; + +export interface Feature { + id: string; + prompt: string; + enabledHint?: string | undefined; + disabledHint?: string | undefined; +} diff --git a/packages/cli/src/top-level-briefs.ts b/packages/cli/src/top-level-briefs.ts index e111dd8149..9a4808be84 100644 --- a/packages/cli/src/top-level-briefs.ts +++ b/packages/cli/src/top-level-briefs.ts @@ -52,6 +52,7 @@ export const TOP_LEVEL_BRIEFS = { trace: "View distributed traces", trial: "Manage product trials", init: "Print instructions for a coding agent to set up Sentry", + wizard: "Set up the Sentry SDK in your project interactively", info: "Print configuration and verify authentication", local: "Sentry for local development", api: "Make an authenticated API request", diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts new file mode 100644 index 0000000000..f320f998b9 --- /dev/null +++ b/packages/cli/test/commands/wizard.test.ts @@ -0,0 +1,131 @@ +/** + * Tests for `sentry wizard`: integration selection, the flags it passes to a + * wizard flow, and how a stopped wizard sets the exit code. + */ + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const { runNextjsWizard } = vi.hoisted(() => ({ + runNextjsWizard: vi.fn<(options: unknown) => Promise>(), +})); +vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ + runNextjsWizard, +})); + +import { wizardCommand } from "../../src/commands/wizard.js"; +import type { SentryContext } from "../../src/context.js"; +import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; +import type { Writer } from "../../src/types/index.js"; +import { loadCommand, useTestConfigDir } from "../helpers.js"; + +useTestConfigDir("wizard-test-"); + +const DEFAULT_FLAGS = { + saas: false, + debug: false, + spotlight: false, + "disable-telemetry": false, + "force-install": false, + "ignore-git-changes": false, + signup: false, + "skip-connect": false, + quiet: false, + uninstall: false, +}; + +async function runWizardCommand( + flags: Record = {}, +): Promise { + const context = { + process, + env: process.env, + stdout: { write: vi.fn(() => true) }, + stderr: { write: vi.fn(() => true) }, + stdin: process.stdin, + cwd: "/tmp", + homeDir: "/tmp", + configDir: "/tmp", + } as unknown as SentryContext; + const func = await loadCommand(wizardCommand); + await func.call(context, { ...DEFAULT_FLAGS, ...flags }); +} + +beforeEach(() => { + runNextjsWizard.mockReset(); + runNextjsWizard.mockResolvedValue(undefined); + process.exitCode = undefined; +}); + +afterEach(() => { + vi.unstubAllEnvs(); + process.exitCode = undefined; +}); + +describe("sentry wizard", () => { + test("runs the -i integration with the @sentry/wizard flags", async () => { + await runWizardCommand({ + integration: "nextjs", + org: "acme", + project: "web", + url: "https://sentry.example.com", + spotlight: true, + "force-install": true, + "ignore-git-changes": true, + "disable-telemetry": true, + "coming-from": "vercel", + }); + + expect(runNextjsWizard).toHaveBeenCalledWith({ + telemetryEnabled: false, + promoCode: undefined, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + saas: false, + forceInstall: true, + comingFrom: "vercel", + ignoreGitChanges: true, + spotlight: true, + }); + }); + + test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); + vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + + await runWizardCommand(); + + expect(runNextjsWizard).toHaveBeenCalledWith( + expect.objectContaining({ url: "https://self-hosted.example.com" }), + ); + }); + + test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { + vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + + await expect(runWizardCommand()).rejects.toThrow(ValidationError); + expect(runNextjsWizard).not.toHaveBeenCalled(); + }); + + test("reports an integration this version can't set up yet", async () => { + await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + "The remix wizard is not available in this version yet.", + ); + }); + + test("exits with the wizard's code when it stops", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(0)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(0); + }); + + test("exits with code 1 when the wizard can't continue", async () => { + runNextjsWizard.mockRejectedValue(new WizardExitError(1)); + + await runWizardCommand({ integration: "nextjs" }); + + expect(process.exitCode).toBe(1); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/templates.test.ts b/packages/cli/test/lib/wizard/nextjs/templates.test.ts new file mode 100644 index 0000000000..243b50328c --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/templates.test.ts @@ -0,0 +1,963 @@ +import { describe, expect, it } from "vitest"; +import { + getNextjsConfigCjsAppendix, + getNextjsConfigCjsTemplate, + getNextjsConfigEsmCopyPasteSnippet, + getNextjsConfigMjsTemplate, + getRootLayout, + getSentryServersideConfigContents, + getInstrumentationClientFileContents, + getWithSentryConfigOptionsTemplate, + getGenerateMetadataSnippet, + getRootLayoutWithGenerateMetadata, + getSentryExamplePageContents, + getSentryExamplePagesDirApiRoute, + getSentryExampleAppDirApiRoute, +} from "../../../../src/lib/wizard/nextjs/templates.js"; + +describe("Next.js code templates", () => { + describe("getInstrumentationClientFileContents", () => { + it("generates client-side Sentry config with all features enabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + // Define how likely Replay events are sampled. + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with performance monitoring disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Add optional integrations for additional features + integrations: [Sentry.replayIntegration()], + + // Define how likely Replay events are sampled. + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // Define how likely Replay events are sampled when an error occurs. + replaysOnErrorSampleRate: 1.0, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + + it("generates client-side Sentry config with session replay disabled", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the client. + // The added config here will be used whenever a users loads a page in their browser. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + + export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; + " + `); + }); + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getInstrumentationClientFileContents( + "my-dsn", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getInstrumentationClientFileContents( + "", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("getSentryServersideConfigContents", () => { + describe("server-side", () => { + it("generates server-side Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates server-side Sentry config with spotlight disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry on the server. + // The config you add here will be used whenever the server handles a request. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "server", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + + it("uses empty DSN in spotlight mode", () => { + const template = getSentryServersideConfigContents( + "", + "server", + { + performance: true, + replay: false, + }, + false, + true, // spotlight + ); + + // Verify DSN is empty for spotlight + expect(template).toContain('dsn: ""'); + expect(template).toContain("spotlight: true"); + }); + }); + + describe("edge", () => { + it("generates edge Sentry config with all features enabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + // Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control. + tracesSampleRate: 1, + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("generates edge Sentry config with performance monitoring disabled", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on). + // The config you add here will be used whenever one of the edge features is loaded. + // Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally. + // https://docs.sentry.io/platforms/javascript/guides/nextjs/ + + import * as Sentry from "@sentry/nextjs"; + + Sentry.init({ + dsn: "my-dsn", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + }); + " + `); + }); + + it("writes the active dataCollection preset when reduceDataCollection is true", () => { + const template = getSentryServersideConfigContents( + "my-dsn", + "edge", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain("// userInfo: false,"); + expect(template).not.toContain( + "To disable sending user data and HTTP bodies", + ); + }); + }); + }); + + describe("getWithSentryConfigOptionsTemplate", () => { + it("generates options for SaaS", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("generates options for self-hosted", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: true, + sentryUrl: "https://my-sentry.com", + tunnelRoute: true, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + sentryUrl: "https://my-sentry.com", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + + it("comments out tunnelRoute if `tunnelRoute` option is disabled", () => { + const template = getWithSentryConfigOptionsTemplate({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: false, + sentryUrl: "https://dont-use-this-url.com", + tunnelRoute: false, + }); + + expect(template).toMatchInlineSnapshot(` + "{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "my-org", + project: "my-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + }, + }" + `); + }); + }); + + describe("getRootLayout", () => { + it("generates a root layout component with types", () => { + expect(getRootLayout(true)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + it("generates a root layout component without types", () => { + expect(getRootLayout(false)).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + // You can delete this file at any time. + + export const metadata = { + title: 'Sentry NextJS Example', + description: 'Generated by Sentry', + } + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getGenerateMetadataSnippet", () => { + it("generates metadata snippet with TypeScript types", () => { + const template = getGenerateMetadataSnippet(true); + + expect(template).toMatchInlineSnapshot(` +" + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata(): Metadata { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } +" +`); + }); + + it("generates metadata snippet without TypeScript types", () => { + const template = getGenerateMetadataSnippet(false); + + expect(template).toMatchInlineSnapshot(` + " + import * as Sentry from '@sentry/nextjs'; + + + // Add or edit your "generateMetadata" to include the Sentry trace data: + export function generateMetadata() { + return { + // ... your existing metadata + other: { + ...Sentry.getTraceData() + } + }; + } + " + `); + }); + }); + + describe("getRootLayoutWithGenerateMetadata", () => { + it("generates root layout with TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(true); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + import type { Metadata } from 'next'; + + export function generateMetadata(): Metadata { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + {children} + + ) + } + " + `); + }); + + it("generates root layout without TypeScript types", () => { + const template = getRootLayoutWithGenerateMetadata(false); + + expect(template).toMatchInlineSnapshot(` + "// This file was generated by the Sentry wizard because we couldn't find a root layout file. + import * as Sentry from '@sentry/nextjs'; + + + export function generateMetadata() { + return { + other: { + ...Sentry.getTraceData(), + } + } + }; + + export default function RootLayout({ + children, + }) { + return ( + + {children} + + ) + } + " + `); + }); + }); + + describe("getSentryExamplePageContents", () => { + it("generates example page with TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without TypeScript types", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: false, + }); + + expect(template).toContain('"use client";'); + expect(template).toContain("constructor(message)"); + expect(template).toContain( + "class SentryExampleFrontendError extends Error", + ); + }); + + it("generates example page without useClient directive", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: false, + isTypeScript: true, + }); + + expect(template).not.toContain('"use client";'); + expect(template).toContain( + "https://my-org.sentry.io/issues/?project=123", + ); + }); + + it("generates example page with logger calls", () => { + const template = getSentryExamplePageContents({ + selfHosted: false, + sentryUrl: "https://sentry.io", + orgSlug: "my-org", + projectId: "123", + useClient: true, + isTypeScript: true, + }); + + expect(template).toContain( + 'Sentry.logger.info("Sentry example page loaded")', + ); + expect(template).toContain( + 'Sentry.logger.info("User clicked the button, throwing a sample error")', + ); + }); + }); + + describe("getSentryExamplePagesDirApiRoute", () => { + it("generates Pages Router API route with TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route without TypeScript types", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: false, + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export default function handler(_req, res)"); + }); + + it("generates Pages Router API route with logger calls", () => { + const template = getSentryExamplePagesDirApiRoute({ + isTypeScript: true, + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("getSentryExampleAppDirApiRoute", () => { + it("generates App Router API route with TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message: string | undefined)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route without TypeScript types", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: false, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain("constructor(message)"); + expect(template).toContain("class SentryExampleAPIError extends Error"); + expect(template).toContain("export function GET()"); + expect(template).toContain('export const dynamic = "force-dynamic";'); + }); + + it("generates App Router API route with logger calls", () => { + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "force-dynamic", + }); + + expect(template).toContain('import * as Sentry from "@sentry/nextjs";'); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + + it("uses connection() instead of route segment config for the connection strategy", () => { + // Next.js 16 with `cacheComponents` rejects route segment config and + // prerenders route handlers unless they opt into request-time rendering. + const template = getSentryExampleAppDirApiRoute({ + isTypeScript: true, + dynamicStrategy: "connection", + }); + + expect(template).not.toContain("force-dynamic"); + expect(template).not.toContain("export const dynamic"); + expect(template).toContain('import { connection } from "next/server";'); + expect(template).toContain("export async function GET()"); + expect(template).toContain("await connection();"); + expect(template).toContain( + 'Sentry.logger.info("Sentry example API called")', + ); + }); + }); + + describe("next.config templates", () => { + const options = '{ org: "my-org", project: "my-project" }'; + + it("CJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsTemplate(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("MJS template imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigMjsTemplate(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(nextConfig, ${options});`, + ); + }); + + it("CJS appendix imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigCjsAppendix(options); + expect(template).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs/config");', + ); + expect(template).toContain( + `module.exports = withSentryConfig(module.exports, ${options});`, + ); + }); + + it("ESM copy-paste snippet imports withSentryConfig from @sentry/nextjs/config", () => { + const template = getNextjsConfigEsmCopyPasteSnippet(options); + expect(template).toContain( + 'import { withSentryConfig } from "@sentry/nextjs/config";', + ); + expect(template).toContain( + `export default withSentryConfig(yourNextConfig, ${options});`, + ); + }); + + it("uses the root export when an older SDK requires it", () => { + const cjs = getNextjsConfigCjsTemplate(options, "@sentry/nextjs"); + const mjs = getNextjsConfigMjsTemplate(options, "@sentry/nextjs"); + const appendix = getNextjsConfigCjsAppendix(options, "@sentry/nextjs"); + const snippet = getNextjsConfigEsmCopyPasteSnippet( + options, + "@sentry/nextjs", + ); + + expect(cjs).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(mjs).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + expect(appendix).toContain( + 'const { withSentryConfig } = require("@sentry/nextjs");', + ); + expect(snippet).toContain( + 'import { withSentryConfig } from "@sentry/nextjs";', + ); + for (const template of [cjs, mjs, appendix, snippet]) { + expect(template).not.toContain("@sentry/nextjs/config"); + } + }); + + it("never references the root @sentry/nextjs export for withSentryConfig by default", () => { + for (const template of [ + getNextjsConfigCjsTemplate(options), + getNextjsConfigMjsTemplate(options), + getNextjsConfigCjsAppendix(options), + getNextjsConfigEsmCopyPasteSnippet(options), + ]) { + expect(template).not.toMatch(/["']@sentry\/nextjs["']/); + } + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts new file mode 100644 index 0000000000..df026e57ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Mock } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +import { parseModule } from "magicast"; +import { + addWithSentryConfigImport, + getNextJsVersionBucket, + getMaybeAppDirLocation, + hasRootLayoutFile, + getExampleApiRouteDynamicStrategy, + getWithSentryConfigImportPath, + isNextJsVersionSupported, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: vi.fn(), + lstatSync: vi.fn(), +})); + +describe("Next.js Utils", () => { + describe("getNextJsVersionBucket", () => { + it('returns "none" for undefined version', () => { + expect(getNextJsVersionBucket(undefined)).toBe("none"); + }); + + it('returns "<11.0.0" for versions below 11', () => { + expect(getNextJsVersionBucket("10.0.0")).toBe("<11.0.0"); + }); + + it("returns major version for versions 11 and above", () => { + expect(getNextJsVersionBucket("11.0.0")).toBe("11.x"); + expect(getNextJsVersionBucket("11.2.5")).toBe("11.x"); + expect(getNextJsVersionBucket("13.5.2")).toBe("13.x"); + expect(getNextJsVersionBucket("14.0.0")).toBe("14.x"); + }); + }); + + describe("getMaybeAppDirLocation", () => { + const mockCwd = "/mock/cwd"; + let originalCwd: () => string; + + beforeEach(() => { + originalCwd = process.cwd; + process.cwd = vi.fn(() => mockCwd); + vi.clearAllMocks(); + }); + + afterEach(() => { + process.cwd = originalCwd; + }); + + it('returns ["app"] when app directory exists in root', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["app"]); + }); + + it('returns ["src", "app"] when app directory exists in src', () => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === "/mock/cwd/src/app"; + }); + (fs.lstatSync as Mock).mockImplementation((filePath: string) => ({ + isDirectory: () => filePath === "/mock/cwd/src/app", + })); + + expect(getMaybeAppDirLocation()).toEqual(["src", "app"]); + }); + + it("returns undefined when no app directory exists", () => { + (fs.existsSync as Mock).mockReturnValue(false); + + expect(getMaybeAppDirLocation()).toBeUndefined(); + }); + }); + + describe("hasRootLayoutFile", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("returns true when layout file exists with any supported extension", () => { + const mockAppFolderPath = "/mock/app"; + const supportedExtensions = ["jsx", "tsx", "js"]; + + supportedExtensions.forEach((ext) => { + (fs.existsSync as Mock).mockImplementation((filePath: string) => { + return filePath === `/mock/app/layout.${ext}`; + }); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); + }); + }); + + it("returns false when no layout file exists", () => { + const mockAppFolderPath = "/mock/app"; + (fs.existsSync as Mock).mockReturnValue(false); + + expect(hasRootLayoutFile(mockAppFolderPath)).toBe(false); + }); + }); + + describe("isNextJsVersionSupported", () => { + it.each(["14.0.0", "^14.2.0", "15.5.21", "~16.2.0", "17.0.0-canary.1"])( + "returns true for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + + it.each(["13.5.6", "^13.0.0", "12.3.4", "11.0.0"])( + "returns false for %s", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(false); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "returns true when the version is unknown (%s)", + (version) => { + expect(isNextJsVersionSupported(version)).toBe(true); + }, + ); + }); + + describe("getExampleApiRouteDynamicStrategy", () => { + it.each(["14.2.35", "^14.0.0", "13.5.6"])( + "returns force-dynamic for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + + it.each(["15.0.0", "^15.5.0", "16.2.11", "~16.0.0", "17.0.0-canary.1"])( + "returns connection for %s", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe("connection"); + }, + ); + + it.each([undefined, "latest", "not-a-version"])( + "falls back to force-dynamic when the version is unknown (%s)", + (version) => { + expect(getExampleApiRouteDynamicStrategy(version)).toBe( + "force-dynamic", + ); + }, + ); + }); + + describe("getWithSentryConfigImportPath", () => { + it.each(["10.73.0", "^10.73.0", "10.74.0", "^11.0.0", "11.0.0-beta.2"])( + "returns the /config subpath for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + + it.each(["10.72.0", "^10.0.0", "~10.50.0", "9.47.1", "8.55.2"])( + "falls back to the root export for %s", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe("@sentry/nextjs"); + }, + ); + + it.each([undefined, "latest", "not-a-version", "workspace:*"])( + "returns the /config subpath when the version is unknown (%s)", + (version) => { + expect(getWithSentryConfigImportPath(version)).toBe( + "@sentry/nextjs/config", + ); + }, + ); + }); + + describe("addWithSentryConfigImport", () => { + it("uses the given import path", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod, "@sentry/nextjs"); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs";', + ); + }); + + it("adds the import from @sentry/nextjs/config when none exists", () => { + const mod = parseModule("export default {};"); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code).toContain( + 'import {withSentryConfig} from "@sentry/nextjs/config";', + ); + }); + + it("rewrites an existing import from the root @sentry/nextjs export", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + const code = mod.generate().code; + expect(code.match(/withSentryConfig.*from/g)).toHaveLength(1); + expect(code).toContain('from "@sentry/nextjs/config"'); + expect(code).not.toContain('from "@sentry/nextjs"'); + }); + + it("leaves an existing import from @sentry/nextjs/config untouched", () => { + const mod = parseModule( + 'import { withSentryConfig } from "@sentry/nextjs/config";\nexport default withSentryConfig({});', + ); + + addWithSentryConfigImport(mod); + + expect(mod.generate().code.match(/withSentryConfig.*from/g)).toHaveLength( + 1, + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts new file mode 100644 index 0000000000..fd2a2c67ed --- /dev/null +++ b/packages/cli/test/lib/wizard/nextjs/wizard-double-wrap-prevention.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect, vi } from "vitest"; +import { generateCode, parseModule } from "magicast"; +import { getWithSentryConfigOptionsTemplate } from "../../../../src/lib/wizard/nextjs/templates.js"; +import { + unwrapSentryConfigAst, + wrapWithSentryConfig, +} from "../../../../src/lib/wizard/nextjs/utils.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Next.js wizard double wrap prevention", () => { + const mockWithSentryConfigOptionsTemplate = + getWithSentryConfigOptionsTemplate({ + orgSlug: "test-org", + projectSlug: "test-project", + selfHosted: false, + sentryUrl: "https://sentry.io", + tunnelRoute: false, + }); + + describe("unwrapSentryConfigAst utility function", () => { + describe("AST-based expression unwrapping", () => { + it("keeps code without withSentryConfig", () => { + const mod = parseModule("export default nextConfig"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + expect(resultAST).toBe(originalAST); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle plain object literal exports", () => { + const mod = parseModule( + `export default { nextConfig: { randomValue: true } }`, + ); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + expect(resultAST.type).toBe("ObjectExpression"); + expect(resultAST).toHaveProperty("properties.length", 1); + }); + + it("should unwrap withSentryConfig with options", () => { + const mod = parseModule( + 'export default withSentryConfig(nextConfig, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should unwrap withSentryConfig without options", () => { + const mod = parseModule("export default withSentryConfig(nextConfig)"); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle nested withSentryConfig calls", () => { + const mod = parseModule( + 'export default withSentryConfig(withSentryConfig(nextConfig, { org: "inner" }), { org: "outer" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + + // Should unwrap one level and return the inner withSentryConfig call + expect(resultAST.type).toBe("CallExpression"); + expect(resultAST).toHaveProperty("callee.name", "withSentryConfig"); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "inner" })"`, + ); + }); + + it("should handle complex expressions", () => { + const mod = parseModule( + "export default withSentryConfig(someComplexExpression.withMethods())", + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"someComplexExpression.withMethods()"`, + ); + }); + + it("should handle object literals", () => { + const mod = parseModule( + 'export default withSentryConfig({ next: "config", obj: { next: "nested" } }, { org: "test" })', + ); + const wrappedAst = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(wrappedAst); + const { code: exportDefaultCode } = generateCode({ $ast: resultAST }); + + expect(exportDefaultCode).toMatchInlineSnapshot( + `"{ next: "config", obj: { next: "nested" } }"`, + ); + }); + + it("should return unchanged if not a withSentryConfig call", () => { + const mod = parseModule("export default someOtherFunction(nextConfig)"); + const originalAST = mod.exports["default"].$ast; + const resultAST = unwrapSentryConfigAst(originalAST); + + expect(resultAST).toBe(originalAST); + }); + }); + }); + + describe("MJS/TS files", () => { + it("should unwrap existing withSentryConfig and re-wrap with new config using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig, { + org: "old-org", + project: "old-project", +});`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Create a fresh module to simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + + // Apply wrapping + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Verify only one withSentryConfig call exists + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).toContain("test-org"); + expect(newCode).toContain("test-project"); + expect(newCode).not.toContain("old-org"); + expect(newCode).not.toContain("old-project"); + }); + + it("should handle complex nested configurations using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = { experimental: { appDir: true } }; + +export default withSentryConfig( + withSentryConfig(nextConfig, { org: "nested-org" }), + { org: "outer-org" } +);`; + + const mod = parseModule(existingMjsContent); + + // First unwrap ---- + const firstUnwrapAST = unwrapSentryConfigAst(mod.exports["default"].$ast); + expect(firstUnwrapAST.type).toBe("CallExpression"); + expect(firstUnwrapAST).toHaveProperty("callee.name", "withSentryConfig"); + + const { code: exportDefaultCode1 } = generateCode({ + $ast: firstUnwrapAST, + }); + expect(exportDefaultCode1).toMatchInlineSnapshot( + `"withSentryConfig(nextConfig, { org: "nested-org" })"`, + ); + + // Second unwrap ---- + const secondUnwrapAST = unwrapSentryConfigAst(firstUnwrapAST); + expect(secondUnwrapAST.type).toBe("Identifier"); + expect(secondUnwrapAST).toHaveProperty("name", "nextConfig"); + + const { code: exportDefaultCode2 } = generateCode({ + $ast: secondUnwrapAST, + }); + + expect(exportDefaultCode2).toMatchInlineSnapshot(`"nextConfig"`); + }); + + it("should handle simple export without existing withSentryConfig using AST", () => { + const simpleMjsContent = `const nextConfig = {}; + +export default nextConfig;`; + + const mod = parseModule(simpleMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + expect(unwrappedAst).toBe(originalAST); + mod.exports["default"] = wrapWithSentryConfig( + mod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = mod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + // Not an inline snapshot: interpolating a shared constant defeats + // vitest's indentation detection for inline snapshots. + expect(newCode).toBe(`const nextConfig = {}; + +export default withSentryConfig(nextConfig, ${sentryOptionsSnapshot});`); + }); + + it("should handle withSentryConfig(nextConfig) without options using AST", () => { + const existingMjsContent = `import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default withSentryConfig(nextConfig);`; + + const mod = parseModule(existingMjsContent); + const originalAST = mod.exports["default"].$ast; + const unwrappedAst = unwrapSentryConfigAst(originalAST); + // Verify it returns the first argument (nextConfig identifier) + expect(unwrappedAst.type).toBe("Identifier"); + expect(unwrappedAst).toHaveProperty("name", "nextConfig"); + + // Simulate the re-wrapping process + const freshMod = + parseModule(`import { withSentryConfig } from "@sentry/nextjs"; + +const nextConfig = {}; + +export default nextConfig;`); + freshMod.exports["default"] = wrapWithSentryConfig( + freshMod.exports["default"], + mockWithSentryConfigOptionsTemplate, + ); + + const newCode = freshMod.generate().code; + + // Should have exactly one withSentryConfig call + const withSentryConfigMatches = newCode.match(/withSentryConfig\s*\(/g); + expect(withSentryConfigMatches).toHaveLength(1); + + expect(newCode).not.toContain("withSentryConfig(withSentryConfig("); + expect(newCode).toMatch(/withSentryConfig\s*\(\s*nextConfig\s*,/); + }); + }); +}); + +const sentryOptionsSnapshot = `{ + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/uploading/bundler-plugin-options/ + + org: "test-org", + + project: "test-project", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // For all available options, see: + // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/ + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Uncomment to route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client- + // side errors will fail. + // tunnelRoute: "/monitoring", + + webpack: { + // Enables automatic instrumentation of Vercel Cron Monitors. (Does not yet work with App Router route handlers.) + // See the following for more information: + // https://docs.sentry.io/product/crons/ + // https://vercel.com/docs/cron-jobs + automaticVercelMonitors: true, + + // Tree-shaking options for reducing bundle size + treeshake: { + // Automatically tree-shake Sentry logger statements to reduce bundle size + removeDebugLogging: true, + }, + } +}`; diff --git a/packages/cli/test/lib/wizard/utils/clack/index.test.ts b/packages/cli/test/lib/wizard/utils/clack/index.test.ts new file mode 100644 index 0000000000..cf8b7c62b8 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/index.test.ts @@ -0,0 +1,719 @@ +import { + abort, + askForToolConfigPath, + confirmContinueIfNoOrDirtyGitRepo, + createNewConfigFile, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, +} from "../../../../../src/lib/wizard/utils/clack/index.js"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as ChildProcess from "node:child_process"; +import type { PackageManager } from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as PackageManagerUtils from "../../../../../src/lib/wizard/utils/package-manager.js"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as GitUtils from "../../../../../src/lib/wizard/utils/git.js"; + +import { + NPM, + PNPM, + YARN_V1, + YARN_V2, +} from "../../../../../src/lib/wizard/utils/package-manager.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as clack from "@clack/prompts"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as Sentry from "@sentry/node"; + +import { + vi, + it, + describe, + expect, + beforeEach, + type Mocked, + type Mock, + type MockInstance, + afterEach, +} from "vitest"; + +vi.mock("node:child_process", async () => ({ + __esModule: true, + ...(await vi.importActual("node:child_process")), +})); + +vi.mock("node:fs", async () => ({ + __esModule: true, + ...(await vi.importActual("node:fs")), +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, + outro: vi.fn(), + text: vi.fn(), + confirm: vi.fn(), + cancel: vi.fn(), + // passthrough for abortIfCancelled + isCancel: vi.fn().mockReturnValue(false), + spinner: vi + .fn() + .mockImplementation(() => ({ start: vi.fn(), stop: vi.fn() })), + select: vi.fn(), +})); +const clackMock = clack as Mocked; + +vi.mock("../../../../../src/lib/wizard/utils/git.js", () => ({ + isInGitRepo: vi.fn(), + getUncommittedOrUntrackedFilePaths: vi.fn(), +})); + +vi.mock("@sentry/node", async () => { + const actual = + await vi.importActual("@sentry/node"); + return { + ...actual, + setTag: vi.fn(), + captureException: vi.fn(() => "id"), + }; +}); + +function mockUserResponse(fn: Mock, response: unknown) { + fn.mockReturnValueOnce(response); +} + +describe("askForToolConfigPath", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("returns undefined if users have no config file", async () => { + mockUserResponse(clack.confirm as Mock, false); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(result).toBeUndefined(); + }); + + it("returns the path if users have a config file and the entered path is valid", async () => { + mockUserResponse(clack.confirm as Mock, true); + mockUserResponse(clack.text as Mock, "my.webpack.config.js"); + + const result = await askForToolConfigPath("Webpack", "webpack.config.js"); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("have a Webpack config file"), + }), + ); + + expect(clack.text).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "enter the path to your Webpack config file", + ), + }), + ); + + expect(result).toBe("my.webpack.config.js"); + }); +}); + +describe("createNewConfigFile", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it("writes the file to disk and returns true if the file was created successfully", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(true); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + }); + + it("logs more information if provided as an argument", async () => { + vi.spyOn(fs.promises, "writeFile").mockImplementation(vi.fn()); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + const moreInfo = "More information..."; + + await createNewConfigFile(filename, code, moreInfo); + + expect(clack.log.info).toHaveBeenCalledTimes(1); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining(moreInfo), + ); + }); + + it("returns false and logs a warning if the file could not be created", async () => { + const writeFileSpy = vi + .spyOn(fs.promises, "writeFile") + .mockImplementation(() => Promise.reject(new Error("Could not write"))); + + const filename = "/webpack.config.js"; + const code = "module.exports = {/*config...*/}"; + + const result = await createNewConfigFile(filename, code); + + expect(result).toBe(false); + expect(writeFileSpy).toHaveBeenCalledWith(filename, code); + expect(clack.log.warn).toHaveBeenCalledTimes(1); + }); + + it("returns false if the passed path is not absolute", async () => { + const result = await createNewConfigFile( + "./relative/webpack.config.js", + "", + ); + + expect(result).toBe(false); + }); +}); + +describe("installPackage", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + const spawnSpy = vi.spyOn(ChildProcess, "spawn").mockImplementation(() => ({ + // @ts-expect-error - not passing the full object but directly resolving + // to simulate a successful install + on: vi.fn((evt: string, cb: (args) => void) => { + if (evt === "close") { + cb(0); + } + }), + // @ts-expect-error - this is fine + stdout: { on: vi.fn() }, + // @ts-expect-error - this is fine + stderr: { on: vi.fn() }, + })); + + it("force-installs a package if the forceInstall flag is set", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@some/package", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it.each([false, undefined])( + "doesn't force-install a package if the forceInstall flag is %s", + async (flag) => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/sveltekit", + packageNameDisplayLabel: "@sentry/sveltekit", + forceInstall: flag, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + ["install", "@sentry/sveltekit"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }, + ); + + it("adds install flags if defined", async () => { + const packageManagerMock: PackageManager = { + name: "npm", + label: "NPM", + installCommand: "install", + buildCommand: "npm run build", + runScriptCommand: "npm run", + flags: "--ignore-workspace-root-check", + forceInstallFlag: "--force", + detect: vi.fn(), + addOverride: vi.fn(), + }; + + await installPackage({ + alreadyInstalled: false, + packageName: "@some/package", + packageNameDisplayLabel: "@some/package", + forceInstall: true, + askBeforeUpdating: false, + packageManager: packageManagerMock, + }); + + expect(spawnSpy).toHaveBeenCalledWith( + "npm", + + ["install", "@some/package", "--ignore-workspace-root-check", "--force"], + { shell: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + }); + + it("irgnores stdout when installing with Yarn", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: YARN_V2, + }); + + expect(spawnSpy).toHaveBeenCalledWith("yarn", ["add", "@sentry/nextjs"], { + shell: true, + stdio: ["pipe", "ignore", "pipe"], + }); + }); + + it("shows pnpm 11 build approval guidance before installation", async () => { + await installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs", + askBeforeUpdating: false, + packageManager: PNPM, + }); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("pnpm approve-builds"), + ); + }); + + it("writes package manager stdout to the error log file", async () => { + const output = "ERR_PNPM_IGNORED_BUILDS Ignored build scripts: sharp"; + const writeFileSpy = vi + .spyOn(fs, "writeFileSync") + .mockImplementation(vi.fn()); + const dateSpy = vi.spyOn(Date, "now").mockReturnValue(123); + const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue("/project"); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + spawnSpy.mockImplementationOnce(() => ({ + stdout: { + on: vi.fn( + ( + _event: string, + callback: ((data: string) => void) | (() => void), + ) => { + callback(output); + }, + ), + } as unknown as ChildProcess.ChildProcess["stdout"], + // @ts-expect-error - not passing the full ChildProcess object + stderr: { on: vi.fn() }, + // @ts-expect-error - not passing the full ChildProcess object + on: vi.fn( + (event: "error" | "close", callback: (code: number) => void) => { + if (event === "close") { + callback(1); + } + }, + ), + })); + + await expect( + installPackage({ + alreadyInstalled: false, + packageName: "@sentry/nextjs@^10", + askBeforeUpdating: false, + packageManager: PNPM, + }), + ).rejects.toThrow(WizardExitError); + + expect(writeFileSpy).toHaveBeenCalledWith( + "/project/sentry-wizard-installation-error-123.log", + output, + { encoding: "utf8" }, + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.not.stringContaining(output), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining("sentry-wizard-installation-error-*.log"), + ); + + writeFileSpy.mockRestore(); + dateSpy.mockRestore(); + cwdSpy.mockRestore(); + exitSpy.mockRestore(); + }); +}); + +describe("printSdkV11MigrationGuideIfOutdated", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it.each(["^10.0.0", "10.5.2", "~9.1.0", ">=8.0.0 <11.0.0"])( + "warns and links the migration guide for the installed range %s", + (version) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": version }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledTimes(1); + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v10-to-v11/", + ), + ); + }, + ); + + it.each([ + ["@sentry/angular", "angular"], + ["@sentry/cloudflare", "cloudflare"], + ["@sentry/nextjs", "nextjs"], + ["@sentry/nuxt", "nuxt"], + ["@sentry/react-router", "react-router"], + ["@sentry/remix", "remix"], + ["@sentry/sveltekit", "sveltekit"], + ])("links the %s migration guide", (packageName, guide) => { + printSdkV11MigrationGuideIfOutdated(packageName, { + dependencies: { [packageName]: "^10.2.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + `https://docs.sentry.io/platforms/javascript/guides/${guide}/migration/v10-to-v11/`, + ), + ); + }); + + it("falls back to the generic migration guide for other SDKs", () => { + printSdkV11MigrationGuideIfOutdated("@sentry/browser", { + dependencies: { "@sentry/browser": "^10.0.0" }, + }); + + expect(clackMock.log.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://docs.sentry.io/platforms/javascript/migration/v10-to-v11/", + ), + ); + }); + + it.each([ + ["the SDK is not installed", {}], + [ + "the SDK is already on v11", + { dependencies: { "@sentry/nextjs": "^11.0.0" } }, + ], + [ + "the installed range is not a valid semver range", + { + dependencies: { "@sentry/nextjs": "workspace:*" }, + }, + ], + ])("stays silent when %s", (_case, packageJson) => { + printSdkV11MigrationGuideIfOutdated("@sentry/nextjs", packageJson); + + expect(clackMock.log.warn).not.toHaveBeenCalled(); + }); +}); + +describe("abort", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("stops the wizard with an error exit code by default", async () => { + const error = await abort().catch((e: unknown) => e); + + expect(error).toBeInstanceOf(WizardExitError); + expect((error as WizardExitError).exitCode).toBe(1); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Wizard setup cancelled."); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "aborted"); + }); + + it("stops the wizard with a custom exit code and message if provided", async () => { + const error = await abort("Bye", 0).catch((e: unknown) => e); + + expect((error as WizardExitError).exitCode).toBe(0); + expect(clackMock.outro).toHaveBeenCalledTimes(1); + expect(clackMock.outro).toHaveBeenCalledWith("Bye"); + expect(Sentry.setTag).toHaveBeenCalledWith("wizard.outcome", "cancelled"); + }); +}); + +describe("getPackageManager", () => { + afterEach(() => { + vi.clearAllMocks(); + // @ts-expect-error - this variable is set by the wizard + delete global.__sentry_wizard_cached_package_manager; + }); + + it("returns the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V1); + }); + + it("caches the auto-detected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(YARN_V1); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(YARN_V1); + expect(packageManager2).toBe(YARN_V1); + }); + + describe("when auto detection fails", () => { + it("returns a fallback package manager if fallback is specified", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + const packageManager = await getPackageManager(YARN_V2); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + + expect(packageManager).toBe(YARN_V2); + }); + + it("doesn't cache the fallback package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValue(null); + + const packageManager1 = await getPackageManager(YARN_V2); + const packageManager2 = await getPackageManager(NPM); + + expect(detectPacManSpy).toHaveBeenCalledTimes(2); + + expect(packageManager1).toBe(YARN_V2); + expect(packageManager2).toBe(NPM); + }); + + it("returns the user-selected package manager if no fallback is provided", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(packageManager).toBe(PNPM); + }); + + it("caches the user-selected package manager", async () => { + const detectPacManSpy = vi + .spyOn(PackageManagerUtils, "_detectPackageManger") + .mockReturnValueOnce(null); + + clackMock.select.mockReturnValueOnce(Promise.resolve(PNPM)); + + const packageManager1 = await getPackageManager(); + const packageManager2 = await getPackageManager(); + + expect(detectPacManSpy).toHaveBeenCalledTimes(1); + expect(clackMock.select).toHaveBeenCalledTimes(1); + + expect(packageManager1).toBe(PNPM); + expect(packageManager2).toBe(PNPM); + }); + }); +}); + +describe("confirmContinueIfNoOrDirtyGitRepo", () => { + // process.exit is mocked to throw so that abort() halts execution the same + // way it would terminate the process in production, instead of falling + // through to the interactive prompt. + let exitSpy: MockInstance; + + beforeEach(() => { + vi.clearAllMocks(); + // Drain any leftover `mockReturnValueOnce` values queued by earlier + // suites; `clearAllMocks` clears call history but not the once-queue. + clackMock.confirm.mockReset(); + exitSpy = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("exit"); + }); + }); + + afterEach(() => { + exitSpy.mockRestore(); + }); + + describe("non-interactive mode", () => { + it("aborts without prompting when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "not inside a git repository in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", false); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + + it("aborts without prompting when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + + await expect( + confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: true, + }), + ).rejects.toThrow(WizardExitError); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.log.error).toHaveBeenCalledWith( + expect.stringContaining( + "uncommitted or untracked files in non-interactive mode", + ), + ); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + false, + ); + expect(clack.confirm).not.toHaveBeenCalled(); + }); + }); + + describe("interactive mode (default)", () => { + it("prompts to continue when the project is not a git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(false); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("not inside a git repository"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith("continue-without-git", true); + }); + + it("prompts to continue when the repository has uncommitted or untracked files", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([ + "src/index.ts", + ]); + mockUserResponse(clack.confirm as Mock, true); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: false, + cwd: undefined, + nonInteractive: false, + }); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("uncommitted or untracked files"), + ); + expect(clack.confirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining("continue anyway"), + }), + ); + expect(clack.log.error).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + expect(Sentry.setTag).toHaveBeenCalledWith( + "continue-with-dirty-repo", + true, + ); + }); + + it("does not prompt or abort for a clean git repository", async () => { + (GitUtils.isInGitRepo as Mock).mockReturnValue(true); + (GitUtils.getUncommittedOrUntrackedFilePaths as Mock).mockReturnValue([]); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: undefined, + cwd: undefined, + }); + + expect(clack.confirm).not.toHaveBeenCalled(); + expect(clack.log.warn).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts new file mode 100644 index 0000000000..af614d9793 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -0,0 +1,1049 @@ +import { + describe, + expect, + it, + vi, + beforeEach, + afterEach, + type Mock, +} from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as fs from "node:fs"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as childProcess from "node:child_process"; +import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; + +// Mock types for better type safety +type ConfigContent = { + mcpServers?: Record; + servers?: Record; + mcp?: Record; + $schema?: string; + otherProperty?: string; +}; + +// Mock the clack utils which wrap the prompts +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", () => ({ + abortIfCancelled: vi.fn((value: unknown) => Promise.resolve(value)), + showCopyPasteInstructions: vi.fn(), +})); + +// Mock the external dependencies +vi.mock("@clack/prompts", () => ({ + confirm: vi.fn(), + select: vi.fn(), + multiselect: vi.fn(), + isCancel: vi.fn(() => false), + cancel: vi.fn(), + log: { + success: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + }, +})); + +vi.mock("node:fs"); +vi.mock("node:child_process"); + +describe("mcp-config", () => { + // Helper to get mocked modules with proper typing + type ClackMocks = { + select: ReturnType; + multiselect: ReturnType; + log: { + success: ReturnType; + info: ReturnType; + warn: ReturnType; + }; + }; + + type ClackUtilsMocks = { + abortIfCancelled: Mock<(value: unknown) => Promise>; + showCopyPasteInstructions: ReturnType; + }; + + const getMocks = async () => { + const clack = await vi.importMock("@clack/prompts"); + const clackUtils = await vi.importMock( + "../../../../../src/lib/wizard/utils/clack/index.js", + ); + return { clack, clackUtils }; + }; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("offerProjectScopedMcpConfig", () => { + it("should return early if user declines MCP config", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValue("no"); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + "Optionally add a project-scoped MCP server configuration", + ) as string, + options: expect.arrayContaining([ + expect.objectContaining({ value: "yes" }), + expect.objectContaining({ value: "no" }), + expect.objectContaining({ value: "explain" }), + ]) as unknown[], + initialValue: "yes", + }), + ); + }); + + it("should configure for Cursor when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(clack.multiselect).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Which editor(s) do you want to configure?", + options: expect.arrayContaining([ + expect.objectContaining({ value: "cursor" }), + expect.objectContaining({ value: "vscode" }), + expect.objectContaining({ value: "claudeCode" }), + ]) as unknown[], + }), + ); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("reload your editor"), + ); + }); + + it("should configure for VS Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + ); + }); + + it("should configure for Claude Code when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + ); + }); + + it("should update existing Cursor config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockReadFile).toHaveBeenCalled(); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining("Sentry"), + "utf8", + ); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .cursor/mcp.json", + ); + }); + + it("should update existing VS Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + servers: { + OtherServer: { + url: "https://other.example.com", + type: "http", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.servers).toHaveProperty("OtherServer"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + expect(writtenContent.servers?.["Sentry"]).toHaveProperty("type", "http"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should update existing Claude Code config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcpServers).toHaveProperty("OtherServer"); + expect(writtenContent.mcpServers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated .mcp.json"); + }); + + it("should configure for OpenCode when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + expect.stringContaining('"mcp"'), + "utf8", + ); + + // Verify the written content has the correct structure for OpenCode + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.$schema).toBe("https://opencode.ai/config.json"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("url"); + expect(writtenContent.mcp?.["Sentry"]?.oauth).toEqual({}); + + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining("opencode.json"), + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for OpenCode.", + ); + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("restart OpenCode"), + ); + }); + + it("should update existing OpenCode config file", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + mcp: { + OtherServer: { + type: "remote", + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent.mcp).toHaveProperty("OtherServer"); + expect(writtenContent.mcp).toHaveProperty("Sentry"); + expect(writtenContent.mcp?.["Sentry"]).toHaveProperty("type", "remote"); + + expect(clack.log.success).toHaveBeenCalledWith("Updated opencode.json"); + }); + + it("should handle file write errors gracefully for OpenCode", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["openCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for openCode"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: "opencode.json", + codeSnippet: expect.stringContaining('"mcp"') as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".cursor", "mcp.json"), + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for VS Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + codeSnippet: expect.stringContaining("servers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle file write errors gracefully for Claude Code", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["claudeCode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Permission denied")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: ".mcp.json", + codeSnippet: expect.stringContaining("mcpServers") as string, + hint: "create the file if it does not exist", + }), + ); + }); + + it("should handle update errors and show copy-paste instructions", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock existing file and simulate write error during update + const existingConfig = JSON.stringify({ + mcpServers: { + OtherServer: { + url: "https://other.example.com", + }, + }, + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi + .fn() + .mockRejectedValue(new Error("Write failed during update")); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should handle mkdirSync errors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn().mockImplementation(() => { + throw new Error("Permission denied"); + }); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await expect(offerProjectScopedMcpConfig()).resolves.toBeUndefined(); + + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config"), + ); + + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalled(); + }); + + it("should create config with empty servers/mcpServers when existing config lacks them", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const existingConfig = JSON.stringify({ + otherProperty: "value", + }); + + const mockReadFile = vi.fn().mockResolvedValue(existingConfig); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + const writtenContent = JSON.parse( + mockWriteFile.mock.calls[0]?.[1] as string, + ) as ConfigContent; + expect(writtenContent).toHaveProperty("otherProperty", "value"); + expect(writtenContent).toHaveProperty("servers"); + expect(writtenContent.servers).toHaveProperty("Sentry"); + + expect(clack.log.success).toHaveBeenCalledWith( + "Updated .vscode/mcp.json", + ); + }); + + it("should show config for JetBrains IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: (code?: number) => void) => { + if (event === "close") callback(0); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("JetBrains IDEs"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + expect(clack.log.success).toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + + consoleSpy.mockRestore(); + }); + + it("should show generic config for unsupported IDEs with clipboard copy", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For the clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["other"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy failure to test fallback + const mockSpawn = vi.fn().mockReturnValue({ + stdin: { + write: vi.fn(), + end: vi.fn(), + }, + on: vi.fn((event, callback: () => void) => { + if (event === "error") callback(); + }), + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("Generic MCP configuration"), + ); + + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining("mcpServers"), + ); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Since clipboard copy failed, should show warning + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should handle clipboard copy failure gracefully for JetBrains", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(true); // For clipboard copy prompt + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + // Mock clipboard copy to throw error + const mockSpawn = vi.fn().mockImplementation(() => { + throw new Error("Clipboard not available"); + }); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should show warning when clipboard fails + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it('should show MCP explanation when user selects "What is MCP?"', async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(true); // User selects "Yes" after explanation + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); // User selects Cursor + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("AI assistants"), + ); + + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("https://docs.sentry.io/product/sentry-mcp/"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should proceed with normal flow + expect(mockWriteFile).toHaveBeenCalled(); + }); + + it("should respect user choice not to copy to clipboard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("yes") + .mockResolvedValueOnce(false); // User declines to copy to clipboard + vi.mocked(clack.multiselect).mockResolvedValueOnce(["jetbrains"]); + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockSpawn = vi.fn(); + vi.spyOn(childProcess, "spawn").mockImplementation(mockSpawn); + + // Mock console.log to capture output + const consoleSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + await offerProjectScopedMcpConfig(); + + // Should ask to copy to clipboard + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Copy configuration to clipboard?", + }), + ); + + // Should NOT attempt to copy when user declines + expect(mockSpawn).not.toHaveBeenCalled(); + + // Should NOT show success or warning messages + expect(clack.log.success).not.toHaveBeenCalledWith( + "Configuration copied to clipboard!", + ); + expect(clack.log.warn).not.toHaveBeenCalledWith( + expect.stringContaining("Failed to copy to clipboard"), + ); + + consoleSpy.mockRestore(); + }); + + it("should exit if user declines after MCP explanation", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select) + .mockResolvedValueOnce("explain") // User selects "What is MCP?" + .mockResolvedValueOnce(false); // User selects "No" after explanation + + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + await offerProjectScopedMcpConfig(); + + // Should show MCP explanation + expect(clack.log.info).toHaveBeenCalledWith( + expect.stringContaining("What is MCP"), + ); + + // Should ask again after explanation + expect(clack.select).toHaveBeenCalledWith( + expect.objectContaining({ + message: "Would you like to configure MCP for your IDE now?", + }), + ); + + // Should NOT proceed with editor selection + expect(clack.multiselect).not.toHaveBeenCalled(); + }); + + it("should configure multiple editors when selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([ + "cursor", + "vscode", + "claudeCode", + ]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Should write config for all three editors + expect(mockWriteFile).toHaveBeenCalledTimes(3); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".vscode/mcp.json"), + expect.stringContaining('"servers"'), + "utf8", + ); + expect(mockWriteFile).toHaveBeenCalledWith( + expect.stringContaining(".mcp.json"), + expect.stringContaining('"mcpServers"'), + "utf8", + ); + + // Should show success messages for each (twice per editor: filename + editor-specific message) + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Cursor.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for VS Code.", + ); + expect(clack.log.success).toHaveBeenCalledWith( + "Added project-scoped Sentry MCP configuration for Claude Code.", + ); + }); + + it("should return early when no editors are selected", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce([]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn(); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + + await offerProjectScopedMcpConfig(); + + expect(clack.log.info).toHaveBeenCalledWith( + "No editors selected. You can add MCP configuration later.", + ); + expect(mockWriteFile).not.toHaveBeenCalled(); + }); + + it("should handle mixed success and failure for multiple editors", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi + .fn() + .mockRejectedValue(new Error("File not found")); + const mockWriteFile = vi + .fn() + .mockResolvedValueOnce(undefined) // Cursor succeeds + .mockRejectedValueOnce(new Error("Permission denied")); // VS Code fails + const mockMkdirSync = vi.fn(); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(mockMkdirSync); + + await offerProjectScopedMcpConfig(); + + // Cursor should succeed + expect(clack.log.success).toHaveBeenCalledWith( + expect.stringContaining(".cursor/mcp.json"), + ); + + // VS Code should fail and show fallback + expect(clack.log.warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to write MCP config for vscode"), + ); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ + filename: path.join(".vscode", "mcp.json"), + }), + ); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/data-collection.test.ts b/packages/cli/test/lib/wizard/utils/data-collection.test.ts new file mode 100644 index 0000000000..6f68c33bf0 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/data-collection.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; + +import { + getDataCollectionSnippet, + sdkSupportsDataCollection, +} from "../../../../src/lib/wizard/utils/data-collection.js"; +import { getMajorVersion } from "../../../../src/lib/wizard/utils/semver.js"; + +describe("getMajorVersion", () => { + it.each([ + ["^10", 10], + ["^10.73.0", 10], + ["~11.2.0", 11], + ["11.0.0", 11], + // Prerelease versions keep their major, so v11 rc/beta installs pass the gate + ["11.0.0-rc.1", 11], + ["^11.0.0-rc.0", 11], + ["~11.0.0-beta.2", 11], + [">=10.57.0 <12", 10], + ])("returns the lowest permitted major for %s", (version, expected) => { + expect(getMajorVersion(version)).toBe(expected); + }); + + it.each([undefined, "", "not-a-version", "workspace:*"])( + "returns undefined for %s", + (version) => { + expect(getMajorVersion(version)).toBeUndefined(); + }, + ); +}); + +describe("sdkSupportsDataCollection", () => { + it.each([ + ["^11.0.0", "^10"], + ["11.2.3", "^10"], + ["^12", "^10"], + ["11.0.0-rc.1", "^10"], + ["^11.0.0-beta.0", "^10"], + ])("returns true for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(true); + }); + + it.each([ + ["^10.73.0", "^10"], + ["10.99.0", "^10"], + ["^9", "^10"], + ["10.99.0-rc.1", "^10"], + ])("returns false for installed version %s", (installed, range) => { + expect(sdkSupportsDataCollection(installed, range)).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is missing", () => { + expect(sdkSupportsDataCollection(undefined, "^11")).toBe(true); + expect(sdkSupportsDataCollection(undefined, "^10")).toBe(false); + }); + + it("falls back to the wizard install range when the installed version is unparseable", () => { + expect(sdkSupportsDataCollection("workspace:*", "^11")).toBe(true); + expect(sdkSupportsDataCollection("workspace:*", "^10")).toBe(false); + }); + + it("returns false when neither version is parseable", () => { + expect(sdkSupportsDataCollection(undefined, "not-a-version")).toBe(false); + }); +}); + +describe("getDataCollectionSnippet", () => { + it("renders the preset with the default indentation", () => { + expect(getDataCollectionSnippet()).toMatchInlineSnapshot(` + " // Turns off collection of data that could identify users. Adjust per category: + // https://docs.sentry.io/platforms/javascript/configuration/options/#dataCollection + dataCollection: { + userInfo: false, + graphQL: { document: false, variables: false }, + genAI: { inputs: false, outputs: false }, + databaseQueryData: false, + queues: false, + httpBodies: [], + httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + cookies: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + urlQueryParams: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }, + }," + `); + }); + + it("prefixes every line with the given indent", () => { + const snippet = getDataCollectionSnippet(" "); + for (const line of snippet.split("\n")) { + expect(line.startsWith(" ")).toBe(true); + } + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/git.test.ts b/packages/cli/test/lib/wizard/utils/git.test.ts new file mode 100644 index 0000000000..4daaffda1c --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/git.test.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, it, vi, expect } from "vitest"; + +import { + getUncommittedOrUntrackedFilePaths, + isInGitRepo, +} from "../../../../src/lib/wizard/utils/git.js"; + +const { mockedExecSync } = vi.hoisted(() => { + return { mockedExecSync: vi.fn() }; +}); + +vi.mock("node:child_process", async () => { + return { + default: {}, + ...(await vi.importActual("node:child_process")), + execSync: mockedExecSync, + }; +}); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("isInGitRepo", () => { + it("returns true if the git command process exits with 0", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + expect(isInGitRepo({ cwd: undefined })).toBe(true); + }); + + it("returns false if the git command process exits with non-zero", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + expect(isInGitRepo({ cwd: undefined })).toBe(false); + }); + + it("forwards cwd if provided", () => { + mockedExecSync.mockImplementationOnce(() => { + return "true"; + }); + isInGitRepo({ cwd: "/path/to/dir" }); + expect(mockedExecSync).toHaveBeenCalledWith( + "git rev-parse --is-inside-work-tree", + { + stdio: "ignore", + cwd: "/path/to/dir", + }, + ); + }); +}); + +describe("getUncommittedOrUntrackedFilePaths", () => { + it("returns the verbatim paths of uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + " M file1.txt\0" + + "?? file2.txt\0" + + "?? file3.txt\0" + + "?? file4.txt\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "file1.txt", + "file2.txt", + "file3.txt", + "file4.txt", + ]); + }); + + it("uses the NUL-delimited porcelain format", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + getUncommittedOrUntrackedFilePaths({ cwd: "/path/to/dir" }); + + expect(mockedExecSync).toHaveBeenCalledWith( + "git status --porcelain=v1 -z", + { + stdio: ["ignore", "pipe", "ignore"], + cwd: "/path/to/dir", + }, + ); + }); + + it("preserves file names containing spaces and shell metacharacters", () => { + mockedExecSync.mockImplementationOnce(() => { + return ( + "?? $(touch pwned).js\0" + + "?? a;id;b.js\0" + + "?? with space.txt\0" + + " M `whoami`.ts\0" + ); + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "$(touch pwned).js", + "a;id;b.js", + "with space.txt", + "`whoami`.ts", + ]); + }); + + it("returns the destination path of a rename and skips the source field", () => { + mockedExecSync.mockImplementationOnce(() => { + return "R renamed.txt\0orig.txt\0?? other.txt\0"; + }); + expect(getUncommittedOrUntrackedFilePaths()).toEqual([ + "renamed.txt", + "other.txt", + ]); + }); + + it("returns an empty list if there are no uncommitted or untracked files", () => { + mockedExecSync.mockImplementationOnce(() => ""); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); + + it("returns an empty list if the git command fails", () => { + mockedExecSync.mockImplementationOnce(() => { + throw new Error("Command failed"); + }); + + expect(getUncommittedOrUntrackedFilePaths()).toEqual([]); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/node-version.test.ts b/packages/cli/test/lib/wizard/utils/node-version.test.ts new file mode 100644 index 0000000000..f7084d0253 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/node-version.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const clackMocks = vi.hoisted(() => ({ warn: vi.fn() })); + +vi.mock("@clack/prompts", () => ({ + log: { warn: clackMocks.warn }, +})); + +import { + isNodeVersionSupportedBySdkV11, + warnIfNodeVersionUnsupportedBySdkV11, +} from "../../../../src/lib/wizard/utils/node-version.js"; + +describe("isNodeVersionSupportedBySdkV11", () => { + it.each([ + "v20.19.0", + "v20.20.2", + "20.19.5", + "v22.12.0", + "v22.23.2", + "v23.2.0", + "v24.0.0", + "v26.8.1", + // Node.js 21 is EOL but inside the documented `>=20.19.0 <22.0.0` range + "v21.7.0", + ])("returns true for %s", (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }); + + it.each(["v18.20.6", "v20.18.3", "v22.11.0", "v23.1.0", "16.20.2"])( + "returns false for %s", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(false); + }, + ); + + it.each(["", "not-a-version"])( + "treats an unparseable version (%s) as supported", + (version) => { + expect(isNodeVersionSupportedBySdkV11(version)).toBe(true); + }, + ); + + it("defaults to the running Node.js version", () => { + expect(isNodeVersionSupportedBySdkV11()).toBe( + isNodeVersionSupportedBySdkV11(process.version), + ); + }); +}); + +describe("warnIfNodeVersionUnsupportedBySdkV11", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("warns on an unsupported version and names it", () => { + warnIfNodeVersionUnsupportedBySdkV11("v18.20.6"); + + expect(clackMocks.warn).toHaveBeenCalledTimes(1); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("v18.20.6"); + expect(clackMocks.warn.mock.calls[0]?.[0]).toContain("20.19.0"); + }); + + it("stays silent on a supported version", () => { + warnIfNodeVersionUnsupportedBySdkV11("v22.18.0"); + + expect(clackMocks.warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts new file mode 100644 index 0000000000..f04f2f9fd4 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -0,0 +1,594 @@ +import { beforeEach, describe, it, vi, expect, afterEach } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as path from "node:path"; + +import { + findInstalledPackageFromList, + hasPackageInstalled, + getPackageVersion, + type PackageDotJson, +} from "../../../../src/lib/wizard/utils/package-json.js"; + +const { mockedFs, mockedClack } = vi.hoisted(() => { + return { + mockedFs: { + existsSync: vi.fn(), + readFileSync: vi.fn(), + }, + mockedClack: { + log: { + error: vi.fn(), + }, + }, + }; +}); + +vi.mock(import("node:fs"), async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: mockedFs.existsSync, + readFileSync: mockedFs.readFileSync, +})); + +vi.mock(import("@clack/prompts"), async (importOriginal) => ({ + ...(await importOriginal()), + log: { + ...(await importOriginal()).log, + error: mockedClack.log.error, + }, +})); + +describe("package-json utils", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getPackageVersion", () => { + it("returns version from dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns version from devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("^2.0.0"); + }); + + it("prioritizes dependencies over devDependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + devDependencies: { + "@sentry/node": "^6.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + }); + + it("returns undefined if package is not found", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if packageJson has no dependencies", () => { + const packageJson: PackageDotJson = {}; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + describe("pnpm catalog resolution", () => { + beforeEach(() => { + vi.spyOn(process, "cwd").mockReturnValue( + "/test/workspace/packages/app", + ); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("resolves default catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("resolves named catalog reference", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.100.0 + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.100.0", + ); + }); + + it("searches parent directories for pnpm-workspace.yaml", () => { + const mockCwd = "/test/workspace/packages/app/src"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + + it("returns undefined if catalog does not contain the package", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("returns undefined if named catalog does not exist", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect( + getPackageVersion("@sentry/sveltekit", packageJson), + ).toBeUndefined(); + }); + + it("returns undefined if pnpm-workspace.yaml is not found", () => { + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + expect(mockedClack.log.error).toHaveBeenCalledWith( + "Could not find pnpm-workspace.yaml.", + ); + }); + + it("stops searching at root directory", () => { + const mockCwd = "/test"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockReturnValue(false); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("handles both default catalog and named catalogs together", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +catalogs: + sveltekit: + '@sentry/sveltekit': ^7.200.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/sveltekit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + expect(getPackageVersion("@sentry/sveltekit", packageJson)).toBe( + "^7.200.0", + ); + }); + + it("handles the correct catalog namespace", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sveltejs/kit': ^1.0.0 +catalogs: + sveltekit: + '@sveltejs/kit': ^2.31.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sveltejs/kit": "catalog:sveltekit", + }, + }; + + expect(getPackageVersion("@sveltejs/kit", packageJson)).toBe("^2.31.0"); + }); + + it("ignores pnpm-workspace.yaml content that is not a catalog mapping", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue("invalid: yaml: content: ["); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBeUndefined(); + }); + + it("reads quoted names, inline comments, and catalogs of other packages", () => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + + mockedFs.readFileSync.mockReturnValue(`packages: + - 'apps/*' + +# Versions shared across the workspace +catalog: + "@sentry/node": "^8.0.0" # keep in sync + react: ^18.2.0 + +catalogs: + legacy: + '@sentry/node': ~7.120.0 + next: + "@sentry/nextjs": 9.0.0 +onlyBuiltDependencies: + - esbuild +`); + + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:" }, + }), + ).toBe("^8.0.0"); + expect( + getPackageVersion("@sentry/node", { + dependencies: { "@sentry/node": "catalog:legacy" }, + }), + ).toBe("~7.120.0"); + expect( + getPackageVersion("@sentry/nextjs", { + dependencies: { "@sentry/nextjs": "catalog:next" }, + }), + ).toBe("9.0.0"); + }); + + it("handles regular version strings without catalog lookup", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "~7.1.0", + "@sentry/cli": "2.0.0", + }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.0.0"); + expect(getPackageVersion("@sentry/react", packageJson)).toBe("~7.1.0"); + expect(getPackageVersion("@sentry/cli", packageJson)).toBe("2.0.0"); + expect(mockedFs.existsSync).not.toHaveBeenCalled(); + }); + }); + }); + + describe("hasPackageInstalled", () => { + it("returns true if package is in dependencies", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns true if package is in devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + expect(hasPackageInstalled("@sentry/cli", packageJson)).toBe(true); + }); + + it("returns false if package is not installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + + it("returns true if package uses catalog reference", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(true); + }); + + it("returns false if package uses catalog reference but catalog does not have it", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + expect(hasPackageInstalled("@sentry/node", packageJson)).toBe(false); + }); + }); + + describe("findInstalledPackageFromList", () => { + it("returns the first installed package from the list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.0.0", + }); + }); + + it("returns undefined if no packages are installed", () => { + const packageJson: PackageDotJson = { + dependencies: {}, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node", "@sentry/react"], + packageJson, + ); + + expect(result).toBeUndefined(); + }); + + it("checks both dependencies and devDependencies", () => { + const packageJson: PackageDotJson = { + devDependencies: { + "@sentry/cli": "^2.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/cli"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/cli", + version: "^2.0.0", + }); + }); + + it("returns first match in order provided", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + "@sentry/react": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/react", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.0.0", + }); + }); + + it("works with catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/node': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/cli", "@sentry/node"], + packageJson, + ); + + expect(result).toEqual({ + name: "@sentry/node", + version: "^7.100.0", + }); + }); + + it("returns undefined for empty package list", () => { + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "^7.0.0", + }, + }; + + const result = findInstalledPackageFromList([], packageJson); + + expect(result).toBeUndefined(); + }); + + it("skips packages with unresolvable catalog references", () => { + const mockCwd = "/test/workspace/packages/app"; + vi.spyOn(process, "cwd").mockReturnValue(mockCwd); + + mockedFs.existsSync.mockImplementation((filepath: string) => { + return filepath === path.join("/test/workspace", "pnpm-workspace.yaml"); + }); + + mockedFs.readFileSync.mockReturnValue(` +catalog: + '@sentry/react': ^7.100.0 +`); + + const packageJson: PackageDotJson = { + dependencies: { + "@sentry/node": "catalog:", + "@sentry/react": "catalog:", + }, + }; + + const result = findInstalledPackageFromList( + ["@sentry/node", "@sentry/react"], + packageJson, + ); + + // Should skip @sentry/node (unresolvable) and return @sentry/react + expect(result).toEqual({ + name: "@sentry/react", + version: "^7.100.0", + }); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/package-manager.test.ts b/packages/cli/test/lib/wizard/utils/package-manager.test.ts new file mode 100644 index 0000000000..2eaec28053 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/package-manager.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { + _detectPackageManger, + NPM, + PNPM, + YARN_V1, +} from "../../../../src/lib/wizard/utils/package-manager.js"; + +describe("_detectPackageManager", () => { + it("returns the detected package manager if exactly one is found", () => { + const pnpm = { ...PNPM, detect: () => true }; + + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + pnpm, + ]); + + expect(packageManager).toBe(pnpm); + }); + + it("returns null if no package manager is found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => false }, + { ...YARN_V1, detect: () => false }, + ]); + expect(packageManager).toBeNull(); + }); + + it("returns null if multiple package managers are found", () => { + const packageManager = _detectPackageManger([ + { ...NPM, detect: () => true }, + { ...YARN_V1, detect: () => true }, + ]); + expect(packageManager).toBeNull(); + }); +}); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts new file mode 100644 index 0000000000..a691410ee2 --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -0,0 +1,252 @@ +/** + * Tests for the wizards' project selection on top of the CLI's login. + */ + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getAuthConfig: vi.fn(), + runInteractiveLogin: vi.fn(), + completeAgentHandoff: vi.fn(), + ensureScopesForAction: vi.fn(), + listOrganizations: vi.fn(), + listProjects: vi.fn(), + getProject: vi.fn(), + getProjectKeys: vi.fn(), + createProjectWithDsn: vi.fn(), + createProjectWithAutoTeam: vi.fn(), + resolveOrCreateTeam: vi.fn(), + createOrgAuthToken: vi.fn(), + select: vi.fn(), + text: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + isCancel: vi.fn(() => false), + cancel: vi.fn(), + outro: vi.fn(), + select: mocks.select, + text: mocks.text, + spinner: vi.fn(() => ({ start: vi.fn(), stop: vi.fn() })), + log: { + info: vi.fn(), + step: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); +vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ + ...(await importOriginal()), + getAuthConfig: mocks.getAuthConfig, +})); +vi.mock("../../../../src/lib/interactive-login.js", () => ({ + runInteractiveLogin: mocks.runInteractiveLogin, +})); +vi.mock("../../../../src/lib/agent-handoff.js", () => ({ + completeAgentHandoff: mocks.completeAgentHandoff, +})); +vi.mock("../../../../src/lib/auto-auth.js", () => ({ + assertAutoLoginHostTrusted: vi.fn(), +})); +vi.mock("../../../../src/lib/scope-recovery.js", () => ({ + ensureScopesForAction: mocks.ensureScopesForAction, +})); +vi.mock("../../../../src/lib/api/organizations.js", () => ({ + listOrganizations: mocks.listOrganizations, +})); +vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ + createOrgAuthToken: mocks.createOrgAuthToken, +})); +vi.mock("../../../../src/lib/resolve-team.js", () => ({ + resolveOrCreateTeam: mocks.resolveOrCreateTeam, +})); +vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/api/projects.js") + >()), + listProjects: mocks.listProjects, + getProject: mocks.getProject, + getProjectKeys: mocks.getProjectKeys, + createProjectWithDsn: mocks.createProjectWithDsn, + createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, +})); + +import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; +import { + DUMMY_AUTH_TOKEN, + getOrAskForProjectData, +} from "../../../../src/lib/wizard/utils/project-data.js"; +import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.js"; + +const ORG = { id: "1", slug: "acme", name: "Acme" }; +const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const KEY = { + id: "k1", + name: "Default", + isActive: true, + dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, +}; + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("SENTRY_HANDOFF", ""); + mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.listOrganizations.mockResolvedValue([ORG]); + mocks.getProject.mockResolvedValue(PROJECT); + mocks.getProjectKeys.mockResolvedValue([KEY]); + mocks.ensureScopesForAction.mockResolvedValue("ready"); + mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); +}); + +describe("getOrAskForProjectData", () => { + it("needs no login in Spotlight mode", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + spotlight: true, + }); + + expect(result).toEqual({ spotlight: true }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("returns a preselected project without asking", async () => { + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.io/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: false }, + }); + + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "tok", + selectedProject: project, + }); + expect(mocks.listOrganizations).not.toHaveBeenCalled(); + }); + + it("uses the stored login and the --org and --project slugs", async () => { + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + expect(result).toEqual({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_new", + selectedProject: { + id: "42", + slug: "web", + organization: ORG, + keys: [{ dsn: { public: KEY.dsn.public } }], + }, + }); + }); + + it("asks for the project when the --project slug is not found", async () => { + mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "missing", + }); + + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("creates a project for the wizard's platform", async () => { + mocks.listProjects.mockResolvedValue([]); + mocks.select.mockImplementationOnce( + (options: { options: { value: unknown }[] }) => + Promise.resolve(options.options[0]?.value), + ); + mocks.text.mockResolvedValueOnce("my app"); + mocks.resolveOrCreateTeam.mockResolvedValue({ slug: "acme" }); + mocks.createProjectWithDsn.mockResolvedValue({ + project: { ...PROJECT, slug: "my-app" }, + }); + + const result = await getOrAskForProjectData( + { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + "javascript-nextjs", + ); + + expect(mocks.createProjectWithDsn).toHaveBeenCalledWith("acme", "acme", { + name: "my app", + platform: "javascript-nextjs", + }); + expect(result).toMatchObject({ selectedProject: { slug: "my-app" } }); + }); + + it("writes a placeholder token when no auth token can be created", async () => { + mocks.ensureScopesForAction.mockResolvedValue("unavailable"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); + expect(result).toMatchObject({ authToken: DUMMY_AUTH_TOKEN }); + }); + + it("logs in with the device flow when there is no stored login", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ + scope: expect.stringContaining("org:tokens"), + }); + }); + + it("stops when the login fails", async () => { + mocks.getAuthConfig.mockReturnValue(undefined); + mocks.runInteractiveLogin.mockResolvedValue(null); + + await expect( + getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + ).rejects.toThrow(WizardExitError); + }); + + it("claims an agent handoff and uses its org", async () => { + vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); + mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + saas: true, + projectSlug: "web", + }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d31e4395bb..363032cd0d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -792,6 +792,9 @@ importers: jpeg-js: specifier: ^0.4.4 version: 0.4.4 + magicast: + specifier: 0.2.11 + version: 0.2.11 marked: specifier: 'catalog:' version: 15.0.12 @@ -5483,6 +5486,10 @@ packages: asciinema-player@3.18.1: resolution: {integrity: sha512-H3blHwZYerDkjUVNABB0zjIzZhZu+JT0/FXT7Skc+4cpa2i7bDab49uOztsIguej4Ppfw6JS0V8J5/6VNqIIkQ==} + ast-types@0.16.3: + resolution: {integrity: sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA==} + engines: {node: '>=4'} + ast-v8-to-istanbul@1.0.7: resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} @@ -6095,6 +6102,11 @@ packages: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} + esprima@4.0.1: + resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} + engines: {node: '>=4'} + hasBin: true + estree-util-attach-comments@3.0.0: resolution: {integrity: sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==} @@ -6835,6 +6847,9 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + magicast@0.2.11: + resolution: {integrity: sha512-6saXbRDA1HMkqbsvHOU6HBjCVgZT460qheRkLhJQHWAbhXoWESI3Kn/dGGXyKs15FFKR85jsUqFx2sMK0wy/5g==} + magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} @@ -7599,6 +7614,10 @@ packages: resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} engines: {node: '>= 20.19.0'} + recast@0.23.21: + resolution: {integrity: sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==} + engines: {node: '>= 4'} + recma-build-jsx@1.0.0: resolution: {integrity: sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==} @@ -7926,6 +7945,10 @@ packages: resolution: {integrity: sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==} engines: {node: '>=0.10.0'} + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + source-map@0.7.6: resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} engines: {node: '>= 12'} @@ -8050,6 +8073,9 @@ packages: tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + tiny-invariant@1.3.3: + resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tinybench@6.2.2: resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} engines: {node: '>=20.0.0'} @@ -12410,6 +12436,10 @@ snapshots: dependencies: solid-js: 1.9.19 + ast-types@0.16.3: + dependencies: + tslib: 2.8.1 + ast-v8-to-istanbul@1.0.7: dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -13092,6 +13122,8 @@ snapshots: escape-string-regexp@5.0.0: {} + esprima@4.0.1: {} + estree-util-attach-comments@3.0.0: dependencies: '@types/estree': 1.0.9 @@ -13944,6 +13976,12 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + magicast@0.2.11: + dependencies: + '@babel/parser': 7.29.14 + '@babel/types': 7.29.14 + recast: 0.23.21 + magicast@0.5.5: dependencies: '@babel/parser': 7.29.14 @@ -15013,6 +15051,14 @@ snapshots: readdirp@5.1.1: {} + recast@0.23.21: + dependencies: + ast-types: 0.16.3 + esprima: 4.0.1 + source-map: 0.6.1 + tiny-invariant: 1.3.3 + tslib: 2.8.1 + recma-build-jsx@1.0.0: dependencies: '@types/estree': 1.0.9 @@ -15575,6 +15621,8 @@ snapshots: source-map@0.5.7: {} + source-map@0.6.1: {} + source-map@0.7.6: {} space-separated-tokens@2.0.2: {} @@ -15710,6 +15758,8 @@ snapshots: tiny-inflate@1.0.3: {} + tiny-invariant@1.3.3: {} + tinybench@6.2.2: {} tinyclip@1.0.3: {} From 76e162b5171220390d3222e30bee02e44b79c6ba Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:52:16 +0000 Subject: [PATCH 02/18] feat(cli): add the wizard's shared AST and URL helpers Port `ast-utils` and `url` from getsentry/sentry-wizard into `src/lib/wizard/utils/`. The SvelteKit, Remix, React Router, Angular, Nuxt, source maps, Cloudflare, React Native and Android wizards all use them, so they land once here and the platform PRs that follow build on them in parallel. `ast-utils` edits recast ASTs, so recast and ast-types become direct dev dependencies; both already came in through magicast. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/package.json | 2 + .../cli/src/lib/wizard/utils/ast-utils.ts | 365 ++++++++++++++++++ packages/cli/src/lib/wizard/utils/url.ts | 29 ++ .../test/lib/wizard/utils/ast-utils.test.ts | 297 ++++++++++++++ pnpm-lock.yaml | 6 + 5 files changed, 699 insertions(+) create mode 100644 packages/cli/src/lib/wizard/utils/ast-utils.ts create mode 100644 packages/cli/src/lib/wizard/utils/url.ts create mode 100644 packages/cli/test/lib/wizard/utils/ast-utils.test.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index ebda846304..0e1e679f24 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -120,6 +120,7 @@ "@types/yauzl": "3.4.0", "@typescript/typescript6": "catalog:", "@vitest/coverage-v8": "catalog:", + "ast-types": "^0.16.3", "binpatch": "^0.4.2", "chalk": "^5.6.2", "cli-highlight": "^2.1.11", @@ -141,6 +142,7 @@ "pngjs": "^7.0.0", "pretty-ms": "^9.3.0", "qrcode-terminal": "^0.12.0", + "recast": "^0.23.21", "semver": "^7.8.5", "shell-quote": "^1.11.0", "string-width": "^8.2.1", diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts new file mode 100644 index 0000000000..05929e5203 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -0,0 +1,365 @@ +/** + * Helpers that find and change nodes in a recast AST, shared by the wizards + * that edit JavaScript and TypeScript config files. + */ + +import { existsSync } from "node:fs"; + +import recast from "recast"; + +import { debug } from "./debug.js"; +import type { namedTypes as t } from "ast-types"; + +const b = recast.types.builders; + +/** + * Checks if a file where we don't know its concrete file type yet exists + * and returns the full path to the file with the correct file type. + */ +export function findFile( + filePath: string, + fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], +): string | undefined { + return fileTypes + .map((type) => `${filePath}${type}`) + .find((file) => existsSync(file)); +} + +/** + * checks for require('@sentry/*') syntax + */ +export function hasSentryContent(program: t.Program): boolean { + let foundSentry: boolean | undefined = false; + recast.visit(program, { + visitStringLiteral(path) { + foundSentry = foundSentry || path.node.value.startsWith("@sentry/"); + this.traverse(path); + }, + visitLiteral(path) { + foundSentry = + foundSentry || path.node.value?.toString().startsWith("@sentry/"); + this.traverse(path); + }, + }); + + return !!foundSentry; +} + +/** + * Searches for a property of an ObjectExpression by name + * + * @param object the ObjectExpression to search in + * @param name the name of the property to search for + * + * @returns the property if it exists + */ +export function getObjectProperty( + object: t.ObjectExpression, + name: string, +): t.Property | undefined { + return object.properties.find((p): p is t.Property => { + const isObjectProp = p.type === "Property" || p.type === "ObjectProperty"; + + if (!isObjectProp) { + return false; + } + + const hasMatchingLiteralKey = + (p.key.type === "Literal" || p.key.type === "StringLiteral") && + p.key.value === name; + + if (hasMatchingLiteralKey) { + return true; + } + + // has matching identifier key + return p.key.type === "Identifier" && p.key.name === name; + }); +} + +/** + * Attempts to find a property of an ObjectExpression by name. If it doesn't exist, + * the property will be added to the ObjectExpression with the provided default value. + * + * @param object the parent object expression to search in + * @param name the name of the property to search for + * @param defaultValue the default value to set if the property doesn't exist + * + * @returns the + */ +export function getOrSetObjectProperty( + object: t.ObjectExpression, + name: string, + defaultValue: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression, +): t.Property { + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + return existingProperty; + } + + const newProperty = b.property.from({ + kind: "init", + key: b.stringLiteral(name), + value: defaultValue, + }); + + object.properties.push(newProperty); + + return newProperty; +} + +/** + * Sets a property of an ObjectExpression if it exists, otherwise adds it + * to the ObjectExpression. Optionally, a comment can be added to the + * property. + * + * @param object the ObjectExpression to set the property on + * @param name the name of the property to set + * @param value the value of the property to set + * @param comment (optional) a comment to add to the property + */ +export function setOrUpdateObjectProperty( + object: t.ObjectExpression, + name: string, + value: + | t.Literal + | t.BooleanLiteral + | t.StringLiteral + | t.ObjectExpression + | t.ArrayExpression, + comment?: string, +): void { + const newComments = comment + ?.split("\n") + .map((c) => b.commentLine(` ${c}`, true, false)); + + const existingProperty = getObjectProperty(object, name); + + if (existingProperty) { + existingProperty.value = value; + if (newComments) { + existingProperty.comments = [ + ...(existingProperty.comments ?? []), + ...newComments, + ]; + } + } else { + object.properties.push( + b.objectProperty.from({ + key: b.stringLiteral(name), + value, + ...(newComments && { + comments: newComments, + }), + }), + ); + } +} + +type JsonCParseResult = + | { + jsonObject: t.ObjectExpression; + ast: t.Program; + } + | { + jsonObject: undefined; + ast: undefined; + }; + +/** + * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST + * that can be walked and modified with recast like a normal JS AST. + * + * This is done by wrapping the JSON-C string in parentheses, thereby making it + * a JS `Program` with an `ExpressionStatement` as its body. The expression is then + * extracted from the AST and returned alongside the AST. + * + * To preserve as much original formatting as possible, the returned `ast` + * property should be passed to {@link `printJsonC`} to get the JSON-C string back. + * + * If the input is not valid JSON-C, the result will be undefined. + * + * @see {@link JsonCParseResult} + * + * @param jsonString a JSON-C string + * + * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases + */ +export function parseJsonC(jsonString: string): JsonCParseResult { + try { + const jsTsConfig = `(${jsonString})`; + // no idea why recast returns any here, this is dumb :/ + const ast = recast.parse(jsTsConfig.toString()).program as t.Program; + + const statement = ast.body[0]; + const jsonObject = + statement?.type === "ExpressionStatement" && + statement.expression.type === "ObjectExpression" + ? statement.expression + : undefined; + + if (jsonObject) { + return { jsonObject, ast }; + } + } catch (error) { + // Not valid JSON-C: the caller handles the undefined result. + debug(error); + return { jsonObject: undefined, ast: undefined }; + } + return { jsonObject: undefined, ast: undefined }; +} + +/** + * Takes the AST of a parsed JSON-C "program" and returns the JSON-C string without + * any of the temporary JS wrapper code that was previously applied. + * + * Only use this in conjunction with {@link `parseJsonC`} + * + * @param ast the `ast` returned from {@link `parseJsonC`} + * + * @returns the JSON-C string + */ +export function printJsonC(ast: t.Program): string { + const js = recast.print(ast).code; + return js.substring(1, js.length - 1); +} + +/** + * Walks the program body and returns index of the last variable assignment initialized by require statement. + * Only counts top level require statements. + * + * @returns index of the last `const foo = require('bar');` statement or -1 if none was found. + */ +export function getLastRequireIndex(program: t.Program): number { + let lastRequireIdex = -1; + program.body.forEach((s, i) => { + const declaration = + s.type === "VariableDeclaration" ? s.declarations[0] : undefined; + if ( + declaration?.type === "VariableDeclarator" && + declaration.init?.type === "CallExpression" && + declaration.init.callee.type === "Identifier" && + declaration.init.callee.name === "require" + ) { + lastRequireIdex = i; + } + }); + return lastRequireIdex; +} + +/** + * Safely checks if a callee is an identifier with the given name + * Prevents crashes when accessing callee.name on non-identifier nodes + */ +export function safeCalleeIdentifierMatch( + callee: unknown, + name: string, +): boolean { + return Boolean( + callee && + typeof callee === "object" && + "type" in callee && + (callee as { type: string }).type === "Identifier" && + "name" in callee && + (callee as { name: string }).name === name, + ); +} + +/** + * Safely gets the name of an identifier node + * Returns null if the node is not an identifier or is undefined + */ +export function safeGetIdentifierName(node: unknown): string | null { + return node && + typeof node === "object" && + "type" in node && + node.type === "Identifier" && + "name" in node + ? String(node.name) + : null; +} + +/** + * Safely access function body array with proper validation + * Prevents crashes when accessing body.body on nodes that don't have a body + */ +export function safeGetFunctionBody(node: unknown): t.Statement[] | null { + if (!node || typeof node !== "object" || !("body" in node)) { + return null; + } + + const nodeBody = node.body; + if (!nodeBody || typeof nodeBody !== "object" || !("body" in nodeBody)) { + return null; + } + + const bodyArray = nodeBody.body; + return Array.isArray(bodyArray) ? (bodyArray as t.Statement[]) : null; +} + +/** + * Safely insert statement before last statement in function body + * Typically used to insert code before a return statement + * Returns true if insertion was successful, false otherwise + */ +export function safeInsertBeforeReturn( + body: t.Statement[], + statement: t.Statement, +): boolean { + if (body.length === 0) { + return false; + } + + // Insert before the last statement (typically a return statement) + const insertIndex = Math.max(0, body.length - 1); + body.splice(insertIndex, 0, statement); + return true; +} + +/** + * Finds a property in an ObjectExpression by name. + * Commonly used for traversing Vite/React Router config objects. + * + * @param configObj - The ObjectExpression to search + * @param name - The property name to find + * @returns The matching ObjectProperty, or undefined if not found + */ +export function findProperty( + configObj: t.ObjectExpression, + name: string, +): t.ObjectProperty | undefined { + return configObj.properties.find( + (p) => + p.type === "ObjectProperty" && + p.key.type === "Identifier" && + p.key.name === name, + ) as t.ObjectProperty | undefined; // Safe: predicate guarantees type +} + +/** + * Preserves trailing newline from original content if present. + * Code generators like magicast/recast don't preserve trailing newlines, + * so this ensures we don't unnecessarily modify user files. + * + * @param originalContent - The original file content + * @param generatedCode - The code generated by AST transformation + * @returns The generated code with trailing newline preserved if original had one + */ +export function preserveTrailingNewline( + originalContent: string, + generatedCode: string, +): string { + const hadTrailingNewline = originalContent.endsWith("\n"); + const hasTrailingNewline = generatedCode.endsWith("\n"); + + if (hadTrailingNewline && !hasTrailingNewline) { + return generatedCode + "\n"; + } + + return generatedCode; +} diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts new file mode 100644 index 0000000000..6d3af99d64 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/url.ts @@ -0,0 +1,29 @@ +/** + * Sentry URLs the wizards print after setup. + */ + +/** + * Returns the url to the Sentry project stream. + * + * Example: https://org-slug.sentry.io/issues/?project=1234567 + */ +export function getIssueStreamUrl({ + url, + orgSlug, + projectId, +}: { + url: string; + orgSlug: string; + projectId: string; +}): string { + const urlObject = new URL(url); + if (urlObject.host === "sentry.io") { + urlObject.host = `${orgSlug}.${urlObject.host}`; + urlObject.pathname = "/issues/"; + } else { + urlObject.pathname = `/organizations/${orgSlug}/issues/`; + } + urlObject.searchParams.set("project", projectId); + + return urlObject.toString(); +} diff --git a/packages/cli/test/lib/wizard/utils/ast-utils.test.ts b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts new file mode 100644 index 0000000000..f42f1de88a --- /dev/null +++ b/packages/cli/test/lib/wizard/utils/ast-utils.test.ts @@ -0,0 +1,297 @@ +import { + getObjectProperty, + getOrSetObjectProperty, + hasSentryContent, + parseJsonC, + preserveTrailingNewline, + printJsonC, + setOrUpdateObjectProperty, +} from "../../../../src/lib/wizard/utils/ast-utils.js"; + +import recast from "recast"; +const b = recast.types.builders; + +import { describe, it, expect } from "vitest"; + +describe("hasSentryContent", () => { + it.each([ + ` + const { sentryVitePlugin } = require("@sentry/bundler-plugins/vite"); + const somethingelse = require('gs'); + `, + ` + import { sentryVitePlugin } from "@sentry/bundler-plugins/vite"; + import * as somethingelse from 'gs'; + + export default { + plugins: [sentryVitePlugin()] + } + `, + ])( + "returns true if a require('@sentry/') call was found in the parsed module", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(true); + }, + ); + + it.each([ + `const whatever = require('something')`, + `// const {sentryWebpackPlugin} = require('@sentry/bundler-plugins/webpack')`, + `const {sAntryWebpackPlugin} = require('webpack-plugin-@sentry')`, + ` + import * as somethingelse from 'gs'; + export default { + plugins: [] + } + `, + `import * as somethingelse from 'gs'; + // import { sentryVitePlugin } from "@sentry/bundler-plugins/vite" + export default { + plugins: [] + } + `, + `import * as thirdPartyVitePlugin from "vite-plugin-@sentry" + export default { + plugins: [thirdPartyVitePlugin()] + } + `, + ])( + "returns false if the file doesn't contain any require('@sentry/') calls", + (code) => { + // recast.parse returns a Program node (or fails) but it's badly typed as any + const program = recast.parse(code) + .program as recast.types.namedTypes.Program; + expect(hasSentryContent(program)).toBe(false); + }, + ); +}); + +describe("getObjectProperty", () => { + it.each([ + [ + "literal", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty( + b.stringLiteral("needle"), + b.stringLiteral("haystack"), + ), + ]), + ], + [ + "stringLiteral", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.literal("needle"), b.stringLiteral("haystack")), + ]), + ], + [ + "identifier", + b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]), + ], + ])("returns the poperty (%s) if it exists", (_, object) => { + const property = getObjectProperty(object, "needle"); + expect(property).toBeDefined(); + // @ts-expect-error we know it's defined due to the expect above + expect(recast.print(property).code).toEqual( + expect.stringContaining("needle"), + ); + }); + + it("returns undefined if the property does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); + + it("handles objects without simple properties", () => { + const object = b.objectExpression([b.spreadElement(b.identifier("foo"))]); + const property = getObjectProperty(object, "needle"); + expect(property).toBeUndefined(); + }); +}); + +describe("getOrSetObjectProperty", () => { + it("returns the property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("nope"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("ObjectProperty"); + // @ts-expect-error we know its type + expect(property.key.name).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); + + it("adds the property if it does not exist", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + const property = getOrSetObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + ); + + expect(property).toBeDefined(); + expect(property.type).toBe("Property"); + // @ts-expect-error we know its type + expect(property.key.value).toBe("needle"); + // @ts-expect-error we know its type + expect(property.value.value).toBe("haystack"); + }); +}); + +describe("setOrUpdateObjectProperty", () => { + it("sets a new property if it does not exist yet", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack")); + + expect(getObjectProperty(object, "needle")).toBeDefined(); + }); + + it("updates an existing property if it exists", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + b.objectProperty(b.identifier("needle"), b.stringLiteral("haystack")), + ]); + + setOrUpdateObjectProperty(object, "needle", b.stringLiteral("haystack2")); + + const property = getObjectProperty(object, "needle"); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.value.value).toBe("haystack2"); + }); + + it("adds a comment to the existing property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); + + it("adds a comment to the new property if provided", () => { + const object = b.objectExpression([ + b.objectProperty(b.identifier("foo"), b.stringLiteral("bar")), + ]); + + setOrUpdateObjectProperty( + object, + "needle", + b.stringLiteral("haystack"), + "This is a comment", + ); + + const property = getObjectProperty(object, "needle"); + expect(property?.comments).toHaveLength(1); + // @ts-expect-error it must be defiend, otherwise we fail anyway + expect(property?.comments[0].value).toBe(" This is a comment"); + }); +}); + +describe("preserveTrailingNewline", () => { + it("adds trailing newline if original had one but generated does not", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not add trailing newline if original did not have one", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;"; + expect(preserveTrailingNewline(original, generated)).toBe("const foo = 1;"); + }); + + it("does not double trailing newline if both already have one", () => { + const original = "const foo = 1;\n"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); + + it("does not remove trailing newline if original did not have one but generated does", () => { + const original = "const foo = 1;"; + const generated = "const foo = 1;\n"; + expect(preserveTrailingNewline(original, generated)).toBe( + "const foo = 1;\n", + ); + }); +}); + +describe("parse and print JSON-C", () => { + it.each([ + ["simple JSON", "{'foo': 'bar'}"], + [ + "JSON-C with inline comment", + ` + { + "foo": "bar" // with an inline comment + } + `, + ], + [ + "JSON-C with multiple comments", + ` + /* + * let's throw in a block comment for good measure + */ + { + // one line comment + "foo": "bar", // another inline comment + /* one more here */ + "dogs": /* and here */ "awesome", + } + /* and here */ + `, + ], + ])(`parses and prints JSON-C (%s)`, (_, json) => { + const { ast, jsonObject } = parseJsonC(json); + expect(ast?.type).toBe("Program"); + expect(jsonObject).toBeDefined(); + expect(jsonObject?.type).toBe("ObjectExpression"); + // @ts-expect-error we know it's defined due to the expect above + expect(printJsonC(ast)).toEqual(json); + }); + + it("returns undefined if the input is not valid JSON-C", () => { + const { ast, jsonObject } = parseJsonC(`{ + "invalid": // "json" + }`); + expect(ast).toBeUndefined(); + expect(jsonObject).toBeUndefined(); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 363032cd0d..aa38f64862 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -759,6 +759,9 @@ importers: '@vitest/coverage-v8': specifier: 'catalog:' version: 5.0.5(vitest@5.0.5) + ast-types: + specifier: ^0.16.3 + version: 0.16.3 binpatch: specifier: ^0.4.2 version: 0.4.2 @@ -822,6 +825,9 @@ importers: qrcode-terminal: specifier: ^0.12.0 version: 0.12.0 + recast: + specifier: ^0.23.21 + version: 0.23.21 semver: specifier: ^7.8.5 version: 7.8.5 From 0113841962a00723228ae9299ee17ac663191c81 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:11:49 +0000 Subject: [PATCH 03/18] feat(cli): reject the wizard's removed sign-up flags `sentry wizard` logs in with the CLI's login, which has no sign-up or partner step, so `--signup`, `--promo-code` and `--coming-from` no longer do anything. Passing one now fails with a message that points to https://sentry.io/signup/ instead of being accepted silently. `promoCode` and `comingFrom` leave `WizardOptions`, the welcome banner and `setupCI`, which loses its Vercel partner branch. The help text and the docs say which `@sentry/wizard` flags were removed. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 9 ++- .../skills/sentry-cli/references/wizard.md | 1 - packages/cli/src/commands/wizard.ts | 58 ++++++++++++++----- .../src/lib/wizard/nextjs/nextjs-wizard.ts | 7 +-- packages/cli/src/lib/wizard/sourcemaps/ci.ts | 14 +---- .../cli/src/lib/wizard/utils/clack/index.ts | 5 -- packages/cli/src/lib/wizard/utils/types.ts | 13 ----- packages/cli/test/commands/wizard.test.ts | 24 +++++++- 8 files changed, 77 insertions(+), 54 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 1e49305bdb..d754b8845b 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -20,5 +20,10 @@ changes nothing. `sentry wizard` takes the same integrations and flags as `npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and -`sentry wizard -i nextjs` do the same thing. The Cordova and Electron wizards -were removed; follow their setup guides in the Sentry docs instead. +`sentry wizard -i nextjs` do the same thing. These were removed: + +- The sign-up flags `--signup`, `--promo-code` and `--coming-from`. Passing one + fails with an explanation. Sign up at https://sentry.io/signup/ (and apply a + promo code there), then run the wizard. +- The Cordova and Electron wizards. Follow their setup guides in the Sentry + docs instead. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 37be843225..7e8405f3e0 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -26,7 +26,6 @@ Set up the Sentry SDK in your project interactively - `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` - `--disable-telemetry - Don't send telemetry about this run to Sentry` - `--debug - Print the wizard's debug output` -- `--promo-code - Promo code to apply when signing up` **Examples:** diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index b48e6a6d2e..2b291ef787 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -20,7 +20,7 @@ import { parseUrl, } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; -import { WizardExitError } from "../lib/errors.js"; +import { ValidationError, WizardExitError } from "../lib/errors.js"; import { disableTelemetryForRun, isTelemetryEnabled, @@ -39,14 +39,39 @@ type WizardFlags = { readonly "disable-telemetry": boolean; readonly "force-install": boolean; readonly "ignore-git-changes": boolean; + readonly signup: boolean; readonly "promo-code"?: string; readonly "coming-from"?: string; - readonly signup: boolean; readonly "skip-connect": boolean; readonly quiet: boolean; readonly uninstall: boolean; }; +/** + * Fail on the `@sentry/wizard` sign-up and partner flags, which `sentry + * wizard` dropped: it logs in with the CLI's login, which has no sign-up or + * partner step. + * + * @throws {ValidationError} When one of them is passed + */ +function rejectRemovedFlags(flags: WizardFlags): void { + const removed = [ + flags.signup ? "--signup" : undefined, + flags["promo-code"] === undefined ? undefined : "--promo-code", + flags["coming-from"] === undefined ? undefined : "--coming-from", + ].filter((flag) => flag !== undefined); + if (removed.length === 0) { + return; + } + throw new ValidationError( + `${removed.join(", ")} ${removed.length === 1 ? "is" : "are"} no longer supported. ` + + "Sign up at https://sentry.io/signup/ (and apply any promo code there), " + + "then run the wizard again without " + + `${removed.length === 1 ? "it" : "them"}.`, + removed[0], + ); +} + /** The trimmed value of the environment variable `name`, unless empty. */ function envValue(name: string): string | undefined { return getEnv()[name]?.trim() || undefined; @@ -63,8 +88,10 @@ export const wizardCommand = buildCommand({ "uploads. It logs in with your `sentry auth login` account (or starts " + "a login), and lets you pick or create the Sentry project to send " + "data to.\n\n" + - "Pass `-i` to skip the integration picker. These are the same " + - "integrations and flags `npx @sentry/wizard` takes.\n\n" + + "Pass `-i` to skip the integration picker. It takes the same " + + "integrations and flags as `npx @sentry/wizard`, except the sign-up " + + "flags `--signup`, `--promo-code` and `--coming-from`, which fail: " + + "sign up at https://sentry.io/signup/ first.\n\n" + "The wizard changes files in your project. To have a coding agent set " + "up Sentry instead, run `sentry init`, which prints the agent's setup " + "guide and changes nothing.", @@ -143,29 +170,33 @@ export const wizardCommand = buildCommand({ brief: "Print the wizard's debug output", default: false, }, + // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in + // with the CLI's login, which has no sign-up or partner step, so these + // fail with an explanation instead of being dropped silently. + signup: { + kind: "boolean", + brief: "Removed: sign up at https://sentry.io/signup/ first", + default: false, + hidden: true as const, + }, "promo-code": { kind: "parsed", parse: parseText, - brief: "Promo code to apply when signing up", + brief: "Removed: apply promo codes when you sign up", placeholder: "code", optional: true, + hidden: true as const, }, "coming-from": { kind: "parsed", parse: parseText, - brief: "Partner the command was copied from, such as vercel", + brief: "Removed: partner sign-up is not supported", placeholder: "partner", optional: true, hidden: true as const, }, // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so // copied commands still run. - signup: { - kind: "boolean", - brief: "Ignored: the login page offers sign-up", - default: false, - hidden: true as const, - }, "skip-connect": { kind: "boolean", brief: "Ignored", @@ -189,6 +220,7 @@ export const wizardCommand = buildCommand({ }, // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. async *func(this: SentryContext, flags: WizardFlags) { + rejectRemovedFlags(flags); if (flags["disable-telemetry"]) { disableTelemetryForRun(); } @@ -199,13 +231,11 @@ export const wizardCommand = buildCommand({ debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", wizardOptions: { telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), - promoCode: flags["promo-code"], url: flags.url ?? envValue("SENTRY_WIZARD_URL"), orgSlug: flags.org, projectSlug: flags.project, saas: flags.saas, forceInstall: flags["force-install"], - comingFrom: flags["coming-from"], ignoreGitChanges: flags["ignore-git-changes"], spotlight: flags.spotlight, }, diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index ef8e11b357..fd14f9bb03 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -104,11 +104,10 @@ export function runNextjsWizard(options: WizardOptions) { export async function runNextjsWizardWithTelemetry( options: WizardOptions, ): Promise { - const { promoCode, telemetryEnabled, forceInstall } = options; + const { telemetryEnabled, forceInstall } = options; printWelcome({ wizardName: "Sentry Next.js Wizard", - promoCode, telemetryEnabled, }); @@ -483,13 +482,13 @@ The wizard will import ${chalk.cyan( path.join(process.cwd(), "vercel.json"), ); - if (mightBeUsingVercel && !options.comingFrom) { + if (mightBeUsingVercel) { clack.log.info( "▲ It seems like you're using Vercel. We recommend using the Sentry Vercel \ integration to set up an auth token for Vercel deployments: https://vercel.com/integrations/sentry", ); } else if (!spotlight) { - await setupCI("nextjs", authToken, options.comingFrom); + await setupCI("nextjs", authToken); } const packageManagerForOutro = diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index e725f44a51..ed73aa32c4 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -13,7 +13,6 @@ import { SENTRY_DOT_ENV_FILE, } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; -import type { WizardOptions } from "../utils/types.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -25,25 +24,16 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ /** * Ask whether the user builds in CI and, if so, show the auth token to set - * there. Skipped for partner flows (Vercel) that already set the token. + * there. * * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file - * @param comingFrom - The partner the command came from (`--coming-from`) */ export async function setupCI( selectedTool: string, authToken: string, - comingFrom: WizardOptions["comingFrom"], ): Promise { - if (comingFrom === "vercel") { - clack.log.info( - "Sentry Vercel integration is already configured. Skipping CI setup.", - ); - Sentry.setTag("using-ci", true); - } else { - await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); - } + await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); } /** Ask about CI and show the auth token to set there. */ diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index fd740e4b6e..0bdb01dc8c 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -151,7 +151,6 @@ export async function abortIfCancelled( /** Print the intro banner and welcome note of a wizard. */ export function printWelcome(options: { wizardName: string; - promoCode?: string | undefined; message?: string | undefined; telemetryEnabled?: boolean | undefined; }): void { @@ -162,10 +161,6 @@ export function printWelcome(options: { options.message || `The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`; - if (options.promoCode) { - welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`; - } - welcomeText = `${welcomeText}\n\nVersion: ${CLI_VERSION}`; if (options.telemetryEnabled) { diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts index b7b267c44e..d349678578 100644 --- a/packages/cli/src/lib/wizard/utils/types.ts +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -26,12 +26,6 @@ export type WizardOptions = { */ telemetryEnabled: boolean; - /** - * The promo code to use while signing up for Sentry. - * This can be passed via the --promo-code arg. - */ - promoCode?: string | undefined; - /** * The url of the Sentry instance to use. * This can be passed via the `-u` or `--url` arg. @@ -73,13 +67,6 @@ export type WizardOptions = { */ forceInstall?: boolean | undefined; - /** - * Used when the wizard command is copied from partner sites (e.g. Vercel) - * to display login/signup instructions specific to organizations provisioned - * through the partner. - */ - comingFrom?: string | undefined; - /** * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. */ diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index f320f998b9..46be02ce14 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -72,23 +72,41 @@ describe("sentry wizard", () => { "force-install": true, "ignore-git-changes": true, "disable-telemetry": true, - "coming-from": "vercel", }); expect(runNextjsWizard).toHaveBeenCalledWith({ telemetryEnabled: false, - promoCode: undefined, url: "https://sentry.example.com", orgSlug: "acme", projectSlug: "web", saas: false, forceInstall: true, - comingFrom: "vercel", ignoreGitChanges: true, spotlight: true, }); }); + test.each([ + [{ signup: true }, "--signup is no longer supported."], + [{ "promo-code": "PROMO" }, "--promo-code is no longer supported."], + [{ "coming-from": "vercel" }, "--coming-from is no longer supported."], + [ + { signup: true, "promo-code": "PROMO" }, + "--signup, --promo-code are no longer supported.", + ], + ])("rejects the removed sign-up flags %o", async (flags, message) => { + const error = await runWizardCommand({ integration: "nextjs", ...flags }) + .then(() => undefined) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ValidationError); + expect((error as ValidationError).message).toContain(message); + expect((error as ValidationError).message).toContain( + "https://sentry.io/signup/", + ); + expect(runNextjsWizard).not.toHaveBeenCalled(); + }); + test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); From 39e20d513acc8f5c30e2611396fad46aa89bdac7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:10:45 +0000 Subject: [PATCH 04/18] fix(cli): address review findings in sentry wizard - Skip the `.sentryclirc` URL check, like `sentry init`: the wizard picks its instance (`--url`, `--saas` or a prompt) before it logs in. - Use the stored login's instance for `sentryUrl` when none was chosen, and log in again when the stored login is for another instance. - Link self-hosted users to `/settings//auth-tokens/`. - Leave an unparseable MCP config alone (show the copy-paste fallback), and let a cancel inside the MCP setup stop the wizard. - Resolve `catalog:` and `catalog:default` against both pnpm default catalog forms. - Find an existing `SENTRY_AUTH_TOKEN` after the comment header of `.env.sentry-build-plugin`, so re-runs don't add a second one. - Run Windows formatters with Node in the standalone binary, where `process.execPath` is `sentry`. - Ask before updating an `@sentry/nextjs` listed in devDependencies, and treat an unknown SDK version as the `^11` the wizard installs. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/commands/wizard.ts | 3 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 5 +- .../cli/src/lib/wizard/utils/clack/index.ts | 28 ++--- .../src/lib/wizard/utils/clack/mcp-config.ts | 22 +++- .../cli/src/lib/wizard/utils/package-json.ts | 12 ++- .../cli/src/lib/wizard/utils/project-data.ts | 16 ++- .../lib/wizard/utils/clack/mcp-config.test.ts | 101 ++++++++++++------ .../lib/wizard/utils/package-json.test.ts | 18 ++++ .../lib/wizard/utils/project-data.test.ts | 72 ++++++++++++- 9 files changed, 211 insertions(+), 66 deletions(-) diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 2b291ef787..71f4b7fefd 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -79,6 +79,9 @@ function envValue(name: string): string | undefined { export const wizardCommand = buildCommand({ auth: false, + // The wizard picks the Sentry instance itself (`--url`, `--saas` or a + // prompt) before it logs in, like `sentry init`. + skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), fullDescription: diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index fd14f9bb03..cb02e11492 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -155,7 +155,7 @@ The wizard will continue, but you may need to upgrade Next.js for the SDK to wor await installPackage({ packageName: "@sentry/nextjs@^11", packageNameDisplayLabel: "@sentry/nextjs", - alreadyInstalled: !!packageJson.dependencies?.["@sentry/nextjs"], + alreadyInstalled: sdkAlreadyInstalled, forceInstall, }); @@ -185,7 +185,8 @@ The wizard will import ${chalk.cyan( // From v11 on, the SDK collects rich context by default, so offer to // reduce collection of data that can identify users. const reduceDataCollection = - sdkSupportsDataCollection(installedSdkVersion, "^10.73.0") && + // An unknown version (e.g. `workspace:*`) is the `^11` the wizard asked for. + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); let selectedProject: SentryProjectData; diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index 0bdb01dc8c..a076b5049b 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -24,6 +24,7 @@ import { sentry } from "../../../app-identity.js"; import { CLI_VERSION } from "../../../constants.js"; import { reportCliError } from "../../../error-reporting.js"; import { WizardExitError } from "../../../errors.js"; +import { isSea } from "../../../react-native/wrap-call.js"; import { Sentry, traceStep } from "../../telemetry.js"; import { debug } from "../debug.js"; import { getUncommittedOrUntrackedFilePaths, isInGitRepo } from "../git.js"; @@ -717,9 +718,7 @@ SENTRY_AUTH_TOKEN=${authToken} if (dotEnvFileExists) { const dotEnvFileContent = readFileSync(dotEnvFilePath, "utf8"); - const hasAuthToken = !!dotEnvFileContent.match( - /^\s*SENTRY_AUTH_TOKEN\s*=/g, - ); + const hasAuthToken = /^\s*SENTRY_AUTH_TOKEN\s*=/m.test(dotEnvFileContent); if (hasAuthToken) { clack.log.warn( @@ -887,7 +886,9 @@ function runFormatterCommand( new Error(`Could not resolve the ${packageName} binary.`), ); } - command = process.execPath; + // In the standalone binary, `process.execPath` is `sentry` itself, not + // Node, so run the formatter with the project's Node. + command = isSea() ? "node" : process.execPath; args = [binPath, ...subArgs, "--", ...files]; } else { command = "npx"; @@ -1265,16 +1266,15 @@ export async function getPackageManager( return fallback; } - const selectedPackageManager: PackageManager | symbol = - await abortIfCancelled( - clack.select({ - message: "Please select your package manager.", - options: packageManagers.map((packageManager) => ({ - value: packageManager, - label: packageManager.label, - })), - }), - ); + const selectedPackageManager = await abortIfCancelled( + clack.select({ + message: "Please select your package manager.", + options: packageManagers.map((packageManager) => ({ + value: packageManager, + label: packageManager.label, + })), + }), + ); globalWithSentryWizard.__sentry_wizard_cached_package_manager = selectedPackageManager; diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index 867c9c0140..0d01374036 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -10,6 +10,7 @@ import { Sentry } from "../../telemetry.js"; import chalk from "chalk"; import { clack } from "./prompts.js"; import { abortIfCancelled, showCopyPasteInstructions } from "./index.js"; +import { WizardExitError } from "../../../errors.js"; import { debug } from "../debug.js"; const SENTRY_MCP_BASE_URL = "https://mcp.sentry.dev/mcp"; @@ -48,14 +49,23 @@ function ensureDir(dirpath: string): void { mkdirSync(dirpath, { recursive: true }); } +/** + * The parsed JSON in `filepath`, or `null` when the file doesn't exist. + * + * @throws {SyntaxError} When the file exists but isn't valid JSON, so the + * caller shows the copy-paste fallback instead of overwriting it + */ async function readJsonIfExists(filepath: string): Promise { + let txt: string; try { - const txt = await promises.readFile(filepath, "utf8"); - return JSON.parse(txt) as unknown; + txt = await promises.readFile(filepath, "utf8"); } catch (error) { - debug(error); - return null; + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; } + return JSON.parse(txt) as unknown; } async function writeJson(filepath: string, obj: unknown): Promise { @@ -600,6 +610,10 @@ export async function offerProjectScopedMcpConfig( } Sentry.setTag(`mcp-config-${editor}-success`, true); } catch (e) { + if (e instanceof WizardExitError) { + throw e; + } + debug(e); Sentry.setTag(`mcp-config-${editor}-success`, false); Sentry.setTag("mcp-config-fallback", true); clack.log.warn( diff --git a/packages/cli/src/lib/wizard/utils/package-json.ts b/packages/cli/src/lib/wizard/utils/package-json.ts index 1de6728d35..775d4f8212 100644 --- a/packages/cli/src/lib/wizard/utils/package-json.ts +++ b/packages/cli/src/lib/wizard/utils/package-json.ts @@ -135,10 +135,14 @@ function resolveCatalogVersion( return undefined; } - const catalog = - catalogName === "" ? workspace.catalog : workspace.catalogs?.[catalogName]; - - return catalog?.[packageName]; + // pnpm treats `catalog:` and `catalogs.default` as the same catalog. + if (catalogName === "" || catalogName === "default") { + return ( + workspace.catalog?.[packageName] ?? + workspace.catalogs?.["default"]?.[packageName] + ); + } + return workspace.catalogs?.[catalogName]?.[packageName]; } /** diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 87718dcbb9..0e4b856c32 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -42,8 +42,12 @@ import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; -import { getSentryBaseUrl, isSentrySaasUrl } from "../../sentry-urls.js"; -import { registerLoginTrustAnchor } from "../../token-host.js"; +import { isSentrySaasUrl } from "../../sentry-urls.js"; +import { getApiBaseUrl } from "../../sentry-client.js"; +import { + isRequestOriginTrusted, + registerLoginTrustAnchor, +} from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -130,7 +134,8 @@ export async function getOrAskForProjectData( ); const handoffOrg = await traceStep("login", ensureLoggedIn); - const sentryUrl = withTrailingSlash(getSentryBaseUrl()); + // The chosen instance, or the stored login's when none was chosen. + const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); @@ -261,7 +266,8 @@ async function ensureLoggedIn(): Promise { return handoff.organizationSlug; } - if (getAuthConfig()) { + // A login for another instance than the selected one can't be used. + if (getAuthConfig() && isRequestOriginTrusted(getApiBaseUrl())) { Sentry.setTag("login-method", "stored"); return; } @@ -464,7 +470,7 @@ async function createAuthToken( Sentry.setTag("auth-token-created", false); const settingsUrl = isSentrySaasUrl(sentryUrl) ? `https://${orgSlug}.sentry.io/settings/auth-tokens/` - : `${sentryUrl}organizations/${orgSlug}/settings/auth-tokens/`; + : `${sentryUrl}settings/${orgSlug}/auth-tokens/`; clack.log.warn( `Could not create an auth token for you. We'll add a placeholder (${chalk.cyan( `"${DUMMY_AUTH_TOKEN}"`, diff --git a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts index af614d9793..2a83ff5028 100644 --- a/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts +++ b/packages/cli/test/lib/wizard/utils/clack/mcp-config.test.ts @@ -13,8 +13,16 @@ import * as fs from "node:fs"; import * as path from "node:path"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking import * as childProcess from "node:child_process"; +import { WizardExitError } from "../../../../../src/lib/errors.js"; import { offerProjectScopedMcpConfig } from "../../../../../src/lib/wizard/utils/clack/mcp-config.js"; +/** The error `fs.promises.readFile` rejects with for a missing file. */ +function fileNotFound(): NodeJS.ErrnoException { + return Object.assign(new Error("ENOENT: no such file or directory"), { + code: "ENOENT", + }); +} + // Mock types for better type safety type ConfigContent = { mcpServers?: Record; @@ -115,9 +123,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -164,9 +170,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -196,9 +200,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -349,9 +351,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -435,9 +435,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -462,7 +460,7 @@ describe("mcp-config", () => { ); }); - it("should handle file write errors gracefully for Cursor", async () => { + it("shows the fallback instead of overwriting an unparseable config", async () => { const { clack, clackUtils } = await getMocks(); vi.mocked(clack.select).mockResolvedValueOnce("yes"); @@ -473,7 +471,52 @@ describe("mcp-config", () => { const mockReadFile = vi .fn() - .mockRejectedValue(new Error("File not found")); + .mockResolvedValue('{ "mcpServers": { "OtherServer": {}, } }'); + const mockWriteFile = vi.fn().mockResolvedValue(undefined); + + vi.spyOn(fs.promises, "readFile").mockImplementation(mockReadFile); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await offerProjectScopedMcpConfig(); + + expect(mockWriteFile).not.toHaveBeenCalled(); + expect(clackUtils.showCopyPasteInstructions).toHaveBeenCalledWith( + expect.objectContaining({ filename: path.join(".cursor", "mcp.json") }), + ); + }); + + it("lets a WizardExitError from an editor's setup stop the wizard", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor", "vscode"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockWriteFile = vi.fn().mockRejectedValue(new WizardExitError(0)); + vi.spyOn(fs.promises, "readFile").mockRejectedValue(fileNotFound()); + vi.spyOn(fs.promises, "writeFile").mockImplementation(mockWriteFile); + vi.spyOn(fs, "mkdirSync").mockImplementation(vi.fn()); + + await expect(offerProjectScopedMcpConfig()).rejects.toThrow( + WizardExitError, + ); + expect(mockWriteFile).toHaveBeenCalledTimes(1); + expect(clackUtils.showCopyPasteInstructions).not.toHaveBeenCalled(); + }); + + it("should handle file write errors gracefully for Cursor", async () => { + const { clack, clackUtils } = await getMocks(); + + vi.mocked(clack.select).mockResolvedValueOnce("yes"); + vi.mocked(clack.multiselect).mockResolvedValueOnce(["cursor"]); + vi.mocked(clackUtils.abortIfCancelled).mockImplementation( + (value: unknown) => Promise.resolve(value), + ); + + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -507,9 +550,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -539,9 +580,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockRejectedValue(new Error("Permission denied")); @@ -608,9 +647,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn().mockImplementation(() => { throw new Error("Permission denied"); @@ -823,9 +860,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -944,9 +979,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi.fn().mockResolvedValue(undefined); const mockMkdirSync = vi.fn(); @@ -1015,9 +1048,7 @@ describe("mcp-config", () => { (value: unknown) => Promise.resolve(value), ); - const mockReadFile = vi - .fn() - .mockRejectedValue(new Error("File not found")); + const mockReadFile = vi.fn().mockRejectedValue(fileNotFound()); const mockWriteFile = vi .fn() .mockResolvedValueOnce(undefined) // Cursor succeeds diff --git a/packages/cli/test/lib/wizard/utils/package-json.test.ts b/packages/cli/test/lib/wizard/utils/package-json.test.ts index f04f2f9fd4..51845812e1 100644 --- a/packages/cli/test/lib/wizard/utils/package-json.test.ts +++ b/packages/cli/test/lib/wizard/utils/package-json.test.ts @@ -123,6 +123,24 @@ catalog: expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); }); + it.each([ + ["catalog:default", "catalog:\n '@sentry/node': ^7.100.0\n"], + ["catalog:", "catalogs:\n default:\n '@sentry/node': ^7.100.0\n"], + ])("resolves %s against either default catalog form", (ref, yaml) => { + mockedFs.existsSync.mockImplementation((filepath: string) => { + return ( + filepath === path.join("/test/workspace", "pnpm-workspace.yaml") + ); + }); + mockedFs.readFileSync.mockReturnValue(yaml); + + const packageJson: PackageDotJson = { + dependencies: { "@sentry/node": ref }, + }; + + expect(getPackageVersion("@sentry/node", packageJson)).toBe("^7.100.0"); + }); + it("resolves named catalog reference", () => { mockedFs.existsSync.mockImplementation((filepath: string) => { return ( diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index a691410ee2..152d7adb29 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -19,6 +19,9 @@ const mocks = vi.hoisted(() => ({ createOrgAuthToken: vi.fn(), select: vi.fn(), text: vi.fn(), + isRequestOriginTrusted: vi.fn(), + getApiBaseUrl: vi.fn(), + warn: vi.fn(), })); vi.mock("@clack/prompts", () => ({ @@ -31,10 +34,23 @@ vi.mock("@clack/prompts", () => ({ log: { info: vi.fn(), step: vi.fn(), - warn: vi.fn(), + warn: mocks.warn, error: vi.fn(), }, })); +// The stored login (`getAuthConfig`) is mocked, so its host check is too. +vi.mock("../../../../src/lib/token-host.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/token-host.js") + >()), + isRequestOriginTrusted: mocks.isRequestOriginTrusted, +})); +vi.mock("../../../../src/lib/sentry-client.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../../../src/lib/sentry-client.js") + >()), + getApiBaseUrl: mocks.getApiBaseUrl, +})); vi.mock("../../../../src/lib/db/auth.js", async (importOriginal) => ({ ...(await importOriginal()), getAuthConfig: mocks.getAuthConfig, @@ -87,10 +103,15 @@ const KEY = { dsn: { public: "https://abc@o1.ingest.sentry.io/42", secret: "" }, }; -beforeEach(() => { +beforeEach(async () => { vi.clearAllMocks(); + const actualClient = await vi.importActual< + typeof import("../../../../src/lib/sentry-client.js") + >("../../../../src/lib/sentry-client.js"); + mocks.getApiBaseUrl.mockImplementation(actualClient.getApiBaseUrl); vi.stubEnv("SENTRY_HANDOFF", ""); mocks.getAuthConfig.mockReturnValue({ token: "stored" }); + mocks.isRequestOriginTrusted.mockReturnValue(true); mocks.listOrganizations.mockResolvedValue([ORG]); mocks.getProject.mockResolvedValue(PROJECT); mocks.getProjectKeys.mockResolvedValue([KEY]); @@ -236,6 +257,53 @@ describe("getOrAskForProjectData", () => { ).rejects.toThrow(WizardExitError); }); + it("logs in again when the stored login is for another instance", async () => { + mocks.isRequestOriginTrusted.mockReturnValueOnce(false); + mocks.runInteractiveLogin.mockResolvedValue({ method: "oauth" }); + + await getOrAskForProjectData({ + telemetryEnabled: false, + url: "https://sentry.example.com", + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).toHaveBeenCalled(); + }); + + it("uses the stored login's instance when none is chosen", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + sentryUrl: "https://sentry.example.com/", + selfHosted: true, + }); + }); + + it("links to the self-hosted auth token settings when it can't create one", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + mocks.createOrgAuthToken.mockRejectedValue(new Error("forbidden")); + + await getOrAskForProjectData({ + telemetryEnabled: false, + orgSlug: "acme", + projectSlug: "web", + }); + + expect(mocks.warn).toHaveBeenCalledWith( + expect.stringContaining( + "https://sentry.example.com/settings/acme/auth-tokens/", + ), + ); + }); + it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); From 2c987511447e235888f3773f3599aaf82d742b54 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:01:23 +0000 Subject: [PATCH 05/18] refactor(cli): reuse existing CLI helpers in the wizard AST utils Address review feedback on the shared wizard helpers: - Enable unicorn/no-array-for-each repo-wide and convert every .forEach call site to for...of, including getLastRequireIndex. - Add buildProjectIssuesUrl to lib/sentry-urls.ts, built on getOrgBaseUrl like buildEventSearchUrl, and delete the wizard-specific wizard/utils/url.ts. - Move findFile into lib/dsn/fs-utils.ts and build it on isRegularFile, so a directory or FIFO with a matching name is skipped. It is async now. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxlintrc.json | 1 + apps/games-api/src/leaderboard.test.ts | 4 +- apps/local/src/lib/profile-session.ts | 14 +++--- packages/cli/src/commands/api.ts | 4 +- packages/cli/src/lib/db/completion-cache.ts | 4 +- packages/cli/src/lib/dsn/errors.ts | 4 +- packages/cli/src/lib/dsn/fs-utils.ts | 22 ++++++++++ packages/cli/src/lib/formatters/alerts.ts | 8 ++-- packages/cli/src/lib/formatters/human.ts | 8 ++-- packages/cli/src/lib/games/snake-game.ts | 4 +- packages/cli/src/lib/select-ui/picker.ts | 4 +- packages/cli/src/lib/sentry-urls.ts | 18 ++++++++ packages/cli/src/lib/sixel-image.ts | 4 +- .../cli/src/lib/wizard/utils/ast-utils.ts | 19 +------- packages/cli/src/lib/wizard/utils/url.ts | 29 ------------- packages/cli/test/lib/api/traces.test.ts | 4 +- packages/cli/test/lib/dsn/fs-utils.test.ts | 43 ++++++++++++++++++- .../test/lib/sdk-positionals.property.test.ts | 4 +- .../cli/test/lib/sentry-urls.property.test.ts | 16 +++++++ .../cli/test/lib/wizard/nextjs/utils.test.ts | 4 +- packages/cli/test/mocks/server.ts | 4 +- .../client/components/chat/chat-messages.tsx | 38 ++++++++-------- packages/mcp-core/chart-app/chart.ts | 8 ++-- .../api-client/client-request-paths.test.ts | 6 +-- .../src/internal/issue-side-quests.test.ts | 8 ++-- packages/mcp-core/src/internal/side-quests.ts | 4 +- .../src/internal/source-map-diagnosis.ts | 8 ++-- .../src/tools/catalog/get-event-attachment.ts | 4 +- .../src/tools/support/profile/analyzer.ts | 8 ++-- .../support/profile/flamegraph-output.ts | 6 +-- .../tools/support/search-events/replays.ts | 4 +- .../src/tools/support/search-events/utils.ts | 21 ++++----- 32 files changed, 193 insertions(+), 144 deletions(-) delete mode 100644 packages/cli/src/lib/wizard/utils/url.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index ff2085d067..4304d7920f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -69,6 +69,7 @@ "typescript/no-useless-default-assignment": "error", "jsx-a11y/interactive-supports-focus": "off", "unicorn/prefer-spread": "error", + "unicorn/no-array-for-each": "error", "typescript/no-misused-promises": "error", "typescript/switch-exhaustiveness-check": [ "error", diff --git a/apps/games-api/src/leaderboard.test.ts b/apps/games-api/src/leaderboard.test.ts index 09b62a9838..cfd655cab1 100644 --- a/apps/games-api/src/leaderboard.test.ts +++ b/apps/games-api/src/leaderboard.test.ts @@ -179,7 +179,9 @@ describe("games leaderboard route", () => { "kk", "ll", ]; - names.forEach((n, i) => rows.push([`${n}-${n}-100${i % 10}`, 300 - i])); + for (const [i, n] of names.entries()) { + rows.push([`${n}-${n}-100${i % 10}`, 300 - i]); + } fetchMock.mockResolvedValue(jsonResponse(upstreamBody(rows))); const res = await app.request(PATH, REQ, makeEnv()); diff --git a/apps/local/src/lib/profile-session.ts b/apps/local/src/lib/profile-session.ts index f29d4ae532..2099a05dfb 100644 --- a/apps/local/src/lib/profile-session.ts +++ b/apps/local/src/lib/profile-session.ts @@ -128,8 +128,8 @@ export function mergeProfileChunks( const frameMap = new Map(), stackMap = new Map(); if (Array.isArray(profile["frames"])) - profile["frames"].forEach((frame, index) => { - if (!Object.keys(record(frame)).length) return; + for (const [index, frame] of profile["frames"].entries()) { + if (!Object.keys(record(frame)).length) continue; const key = profileValueKey(frame); let id = frameIds.get(key); if (id === undefined) { @@ -138,15 +138,15 @@ export function mergeProfileChunks( frameIds.set(key, id); } frameMap.set(index, id); - }); + } if (Array.isArray(profile["stacks"])) - profile["stacks"].forEach((stack, index) => { - if (!Array.isArray(stack)) return; + stacks: for (const [index, stack] of profile["stacks"].entries()) { + if (!Array.isArray(stack)) continue; const mapped: number[] = []; for (const frame of stack) { const id = typeof frame === "number" ? frameMap.get(frame) : undefined; - if (id === undefined) return; // Broken indexes cannot silently describe another frame. + if (id === undefined) continue stacks; // Broken indexes cannot silently describe another frame. mapped.push(id); } const key = JSON.stringify(mapped); @@ -157,7 +157,7 @@ export function mergeProfileChunks( stackIds.set(key, id); } stackMap.set(index, id); - }); + } const chunkThreads = new Map[]>(); if (Array.isArray(profile["samples"])) for (const value of profile["samples"]) { diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts index 3d2ff084d9..e6f7e0c03c 100644 --- a/packages/cli/src/commands/api.ts +++ b/packages/cli/src/commands/api.ts @@ -1487,9 +1487,9 @@ function logResponse(response: { log.debug( `< HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`, ); - response.headers.forEach((value, key) => { + for (const [key, value] of response.headers) { log.debug(`< ${key}: ${value}`); - }); + } log.debug("<"); } diff --git a/packages/cli/src/lib/db/completion-cache.ts b/packages/cli/src/lib/db/completion-cache.ts index 3cd00d3cb2..8236087027 100644 --- a/packages/cli/src/lib/db/completion-cache.ts +++ b/packages/cli/src/lib/db/completion-cache.ts @@ -114,7 +114,7 @@ export function cacheCompletionEntities( ) .get(kind, orgSlug) as { latest: number | null } | undefined; const now = Math.max(Date.now(), (latest?.latest ?? 0) + valid.length); - valid.forEach((entity, index) => { + for (const [index, entity] of valid.entries()) { runUpsert( db, "completion_cache", @@ -127,7 +127,7 @@ export function cacheCompletionEntities( }, ["kind", "org_slug", "value"], ); - }); + } db.query( `DELETE FROM completion_cache WHERE kind = ? AND org_slug = ? AND rowid NOT IN ( diff --git a/packages/cli/src/lib/dsn/errors.ts b/packages/cli/src/lib/dsn/errors.ts index 9ad83c3ce8..cccef4c341 100644 --- a/packages/cli/src/lib/dsn/errors.ts +++ b/packages/cli/src/lib/dsn/errors.ts @@ -22,14 +22,14 @@ import type { DsnDetectionResult } from "./types.js"; export function formatConflictError(result: DsnDetectionResult): string { const lines = ["Error: Multiple Sentry DSNs detected in this project.\n"]; - result.all.forEach((dsn, i) => { + for (const [i, dsn] of result.all.entries()) { lines.push(` DSN ${i + 1}: ${dsn.raw}`); lines.push(` Source: ${getDsnSourceDescription(dsn)}`); if (dsn.projectId) { lines.push(` Project ID: ${dsn.projectId}`); } lines.push(""); - }); + } lines.push("To resolve, specify which project to use:"); lines.push(` ${sentry` /`}`); diff --git a/packages/cli/src/lib/dsn/fs-utils.ts b/packages/cli/src/lib/dsn/fs-utils.ts index 9c954d0686..1c28aebffe 100644 --- a/packages/cli/src/lib/dsn/fs-utils.ts +++ b/packages/cli/src/lib/dsn/fs-utils.ts @@ -113,3 +113,25 @@ export async function isRegularFile( return false; } } + +/** + * Find the first of `basePath` + each extension that is a regular file, for + * config files whose extension isn't known yet (`next.config` → + * `next.config.mjs`). + * + * @param basePath - Path without the extension + * @param extensions - Extensions to try, in order, each with its leading dot + * @returns The first matching path, or undefined when none is a regular file + */ +export async function findFile( + basePath: string, + extensions: readonly string[] = [".js", ".ts", ".mjs", ".cjs"], +): Promise { + for (const extension of extensions) { + const candidate = `${basePath}${extension}`; + if (await isRegularFile(candidate, "findFile")) { + return candidate; + } + } + return undefined; +} diff --git a/packages/cli/src/lib/formatters/alerts.ts b/packages/cli/src/lib/formatters/alerts.ts index ecee154539..24e0171353 100644 --- a/packages/cli/src/lib/formatters/alerts.ts +++ b/packages/cli/src/lib/formatters/alerts.ts @@ -81,9 +81,9 @@ function conditionRows(value: unknown, detector: boolean): Row[] { const rows: Row[] = [["Logic", valueText(group["logicType"])]]; const conditions = group["conditions"]; if (Array.isArray(conditions) && conditions.length > 0) { - conditions.forEach((condition, index) => { + for (const [index, condition] of conditions.entries()) { rows.push([`Condition ${index + 1}`, conditionText(condition, detector)]); - }); + } } else { rows.push([ "Conditions", @@ -150,11 +150,11 @@ function workflowSections(workflow: GetOrganizationWorkflowResponse): string[] { ...workflowGroupSections(workflow.triggers, "Triggers"), ]; if (workflow.actionFilters?.length) { - workflow.actionFilters.forEach((group, index) => { + for (const [index, group] of workflow.actionFilters.entries()) { sections.push( ...workflowGroupSections(group, `Action filter ${index + 1}`), ); - }); + } } else { sections.push(table([["Action filters", "none"]])); } diff --git a/packages/cli/src/lib/formatters/human.ts b/packages/cli/src/lib/formatters/human.ts index 2ee356406a..e34818d542 100644 --- a/packages/cli/src/lib/formatters/human.ts +++ b/packages/cli/src/lib/formatters/human.ts @@ -1286,7 +1286,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { if (currentDepth < maxDepth) { const children = span.children ?? []; const childCount = children.length; - children.forEach((child, i) => { + for (const [i, child] of children.entries()) { formatSpanSimple(child, { lines, prefix: childPrefix, @@ -1294,7 +1294,7 @@ function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void { currentDepth: currentDepth + 1, maxDepth, }); - }); + } } } @@ -1367,7 +1367,7 @@ export function formatSimpleSpanTree( const displaySpans = truncated ? spans.slice(0, MAX_ROOT_SPANS) : spans; const displayCount = displaySpans.length; - displaySpans.forEach((span, i) => { + for (const [i, span] of displaySpans.entries()) { formatSpanSimple(span, { lines, prefix: "", @@ -1375,7 +1375,7 @@ export function formatSimpleSpanTree( currentDepth: 1, maxDepth: effectiveMaxDepth, }); - }); + } if (truncated) { const remaining = totalRootSpans - MAX_ROOT_SPANS; diff --git a/packages/cli/src/lib/games/snake-game.ts b/packages/cli/src/lib/games/snake-game.ts index b4b3f4c052..5be8d6628a 100644 --- a/packages/cli/src/lib/games/snake-game.ts +++ b/packages/cli/src/lib/games/snake-game.ts @@ -313,9 +313,9 @@ export function renderSnake( if (state.food) { cells[state.food.y * state.width + state.food.x] = FOOD; } - state.body.forEach((part, index) => { + for (const [index, part] of state.body.entries()) { cells[part.y * state.width + part.x] = index === 0 ? HEAD : BODY; - }); + } const lines: string[] = []; for (let row = 0; row < snakeTerminalRows(state.height); row++) { diff --git a/packages/cli/src/lib/select-ui/picker.ts b/packages/cli/src/lib/select-ui/picker.ts index 3e5a729799..7060a1a276 100644 --- a/packages/cli/src/lib/select-ui/picker.ts +++ b/packages/cli/src/lib/select-ui/picker.ts @@ -450,14 +450,14 @@ function renderPicker( const accent = chalk.hex(ACCENT); const lines = [""]; - titleLines.forEach((line, index) => { + for (const [index, line] of titleLines.entries()) { const icon = padIcon(index === 0 ? ICONS.diamondOpen : ""); const counter = index === 0 && isWindowed ? chalk.hex(MUTED_DIM)(` (${highlighted + 1}/${filtered.length})`) : ""; lines.push(`${accent.bold(icon)}${chalk.bold(line)}${counter}`); - }); + } lines.push(""); const optionLines = diff --git a/packages/cli/src/lib/sentry-urls.ts b/packages/cli/src/lib/sentry-urls.ts index 3e8dbd5072..902e2fcdc7 100644 --- a/packages/cli/src/lib/sentry-urls.ts +++ b/packages/cli/src/lib/sentry-urls.ts @@ -236,6 +236,24 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?query=event.id:${eventId}`; } +/** + * Build URL to a project's issue stream in Sentry. + * + * @param orgSlug - Organization slug + * @param projectId - Numeric project ID + * @returns Full URL to the issues list filtered to the project + */ +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + const project = encodeURIComponent(projectId); + if (isSaaS()) { + return `${getOrgBaseUrl(orgSlug)}/issues/?project=${project}`; + } + return `${getSentryBaseUrl()}/organizations/${orgSlug}/issues/?project=${project}`; +} + // Settings URLs /** diff --git a/packages/cli/src/lib/sixel-image.ts b/packages/cli/src/lib/sixel-image.ts index 30b175ac3d..a7ac0f3141 100644 --- a/packages/cli/src/lib/sixel-image.ts +++ b/packages/cli/src/lib/sixel-image.ts @@ -601,9 +601,9 @@ export function encodeImageToSixel( // DCS: P1=0 aspect, P2=1 (unpainted = transparent), P3=0 grid; then raster // attributes "1;1;W;H so the terminal reserves the right pixel box. let out = `\x1bP0;1;0q"1;1;${width};${height}`; - palette.forEach(([r, g, b], i) => { + for (const [i, [r, g, b]] of palette.entries()) { out += `#${i};2;${to100(r)};${to100(g)};${to100(b)}`; - }); + } const totalBands = Math.ceil(height / 6); for (let band = 0; band < totalBands; band++) { diff --git a/packages/cli/src/lib/wizard/utils/ast-utils.ts b/packages/cli/src/lib/wizard/utils/ast-utils.ts index 05929e5203..9bf504f456 100644 --- a/packages/cli/src/lib/wizard/utils/ast-utils.ts +++ b/packages/cli/src/lib/wizard/utils/ast-utils.ts @@ -3,8 +3,6 @@ * that edit JavaScript and TypeScript config files. */ -import { existsSync } from "node:fs"; - import recast from "recast"; import { debug } from "./debug.js"; @@ -12,19 +10,6 @@ import type { namedTypes as t } from "ast-types"; const b = recast.types.builders; -/** - * Checks if a file where we don't know its concrete file type yet exists - * and returns the full path to the file with the correct file type. - */ -export function findFile( - filePath: string, - fileTypes: string[] = [".js", ".ts", ".mjs", ".cjs"], -): string | undefined { - return fileTypes - .map((type) => `${filePath}${type}`) - .find((file) => existsSync(file)); -} - /** * checks for require('@sentry/*') syntax */ @@ -237,7 +222,7 @@ export function printJsonC(ast: t.Program): string { */ export function getLastRequireIndex(program: t.Program): number { let lastRequireIdex = -1; - program.body.forEach((s, i) => { + for (const [i, s] of program.body.entries()) { const declaration = s.type === "VariableDeclaration" ? s.declarations[0] : undefined; if ( @@ -248,7 +233,7 @@ export function getLastRequireIndex(program: t.Program): number { ) { lastRequireIdex = i; } - }); + } return lastRequireIdex; } diff --git a/packages/cli/src/lib/wizard/utils/url.ts b/packages/cli/src/lib/wizard/utils/url.ts deleted file mode 100644 index 6d3af99d64..0000000000 --- a/packages/cli/src/lib/wizard/utils/url.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Sentry URLs the wizards print after setup. - */ - -/** - * Returns the url to the Sentry project stream. - * - * Example: https://org-slug.sentry.io/issues/?project=1234567 - */ -export function getIssueStreamUrl({ - url, - orgSlug, - projectId, -}: { - url: string; - orgSlug: string; - projectId: string; -}): string { - const urlObject = new URL(url); - if (urlObject.host === "sentry.io") { - urlObject.host = `${orgSlug}.${urlObject.host}`; - urlObject.pathname = "/issues/"; - } else { - urlObject.pathname = `/organizations/${orgSlug}/issues/`; - } - urlObject.searchParams.set("project", projectId); - - return urlObject.toString(); -} diff --git a/packages/cli/test/lib/api/traces.test.ts b/packages/cli/test/lib/api/traces.test.ts index 1b7b0d06a2..2cdc4babac 100644 --- a/packages/cli/test/lib/api/traces.test.ts +++ b/packages/cli/test/lib/api/traces.test.ts @@ -594,9 +594,9 @@ describe("getSpanDetails", () => { const req = new Request(input, init); capturedUrl = req.url; const url = new URL(capturedUrl); - url.searchParams.forEach((v, k) => { + for (const [k, v] of url.searchParams) { capturedParams[k] = v; - }); + } return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" }, diff --git a/packages/cli/test/lib/dsn/fs-utils.test.ts b/packages/cli/test/lib/dsn/fs-utils.test.ts index a1b47c0da7..c637ac2761 100644 --- a/packages/cli/test/lib/dsn/fs-utils.test.ts +++ b/packages/cli/test/lib/dsn/fs-utils.test.ts @@ -5,6 +5,10 @@ * errors (ignored, debug-logged) from unexpected ones (reported to Sentry). */ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; const { reportCliError } = vi.hoisted(() => ({ @@ -16,7 +20,8 @@ vi.mock("@sentry/node", () => ({ startSpan: (_opts: unknown, fn: () => unknown) => fn(), })); -const { handleFileError } = await import("../../../src/lib/dsn/fs-utils.js"); +const { findFile, handleFileError } = + await import("../../../src/lib/dsn/fs-utils.js"); /** Create an Error with a `code` property, mimicking Node/Bun errno errors. */ function errnoError(code: string, message?: string): Error { @@ -184,3 +189,39 @@ describe("handleFileError", () => { }); }); }); + +describe("findFile", () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "find-file-")); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + test("returns the first extension that exists, in order", async () => { + await writeFile(join(dir, "next.config.mjs"), ""); + await writeFile(join(dir, "next.config.cjs"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.mjs"), + ); + }); + + test("skips a directory with a matching name", async () => { + await mkdir(join(dir, "next.config.js")); + await writeFile(join(dir, "next.config.ts"), ""); + + expect(await findFile(join(dir, "next.config"))).toBe( + join(dir, "next.config.ts"), + ); + }); + + test("returns undefined when no extension matches", async () => { + expect( + await findFile(join(dir, "vite.config"), [".js", ".ts"]), + ).toBeUndefined(); + }); +}); diff --git a/packages/cli/test/lib/sdk-positionals.property.test.ts b/packages/cli/test/lib/sdk-positionals.property.test.ts index 15b53cb35c..b1a45e503a 100644 --- a/packages/cli/test/lib/sdk-positionals.property.test.ts +++ b/packages/cli/test/lib/sdk-positionals.property.test.ts @@ -26,9 +26,9 @@ describe("positionals", () => { fcAssert( property(valuesArb, (values) => { const result = positionals(...values); - result.forEach((token, i) => { + for (const [i, token] of result.entries()) { expect(token).toBe(values[i] ?? ""); - }); + } }), { numRuns: DEFAULT_NUM_RUNS }, ); diff --git a/packages/cli/test/lib/sentry-urls.property.test.ts b/packages/cli/test/lib/sentry-urls.property.test.ts index 22027bdf10..1d4227b1ae 100644 --- a/packages/cli/test/lib/sentry-urls.property.test.ts +++ b/packages/cli/test/lib/sentry-urls.property.test.ts @@ -19,6 +19,7 @@ import { buildDashboardsListUrl, buildDashboardUrl, buildEventSearchUrl, + buildProjectIssuesUrl, buildLogsUrl, buildOrgSettingsUrl, buildOrgUrl, @@ -301,6 +302,21 @@ describe("buildEventSearchUrl properties", () => { }); }); +describe("buildProjectIssuesUrl", () => { + test("filters the org-subdomain issue stream to the project on SaaS", () => { + expect(buildProjectIssuesUrl("my-org", "1234567")).toBe( + "https://my-org.sentry.io/issues/?project=1234567", + ); + }); + + test("uses the organizations path on self-hosted", () => { + process.env["SENTRY_URL"] = "https://sentry.example.com"; + expect(buildProjectIssuesUrl("my-org", "42")).toBe( + "https://sentry.example.com/organizations/my-org/issues/?project=42", + ); + }); +}); + describe("buildOrgSettingsUrl properties", () => { test("without hash, output ends with trailing slash", async () => { fcAssert( diff --git a/packages/cli/test/lib/wizard/nextjs/utils.test.ts b/packages/cli/test/lib/wizard/nextjs/utils.test.ts index df026e57ed..cddd023814 100644 --- a/packages/cli/test/lib/wizard/nextjs/utils.test.ts +++ b/packages/cli/test/lib/wizard/nextjs/utils.test.ts @@ -89,13 +89,13 @@ describe("Next.js Utils", () => { const mockAppFolderPath = "/mock/app"; const supportedExtensions = ["jsx", "tsx", "js"]; - supportedExtensions.forEach((ext) => { + for (const ext of supportedExtensions) { (fs.existsSync as Mock).mockImplementation((filePath: string) => { return filePath === `/mock/app/layout.${ext}`; }); expect(hasRootLayoutFile(mockAppFolderPath)).toBe(true); - }); + } }); it("returns false when no layout file exists", () => { diff --git a/packages/cli/test/mocks/server.ts b/packages/cli/test/mocks/server.ts index 364b5b3f90..9e5b466d8c 100644 --- a/packages/cli/test/mocks/server.ts +++ b/packages/cli/test/mocks/server.ts @@ -69,12 +69,12 @@ function matchRoute( if (match) { const [, ...values] = match; const params: Record = {}; - route.paramNames.forEach((name, i) => { + for (const [i, name] of route.paramNames.entries()) { const value = values[i]; if (value !== undefined) { params[name] = value; } - }); + } return { route, params }; } } diff --git a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx index 9aedb5d575..242541ed7f 100644 --- a/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx +++ b/packages/mcp-cloudflare/src/client/components/chat/chat-messages.tsx @@ -24,34 +24,32 @@ function processMessages( // Only the very last text part of the very last message should be streaming const lastMessageIndex = messages.length - 1; - messages.forEach((message, messageIndex) => { + for (const [messageIndex, message] of messages.entries()) { const isLastMessage = messageIndex === lastMessageIndex; // Handle messages with parts array if (message.parts.length > 0) { const lastPartIndex = message.parts.length - 1; - message.parts.forEach( - (part: UIMessage["parts"][number], partIndex: number) => { - const isLastPartOfLastMessage = - isLastMessage && partIndex === lastPartIndex; + for (const [partIndex, part] of message.parts.entries()) { + const isLastPartOfLastMessage = + isLastMessage && partIndex === lastPartIndex; - allParts.push({ - part, - messageId: message.id, - messageRole: message.role, - partIndex, - // Stream if it's AI response OR local streaming simulation - isStreaming: - (isLastPartOfLastMessage && - isChatLoading && - part.type === "text") || - (part.type === "text" && !!isMessageStreaming?.(message.id)), - }); - }, - ); + allParts.push({ + part, + messageId: message.id, + messageRole: message.role, + partIndex, + // Stream if it's AI response OR local streaming simulation + isStreaming: + (isLastPartOfLastMessage && + isChatLoading && + part.type === "text") || + (part.type === "text" && !!isMessageStreaming?.(message.id)), + }); + } } - }); + } return allParts; } diff --git a/packages/mcp-core/chart-app/chart.ts b/packages/mcp-core/chart-app/chart.ts index 569d49cdd4..78c9f684ea 100644 --- a/packages/mcp-core/chart-app/chart.ts +++ b/packages/mcp-core/chart-app/chart.ts @@ -256,7 +256,7 @@ export function drawChart( const single = chart.series.length === 1; const path = (pts: readonly Point[]) => pts.map(([px, py], i) => `${i ? "L" : "M"}${px},${py}`).join(""); - chart.series.forEach((series, index) => { + for (const [index, series] of chart.series.entries()) { const color = SERIES_COLORS[index % SERIES_COLORS.length] ?? "#7553ff"; // Runs of buckets with data. A null bucket ends a run, so it draws as a // gap instead of a drop to 0. @@ -306,7 +306,7 @@ export function drawChart( ); } } - }); + } const crosshair = svg( "line", @@ -397,11 +397,11 @@ export function drawChart( } const time = first + ((px - MARGIN.left) / plotWidth) * span; let nearest = 0; - times.forEach((t, i) => { + for (const [i, t] of times.entries()) { if (Math.abs(t - time) < Math.abs((times[nearest] ?? 0) - time)) { nearest = i; } - }); + } showAt(nearest); }); root.addEventListener("pointerleave", hide); diff --git a/packages/mcp-core/src/api-client/client-request-paths.test.ts b/packages/mcp-core/src/api-client/client-request-paths.test.ts index c4b347c859..b0f893bb48 100644 --- a/packages/mcp-core/src/api-client/client-request-paths.test.ts +++ b/packages/mcp-core/src/api-client/client-request-paths.test.ts @@ -35,9 +35,9 @@ describe("client.ts request path invariant", () => { it("interpolates every request path through apiPath", () => { const offenders: string[] = []; - source.split("\n").forEach((line, index) => { + for (const [index, line] of source.split("\n").entries()) { const trimmed = line.trim(); - if (trimmed.startsWith("//") || trimmed.startsWith("*")) return; + if (trimmed.startsWith("//") || trimmed.startsWith("*")) continue; // A template literal opening with a slash is an API request path. for (let i = 0; i < line.length - 1; i++) { @@ -53,7 +53,7 @@ describe("client.ts request path invariant", () => { offenders.push(`${index + 1}: ${trimmed}`); } } - }); + } expect( offenders, diff --git a/packages/mcp-core/src/internal/issue-side-quests.test.ts b/packages/mcp-core/src/internal/issue-side-quests.test.ts index 894aab0c0a..6fa41fde2c 100644 --- a/packages/mcp-core/src/internal/issue-side-quests.test.ts +++ b/packages/mcp-core/src/internal/issue-side-quests.test.ts @@ -24,11 +24,9 @@ function eventWithFourFiles() { if (!("rawStacktrace" in value)) { continue; } - value.rawStacktrace.frames.forEach( - (frame: { absPath: string | null }, index: number) => { - frame.absPath = files[index] ?? frame.absPath; - }, - ); + for (const [index, frame] of value.rawStacktrace.frames.entries()) { + frame.absPath = files[index] ?? frame.absPath; + } } } return EventSchema.parse({ diff --git a/packages/mcp-core/src/internal/side-quests.ts b/packages/mcp-core/src/internal/side-quests.ts index be29b1e1a5..06e18f95d8 100644 --- a/packages/mcp-core/src/internal/side-quests.ts +++ b/packages/mcp-core/src/internal/side-quests.ts @@ -122,9 +122,9 @@ function recordSideQuests(ids: string[], max: number) { "app.side_quests.detected": ids.length, "app.side_quests.shown": shown.length, }; - ids.forEach((id, index) => { + for (const [index, id] of ids.entries()) { attributes[`app.side_quest.${id}`] = index < max ? "shown" : "capped"; - }); + } getActiveSpan()?.setAttributes(attributes); for (const id of shown) { metrics.count("app.side_quest.shown", 1, { diff --git a/packages/mcp-core/src/internal/source-map-diagnosis.ts b/packages/mcp-core/src/internal/source-map-diagnosis.ts index 6ae0968dfc..d1519414f3 100644 --- a/packages/mcp-core/src/internal/source-map-diagnosis.ts +++ b/packages/mcp-core/src/internal/source-map-diagnosis.ts @@ -101,17 +101,17 @@ function getDebugFramesByPath(event: Event, debug: SourceMapDebug) { } return parsed.data.values ?? (parsed.data.value ? [parsed.data.value] : []); }); - values.forEach((value, exceptionIndex) => { + for (const [exceptionIndex, value] of values.entries()) { const rawFrames = value?.rawStacktrace?.frames ?? []; - rawFrames.forEach((rawFrame, frameIndex) => { + for (const [frameIndex, rawFrame] of rawFrames.entries()) { const path = rawFrame.absPath; // the check can return fewer exceptions or frames than the event has const frame = debug.exceptions.at(exceptionIndex)?.frames.at(frameIndex); if (path && frame && !frames.has(path)) { frames.set(path, frame); } - }); - }); + } + } return frames; } diff --git a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts index 44591e0df7..1ab6b10733 100644 --- a/packages/mcp-core/src/tools/catalog/get-event-attachment.ts +++ b/packages/mcp-core/src/tools/catalog/get-event-attachment.ts @@ -221,7 +221,7 @@ export default defineTool({ output += `Found ${attachments.length} attachment(s):\n\n`; - attachments.forEach((attachment, index) => { + for (const [index, attachment] of attachments.entries()) { output += `## Attachment ${index + 1}\n\n`; output += `**ID:** ${attachment.id}\n`; output += `**Name:** ${attachment.name}\n`; @@ -242,7 +242,7 @@ export default defineTool({ availableToolNames: context.availableToolNames, directToolNames: context.directToolNames, })}\n\n`; - }); + } return output; }, diff --git a/packages/mcp-core/src/tools/support/profile/analyzer.ts b/packages/mcp-core/src/tools/support/profile/analyzer.ts index 70c89eeacf..8900f03c64 100644 --- a/packages/mcp-core/src/tools/support/profile/analyzer.ts +++ b/packages/mcp-core/src/tools/support/profile/analyzer.ts @@ -338,15 +338,15 @@ export function compareFrameStats( { baselineIdx?: number; currentIdx?: number } >(); - baselineFrames.forEach((frame, idx) => { + for (const [idx, frame] of baselineFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, baselineIdx: idx }); - }); + } - currentFrames.forEach((frame, idx) => { + for (const [idx, frame] of currentFrames.entries()) { const existing = frameMap.get(frame.fingerprint) || {}; frameMap.set(frame.fingerprint, { ...existing, currentIdx: idx }); - }); + } // Compare frames that exist in both const comparisons: FrameComparison[] = []; diff --git a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts index 848a6963ee..16df286e86 100644 --- a/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts +++ b/packages/mcp-core/src/tools/support/profile/flamegraph-output.ts @@ -178,15 +178,15 @@ export function buildFlamegraphAnalysis( // both overlap across nested frames, so they cannot be summed. const totalNs = sumOf(mainProfile?.sample_durations_ns); let userCodeNs = 0; - mainProfile?.samples.forEach((stack, index) => { + for (const [index, stack] of (mainProfile?.samples ?? []).entries()) { const leafIndex = stack.at(-1); if ( leafIndex !== undefined && flamegraph.shared.frames[leafIndex]?.is_application ) { - userCodeNs += mainProfile.sample_durations_ns[index] ?? 0; + userCodeNs += mainProfile?.sample_durations_ns[index] ?? 0; } - }); + } const outputFrames: FlamegraphAnalysis["frames"] = []; const outputIndexBySource = new Map(); diff --git a/packages/mcp-core/src/tools/support/search-events/replays.ts b/packages/mcp-core/src/tools/support/search-events/replays.ts index 9d3dc817b3..45b9003865 100644 --- a/packages/mcp-core/src/tools/support/search-events/replays.ts +++ b/packages/mcp-core/src/tools/support/search-events/replays.ts @@ -312,7 +312,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { output += `Found **${replays.length}** replay${replays.length === 1 ? "" : "s"}:\n\n`; - replays.forEach((replay, index) => { + for (const [index, replay] of replays.entries()) { const replayUrl = apiService.getReplayUrl(organizationSlug, replay.id); const user = formatReplayUser(replay); const clickSummary = [ @@ -343,7 +343,7 @@ export function formatReplayResults(params: FormatReplayResultsParams): string { } output += "\n"; - }); + } output += "## Next Steps\n\n"; const replayDetailsInstruction = formatToolCallInstruction({ diff --git a/packages/mcp-core/src/tools/support/search-events/utils.ts b/packages/mcp-core/src/tools/support/search-events/utils.ts index af4975d8b2..131472ef92 100644 --- a/packages/mcp-core/src/tools/support/search-events/utils.ts +++ b/packages/mcp-core/src/tools/support/search-events/utils.ts @@ -1348,21 +1348,18 @@ export function createDatasetAttributesTool(options: { let commonFields: Record = {}; let datasetFields: Record = {}; if (substringMatch) { - Object.entries(BASE_COMMON_FIELDS).forEach(([key, value]) => { + for (const [key, value] of Object.entries(BASE_COMMON_FIELDS)) { if (key.includes(substringMatch) || value.includes(substringMatch)) { commonFields[key] = value; } - }); - Object.entries(DATASET_FIELDS[normalizedDataset]).forEach( - ([key, value]) => { - if ( - key.includes(substringMatch) || - value.includes(substringMatch) - ) { - datasetFields[key] = value; - } - }, - ); + } + for (const [key, value] of Object.entries( + DATASET_FIELDS[normalizedDataset], + )) { + if (key.includes(substringMatch) || value.includes(substringMatch)) { + datasetFields[key] = value; + } + } } else { commonFields = BASE_COMMON_FIELDS; datasetFields = DATASET_FIELDS[normalizedDataset]; From ac6b75d40aa9bc5a13bab92a14f1612b0d165343 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:06:39 +0000 Subject: [PATCH 06/18] feat(cli): use positionals and existing CLI flags in sentry wizard `sentry wizard [/] []` replaces the `@sentry/wizard` flags, with the target first like other commands. - The integration is a positional, one at a time. A bare integration id is never read as a target, and a single bare word is always read as an integration, so a project or org spelled like one is written `my-org/nextjs`, `nextjs/` or `/nextjs`. - The target parses with the CLI's org/project grammar and resolves after login with `resolveOrgOptionalTarget`, like other commands. Without one the org and project pickers run, with no detection. - `-f/--force` is the only flag. It sets both `forceInstall` and `ignoreGitChanges`. - The instance comes from `SENTRY_URL` or the stored login, so the SaaS/self-hosted prompt, `--url`, `--saas` and `skipRcUrlCheck` go. - Spotlight mode follows `SENTRY_SPOTLIGHT`, telemetry follows `isTelemetryEnabled()`, and debug output goes through the CLI logger (`--verbose`, `--log-level`). - Every other `@sentry/wizard` flag and `SENTRY_WIZARD_*` variable is gone, hidden ones included, with `disableTelemetryForRun` and `rejectRemovedFlags`. A test pins the wizard's own flags to `force`, and `check:env-coverage` (part of `ci:policy`) fails when any file under `src/` names `SENTRY_WIZARD_`. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 51 ++- .../sentry-cli/skills/sentry-cli/SKILL.md | 2 +- .../skills/sentry-cli/references/wizard.md | 30 +- packages/cli/script/check-env-coverage.ts | 37 +- packages/cli/src/commands/wizard.ts | 346 +++++++++--------- packages/cli/src/lib/env-registry.ts | 25 +- packages/cli/src/lib/telemetry.ts | 13 - packages/cli/src/lib/wizard/run.ts | 47 +-- packages/cli/src/lib/wizard/telemetry.ts | 9 +- .../cli/src/lib/wizard/utils/clack/index.ts | 8 +- packages/cli/src/lib/wizard/utils/debug.ts | 31 +- .../cli/src/lib/wizard/utils/project-data.ts | 120 +----- packages/cli/src/lib/wizard/utils/types.ts | 32 +- packages/cli/test/commands/wizard.test.ts | 253 +++++++++---- .../lib/wizard/utils/project-data.test.ts | 127 +++++-- 15 files changed, 592 insertions(+), 539 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index d754b8845b..91218e9918 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -4,13 +4,29 @@ `sentry wizard` sets up the Sentry SDK in the project in the current directory. It asks a few questions, installs the SDK for your framework, -writes its configuration, and sets up source map or debug file uploads. -Pass `-i` with an integration, such as `nextjs`, to skip the integration -picker. +writes its configuration, and sets up source map or debug file uploads. It +takes an optional `/` first, then an optional integration: + +- Pass an integration, such as `nextjs`, to skip the integration picker. +- Pass `/` first to skip the org and project pickers, or + `/` to pick only the project. Without it, the wizard asks; it doesn't + detect a project from your files. +- An integration id is never read as a project or org, and a single bare + word is always read as an integration. Write a project or org with a `/`: + `my-org/my-project`, `my-org/`, or `/my-project`. For a project spelled + like an integration, write `my-org/nextjs`. +- `-f`/`--force` changes a project with uncommitted changes without asking, + and installs the SDK even when the package manager's checks fail. It logs in with your `sentry auth login` account, or starts a login when you -have none, and lets you pick or create the Sentry project to send data to. -Pass `--org` and `--project` to skip those questions. +have none, on the Sentry instance the rest of the CLI uses: `SENTRY_URL`, or +the stored login's. To use a self-hosted instance, log in to it first with +`sentry auth login --url`. + +Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development instead, +with no Sentry account or login. Telemetry follows the CLI's settings +(`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, `sentry cli defaults`), and the +global `--verbose` flag shows the wizard's debug output. `sentry wizard` changes your project's files. To have a coding agent set up Sentry instead, run `sentry init`, which prints the agent's setup guide and @@ -18,12 +34,19 @@ changes nothing. ## Coming from `@sentry/wizard` -`sentry wizard` takes the same integrations and flags as -`npx @sentry/wizard`, so `npx @sentry/wizard -i nextjs` and -`sentry wizard -i nextjs` do the same thing. These were removed: - -- The sign-up flags `--signup`, `--promo-code` and `--coming-from`. Passing one - fails with an explanation. Sign up at https://sentry.io/signup/ (and apply a - promo code there), then run the wizard. -- The Cordova and Electron wizards. Follow their setup guides in the Sentry - docs instead. +`sentry wizard` takes the same integration ids as `npx @sentry/wizard -i`, +but not its flags or `SENTRY_WIZARD_*` environment variables: + +| `@sentry/wizard` | `sentry wizard` | +| -------------------------------------- | ------------------------------------------------ | +| `-i nextjs` | `nextjs` | +| `--org my-org --project my-project` | `my-org/my-project`, before the integration | +| `--url`, `-u`, `--saas` | `sentry auth login --url`, or `SENTRY_URL` | +| `--spotlight` | `SENTRY_SPOTLIGHT=1` | +| `--force-install`, `--ignore-git-changes` | `-f`/`--force` | +| `--disable-telemetry` | `SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` | +| `--debug` | `--verbose` or `--log-level debug` | +| `--signup`, `--promo-code`, `--coming-from` | Sign up at https://sentry.io/signup/ first | + +The Cordova and Electron wizards were retired. Follow their setup guides in +the Sentry docs instead. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 963ccb51a1..d5dc5253d3 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -818,7 +818,7 @@ Print instructions for a coding agent to set up Sentry Set up the Sentry SDK in your project interactively -- `sentry wizard` — Set up the Sentry SDK in your project interactively +- `sentry wizard [/] []` — Set up the Sentry SDK in your project interactively → Full flags and examples: `references/wizard.md` diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 7e8405f3e0..fe5382422e 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -11,33 +11,33 @@ requires: Set up the Sentry SDK in your project interactively -### `sentry wizard` +### `sentry wizard [/] []` Set up the Sentry SDK in your project interactively +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `[/] []` | <org>/<project> to set up (skips the project picker), then the integration (skips the integration picker) | + **Flags:** -- `-i, --integration - Integration to set up (skips the picker)` -- `-u, --url - URL of your self-hosted Sentry instance` -- `--org - Slug of the Sentry organization to use` -- `--project - Slug of the Sentry project to use` -- `--saas - Use Sentry SaaS (sentry.io) without asking` -- `--spotlight - Set up Spotlight for local development, without a Sentry account` -- `--force-install - Install the SDK even when the package manager's checks fail` -- `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` -- `--disable-telemetry - Don't send telemetry about this run to Sentry` -- `--debug - Print the wizard's debug output` +- `-f, --force - Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail` **Examples:** ```bash -# Pick an integration and set it up +# Pick an integration and a project, then set it up sentry wizard -# Set up Next.js for a known org and project on sentry.io -sentry wizard -i nextjs --saas --org my-org --project my-project +# Set up Next.js, picking the project +sentry wizard nextjs + +# Set up Next.js for a known org and project +sentry wizard my-org/my-project nextjs # Set up Next.js for Spotlight, without a Sentry account -sentry wizard -i nextjs --spotlight +SENTRY_SPOTLIGHT=1 sentry wizard nextjs ``` All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index c07ddd5fc9..92e7d6c431 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -15,13 +15,17 @@ * test-only hooks, and vars inherited from the SDK are listed (with a reason) in * INTERNAL_ENV_VARS so their exclusion is explicit and reviewable. * + * It also fails when any file under src/ names a prefix in + * RETIRED_ENV_PREFIXES, such as the `SENTRY_WIZARD_*` vars of `@sentry/wizard`. + * * Usage: * pnpm ts script/check-env-coverage.ts * * Exit codes: * 0 - Every user-facing env var read by the CLI or an installer is documented * or explicitly internal - * 1 - Coverage gap, redundant allowlist entry, or stale allowlist entry + * 1 - Coverage gap, redundant allowlist entry, stale allowlist entry, or a + * retired env var prefix (RETIRED_ENV_PREFIXES) under src/ */ import { readFile } from "node:fs/promises"; @@ -51,10 +55,6 @@ const INTERNAL_ENV_VARS = new Map([ "SENTRY_ENVIRONMENT", "bash-hook traceback template only; inherited SDK convention", ], - [ - "SENTRY_SPOTLIGHT", - "set by `local run` for the child app; the CLI only names it in Worker setup hints", - ], [ "SENTRY_TRACES_SAMPLE_RATE", "inherited from the SDK when spawning subprocesses, not a CLI config knob", @@ -79,6 +79,17 @@ const INTERNAL_ENV_VARS = new Map([ ["SENTRY_RN_SOURCEMAP_REPORT", "internal react-native wrapper plumbing"], ]); +/** + * Env var prefixes the CLI dropped on purpose. No file under src/ may name + * one, read or not, so none comes back as a hidden alias. Each has a reason. + */ +const RETIRED_ENV_PREFIXES = new Map([ + [ + "SENTRY_WIZARD_", + "`sentry wizard` takes `/` and the integration as positionals, and reads only the CLI's own env vars (SENTRY_URL, SENTRY_SPOTLIGHT, SENTRY_LOG_LEVEL)", + ], +]); + const registryNames = new Set(ENV_VAR_REGISTRY.map((entry) => entry.name)); /** @@ -230,6 +241,22 @@ for (const name of INTERNAL_ENV_VARS.keys()) { } } +// Every file type under src/, generated files included, not just the env +// reads above: a retired name in a string or a comment fails too. +for (const file of await glob("src/**/*")) { + const content = await readFile(file, "utf-8"); + for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { + const index = content.indexOf(prefix); + if (index !== -1) { + const line = content.slice(0, index).split("\n").length; + errors.push( + `Retired env var prefix: ${prefix} (at ${file}:${line})\n` + + ` Remove it: ${reason}.`, + ); + } + } +} + if (errors.length > 0) { logger.error( [ diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 71f4b7fefd..01311bd7a6 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -3,244 +3,226 @@ * * Run the interactive setup wizard of a framework or platform: it installs * the Sentry SDK, writes its config files, and sets up source map or debug - * file uploads in the current project. Ported from `@sentry/wizard`, whose - * `-i ` invocations keep working. + * file uploads in the current project. Ported from `@sentry/wizard`. * * The wizard logs in with the CLI's own login instead of the old browser - * hand-off, so `auth: false` here: a run in Spotlight mode, or with a - * preselected project, needs no login at all. + * hand-off, so `auth: false` here: a run in Spotlight mode needs no login at + * all. */ import type { SentryContext } from "../context.js"; -import { buildCommand } from "../lib/command.js"; +import { sentry } from "../lib/app-identity.js"; import { - parseOrgSlug, - parseProjectSlug, - parseText, - parseUrl, -} from "../lib/completion-target.js"; + type ParsedOrgProject, + parseOrgProjectInput, +} from "../lib/arg-parsing.js"; +import { buildCommand } from "../lib/command.js"; +import { ORG_PROJECT_TARGET } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; import { ValidationError, WizardExitError } from "../lib/errors.js"; +import { parseBoolValue } from "../lib/parse-bool.js"; import { - disableTelemetryForRun, - isTelemetryEnabled, -} from "../lib/telemetry.js"; -import { INTEGRATION_IDS, runWizard } from "../lib/wizard/run.js"; + type BoundArguments, + boundArguments, +} from "../lib/positional-parse.js"; +import { applySentryUrlContext } from "../lib/sentry-url-parser.js"; +import { isTelemetryEnabled } from "../lib/telemetry.js"; +import { + INTEGRATION_IDS, + runWizard, + type WizardIntegration, +} from "../lib/wizard/run.js"; import { topLevelBrief } from "../top-level-briefs.js"; +const USAGE = "[/] []"; +const usageHint = () => sentry`wizard ${USAGE}`; + type WizardFlags = { - readonly integration?: string; - readonly url?: string; - readonly org?: string; - readonly project?: string; - readonly saas: boolean; - readonly debug: boolean; - readonly spotlight: boolean; - readonly "disable-telemetry": boolean; - readonly "force-install": boolean; - readonly "ignore-git-changes": boolean; - readonly signup: boolean; - readonly "promo-code"?: string; - readonly "coming-from"?: string; - readonly "skip-connect": boolean; - readonly quiet: boolean; - readonly uninstall: boolean; + readonly force: boolean; }; +/** Parsed `sentry wizard` arguments. */ +export type WizardInput = { + /** The org and project to set up; auto-detect means the user picks */ + readonly target: ParsedOrgProject; + /** Server of a pasted Sentry URL, applied when the arguments resolve */ + readonly baseUrl?: string; + /** The integration to set up; the user picks when unset */ + readonly integration?: WizardIntegration; +}; + +/** The arguments of `sentry wizard`. */ +export type WizardArguments = BoundArguments; + +/** Whether `value` is exactly one of {@link INTEGRATION_IDS}. */ +function isIntegrationId(value: string): value is WizardIntegration { + return (INTEGRATION_IDS as readonly string[]).includes(value); +} + /** - * Fail on the `@sentry/wizard` sign-up and partner flags, which `sentry - * wizard` dropped: it logs in with the CLI's login, which has no sign-up or - * partner step. + * The error for an argument in the integration position that names none. * - * @throws {ValidationError} When one of them is passed + * @param hint - Extra line saying how to name a target instead */ -function rejectRemovedFlags(flags: WizardFlags): void { - const removed = [ - flags.signup ? "--signup" : undefined, - flags["promo-code"] === undefined ? undefined : "--promo-code", - flags["coming-from"] === undefined ? undefined : "--coming-from", - ].filter((flag) => flag !== undefined); - if (removed.length === 0) { - return; - } - throw new ValidationError( - `${removed.join(", ")} ${removed.length === 1 ? "is" : "are"} no longer supported. ` + - "Sign up at https://sentry.io/signup/ (and apply any promo code there), " + - "then run the wizard again without " + - `${removed.length === 1 ? "it" : "them"}.`, - removed[0], +function unknownIntegration(value: string, hint = ""): ValidationError { + return new ValidationError( + `Unknown integration '${value}'. Pick one of: ${INTEGRATION_IDS.join(", ")}.\n` + + `${hint} Usage: ${usageHint()}`, + "integration", ); } -/** The trimmed value of the environment variable `name`, unless empty. */ -function envValue(name: string): string | undefined { - return getEnv()[name]?.trim() || undefined; +/** + * Parse the positionals of `sentry wizard`: `[/] []`. + * Has no side effects. + * + * - No arguments: the user picks both. + * - One argument: a bare word is the integration. A target always has a `/` + * (`/`, `/`, `/`) or is a Sentry URL. + * - Two arguments: the target, then the integration. The first may be any + * target form, including a bare project or org slug, except an + * integration id. + * + * A bare integration id is never a target, in either position: an org or + * project spelled like one is written `/nextjs`, `nextjs/` or + * `/nextjs`. + * + * @throws {ValidationError} For more than two arguments, an unknown + * integration, two integrations, or a malformed target + */ +export function parseWizardArguments(args: readonly string[]): WizardInput { + const [first, second, ...extra] = args; + if (extra.length > 0) { + throw new ValidationError( + `Too many arguments: ${extra.join(" ")}. Expected: ${usageHint()}`, + "positional", + ); + } + if (first === undefined) { + return { target: { type: "auto-detect" } }; + } + if (second === undefined) { + if (isIntegrationId(first)) { + return { target: { type: "auto-detect" }, integration: first }; + } + if (!first.includes("/")) { + throw unknownIntegration( + first, + " To name an org or project instead, write it as /, / or /.\n", + ); + } + } else if (isIntegrationId(first)) { + throw new ValidationError( + `'${first}' is an integration, and the wizard sets up one at a time.\n` + + ` To name a project or org called '${first}', write it as /${first}, ${first}/ or /${first}.\n` + + ` Usage: ${usageHint()}`, + "integration", + ); + } else if (!isIntegrationId(second)) { + throw unknownIntegration(second); + } + const { parsed, baseUrl } = parseOrgProjectInput(first); + return { + target: parsed, + ...(baseUrl && { baseUrl }), + ...(second !== undefined && { integration: second }), + }; +} + +/** + * Whether `SENTRY_SPOTLIGHT` turns on Spotlight mode. Like the Sentry SDKs, + * any value but an empty or false-like one (`0`, `false`, `off`, …) counts, + * including a Spotlight URL. + */ +function isSpotlightEnabled(): boolean { + const value = getEnv()["SENTRY_SPOTLIGHT"]?.trim(); + return value ? parseBoolValue(value) !== false : false; } export const wizardCommand = buildCommand({ auth: false, - // The wizard picks the Sentry instance itself (`--url`, `--saas` or a - // prompt) before it logs in, like `sentry init`. - skipRcUrlCheck: true, docs: { brief: topLevelBrief("wizard"), + customUsage: [USAGE], fullDescription: "Set up Sentry in the project in the current directory. The wizard " + "asks you a few questions, installs the Sentry SDK for your framework, " + "writes its configuration, and sets up source map or debug file " + - "uploads. It logs in with your `sentry auth login` account (or starts " + - "a login), and lets you pick or create the Sentry project to send " + - "data to.\n\n" + - "Pass `-i` to skip the integration picker. It takes the same " + - "integrations and flags as `npx @sentry/wizard`, except the sign-up " + - "flags `--signup`, `--promo-code` and `--coming-from`, which fail: " + - "sign up at https://sentry.io/signup/ first.\n\n" + + "uploads.\n\n" + + "It logs in with your `sentry auth login` account (or starts a login) " + + "on the Sentry instance the rest of the CLI uses, and lets you pick or " + + "create the Sentry project to send data to. Pass `/` " + + "first to skip those questions, or `/` to pick only the project. " + + "Pass an integration, such as `nextjs`, to skip the integration " + + `picker. Integrations: ${INTEGRATION_IDS.join(", ")}.\n\n` + + "An integration id is never read as a project or org, and a single " + + "bare word is always read as an integration. To name a project or " + + "org, write it with a `/`: `my-org/my-project`, `my-org/`, or " + + "`/my-project` (for a project spelled like an integration, " + + "`my-org/nextjs`).\n\n" + + "Set `SENTRY_SPOTLIGHT=1` to set up Spotlight for local development " + + "instead, without a Sentry account or login. Use the global " + + "`--verbose` flag for the wizard's debug output.\n\n" + "The wizard changes files in your project. To have a coding agent set " + "up Sentry instead, run `sentry init`, which prints the agent's setup " + "guide and changes nothing.", examples: [ { - description: "Pick an integration and set it up", + description: "Pick an integration and a project, then set it up", run: "wizard", }, { - description: "Set up Next.js for a known org and project on sentry.io", - run: "wizard -i nextjs --saas --org my-org --project my-project", + description: "Set up Next.js, picking the project", + run: "wizard nextjs", + }, + { + description: "Set up Next.js for a known org and project", + run: "wizard my-org/my-project nextjs", }, { description: "Set up Next.js for Spotlight, without a Sentry account", - run: "wizard -i nextjs --spotlight", + run: { prefix: "SENTRY_SPOTLIGHT=1 ", args: "wizard nextjs" }, }, ], }, parameters: { + positional: boundArguments({ + placeholder: "org/project-or-integration", + brief: + "/ to set up (skips the project picker), then the integration (skips the integration picker)", + kind: ORG_PROJECT_TARGET, + parse: parseWizardArguments, + // The org and project resolve after the wizard logs in; only a pasted + // URL's server applies here, before the login picks an instance. + resolve: async (input) => { + if (input.baseUrl) { + applySentryUrlContext(input.baseUrl); + } + return input; + }, + }), flags: { - integration: { - kind: "enum", - values: INTEGRATION_IDS, - brief: "Integration to set up (skips the picker)", - optional: true, - }, - url: { - kind: "parsed", - parse: parseUrl, - brief: "URL of your self-hosted Sentry instance", - placeholder: "url", - optional: true, - }, - org: { - kind: "parsed", - parse: parseOrgSlug, - brief: "Slug of the Sentry organization to use", - placeholder: "org", - optional: true, - }, - project: { - kind: "parsed", - parse: parseProjectSlug, - brief: "Slug of the Sentry project to use", - placeholder: "project", - optional: true, - }, - saas: { - kind: "boolean", - brief: "Use Sentry SaaS (sentry.io) without asking", - default: false, - }, - spotlight: { + force: { kind: "boolean", brief: - "Set up Spotlight for local development, without a Sentry account", - default: false, - }, - "force-install": { - kind: "boolean", - brief: "Install the SDK even when the package manager's checks fail", - default: false, - }, - "ignore-git-changes": { - kind: "boolean", - brief: "Don't ask before changing a project with uncommitted changes", - default: false, - }, - "disable-telemetry": { - kind: "boolean", - brief: "Don't send telemetry about this run to Sentry", - default: false, - }, - debug: { - kind: "boolean", - brief: "Print the wizard's debug output", - default: false, - }, - // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in - // with the CLI's login, which has no sign-up or partner step, so these - // fail with an explanation instead of being dropped silently. - signup: { - kind: "boolean", - brief: "Removed: sign up at https://sentry.io/signup/ first", - default: false, - hidden: true as const, - }, - "promo-code": { - kind: "parsed", - parse: parseText, - brief: "Removed: apply promo codes when you sign up", - placeholder: "code", - optional: true, - hidden: true as const, - }, - "coming-from": { - kind: "parsed", - parse: parseText, - brief: "Removed: partner sign-up is not supported", - placeholder: "partner", - optional: true, - hidden: true as const, - }, - // Flags `@sentry/wizard` accepted that no flow reads any more. Kept so - // copied commands still run. - "skip-connect": { - kind: "boolean", - brief: "Ignored", + "Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail", default: false, - hidden: true as const, - }, - quiet: { - kind: "boolean", - brief: "Ignored", - default: false, - hidden: true as const, - }, - uninstall: { - kind: "boolean", - brief: "Ignored: only the retired Cordova wizard could uninstall", - default: false, - hidden: true as const, }, }, - aliases: { i: "integration", u: "url", s: "signup" }, + aliases: { f: "force" }, }, // oxlint-disable-next-line require-yield -- The wizard prints its own interactive output; the command yields none. - async *func(this: SentryContext, flags: WizardFlags) { - rejectRemovedFlags(flags); - if (flags["disable-telemetry"]) { - disableTelemetryForRun(); - } - + async *func(this: SentryContext, flags: WizardFlags, args: WizardArguments) { + const { target, integration } = await args.resolved; try { await runWizard({ - integration: flags.integration ?? envValue("SENTRY_WIZARD_INTEGRATION"), - debug: flags.debug || envValue("SENTRY_WIZARD_DEBUG") === "true", + integration, wizardOptions: { - telemetryEnabled: !flags["disable-telemetry"] && isTelemetryEnabled(), - url: flags.url ?? envValue("SENTRY_WIZARD_URL"), - orgSlug: flags.org, - projectSlug: flags.project, - saas: flags.saas, - forceInstall: flags["force-install"], - ignoreGitChanges: flags["ignore-git-changes"], - spotlight: flags.spotlight, + telemetryEnabled: isTelemetryEnabled(), + target, + forceInstall: flags.force, + ignoreGitChanges: flags.force, + spotlight: isSpotlightEnabled(), }, }); } catch (error) { diff --git a/packages/cli/src/lib/env-registry.ts b/packages/cli/src/lib/env-registry.ts index b9b5edb556..52d355f748 100644 --- a/packages/cli/src/lib/env-registry.ts +++ b/packages/cli/src/lib/env-registry.ts @@ -139,24 +139,6 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ selfHosted: true, devGuide: "Sentry OAuth app client ID", }, - { - name: "SENTRY_WIZARD_INTEGRATION", - description: - "Integration for `sentry wizard` to set up when `-i` is not passed, such as `nextjs`. Kept from `@sentry/wizard`.", - example: "nextjs", - }, - { - name: "SENTRY_WIZARD_URL", - description: - "URL of the self-hosted Sentry instance for `sentry wizard` when `--url` is not passed. Kept from `@sentry/wizard`.", - example: "https://sentry.example.com", - }, - { - name: "SENTRY_WIZARD_DEBUG", - description: - "Set to `true` to print the debug output of `sentry wizard`, like `--debug`. Kept from `@sentry/wizard`.", - example: "true", - }, { name: "SENTRY_HANDOFF", description: @@ -220,6 +202,13 @@ export const ENV_VAR_REGISTRY: readonly EnvVarEntry[] = [ example: "1", installOnly: true, }, + // -- Local development -- + { + name: "SENTRY_SPOTLIGHT", + description: + "Turns on Spotlight, the local debugger, in Sentry SDKs. Set it to `1`, `true`, or a Spotlight URL when running `sentry wizard` to set up Spotlight for local development instead of a Sentry project, with no login. Empty, `0`, `false`, and `off` leave it off. `sentry local run` sets it for the app it runs.", + example: "1", + }, // -- Games -- { name: "SENTRY_GAMES_API_URL", diff --git a/packages/cli/src/lib/telemetry.ts b/packages/cli/src/lib/telemetry.ts index b4e32c1640..2467c3f349 100644 --- a/packages/cli/src/lib/telemetry.ts +++ b/packages/cli/src/lib/telemetry.ts @@ -176,19 +176,6 @@ export function isTelemetryEnabled(): boolean { return computeTelemetryEffective().enabled; } -/** - * Stop sending telemetry for the rest of this run, after `withTelemetry` - * already started it: the client drops every envelope from now on, including - * the command's own transaction. For flags such as `sentry wizard - * --disable-telemetry` that opt out of one run. - */ -export function disableTelemetryForRun(): void { - const client = Sentry.getClient(); - if (client) { - client.getOptions().enabled = false; - } -} - /** * Attributes a Snake score metric may carry. Everything else the SDK adds * (user.*, replay ids, ...) is dropped so a score cannot be linked to a user. diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..ebae262d08 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -9,12 +9,11 @@ import { ValidationError } from "../errors.js"; import { abortIfCancelled } from "./utils/clack/index.js"; import { clack } from "./utils/clack/prompts.js"; -import { enableDebugLogs } from "./utils/debug.js"; import type { WizardOptions } from "./utils/types.js"; import { CLI_VERSION } from "../constants.js"; /** - * The integrations `sentry wizard -i` accepts, in the order the picker lists + * The integrations `sentry wizard` accepts, in the order the picker lists * them. The ids are the ones `@sentry/wizard -i` took. */ export const WIZARD_INTEGRATIONS = [ @@ -33,12 +32,13 @@ export const WIZARD_INTEGRATIONS = [ { id: "sourcemaps", label: "Configure Source Maps Upload" }, ] as const; -/** An integration id `sentry wizard -i` accepts. */ +/** An integration id `sentry wizard` accepts. */ export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; /** - * Every value `-i` accepts. The Cordova and Electron wizards of - * `@sentry/wizard` were retired; their setup guides are in the Sentry docs. + * Every integration id `sentry wizard` accepts. The Cordova and Electron + * wizards of `@sentry/wizard` were retired; their setup guides are in the + * Sentry docs. */ export const INTEGRATION_IDS: readonly WizardIntegration[] = WIZARD_INTEGRATIONS.map((integration) => integration.id); @@ -59,10 +59,8 @@ const WIZARD_RUNNERS: Partial> = { /** What `sentry wizard` passes to {@link runWizard}. */ export type RunWizardArgs = { - /** `-i`: the integration to set up; prompts for one when unset. */ - integration?: string | undefined; - /** `--debug`: print the wizard's debug output. */ - debug: boolean; + /** The integration to set up; prompts for one when unset. */ + integration?: WizardIntegration | undefined; /** The options every wizard flow takes. */ wizardOptions: WizardOptions; }; @@ -71,17 +69,11 @@ export type RunWizardArgs = { * Run the wizard of `args.integration`, after asking for one when it is * unset. * - * @throws {ValidationError} For an unknown integration, or one that has no - * flow in this version yet + * @throws {ValidationError} For an integration that has no flow in this + * version yet */ export async function runWizard(args: RunWizardArgs): Promise { - if (args.debug) { - enableDebugLogs(); - } - - const integration = args.integration - ? toWizardIntegration(args.integration) - : await askForIntegration(); + const integration = args.integration ?? (await askForIntegration()); const runner = WIZARD_RUNNERS[integration]; if (!runner) { @@ -93,25 +85,6 @@ export async function runWizard(args: RunWizardArgs): Promise { await runner(args.wizardOptions); } -/** - * `id` as one of {@link WIZARD_INTEGRATIONS}. `-i` already checks its - * value; `SENTRY_WIZARD_INTEGRATION` is checked here. - * - * @throws {ValidationError} When `id` names no integration - */ -function toWizardIntegration(id: string): WizardIntegration { - const match = WIZARD_INTEGRATIONS.find( - (integration) => integration.id === id, - ); - if (!match) { - throw new ValidationError( - `Unknown integration "${id}". Pick one of: ${INTEGRATION_IDS.join(", ")}.`, - "integration", - ); - } - return match.id; -} - /** Ask which integration to set up, out of the ones that have a flow. */ async function askForIntegration(): Promise { clack.intro(`Sentry Wizard ${CLI_VERSION}`); diff --git a/packages/cli/src/lib/wizard/telemetry.ts b/packages/cli/src/lib/wizard/telemetry.ts index 09a39e330d..e19324fcca 100644 --- a/packages/cli/src/lib/wizard/telemetry.ts +++ b/packages/cli/src/lib/wizard/telemetry.ts @@ -6,8 +6,7 @@ * wizard flow is a `wizard.flow` span under it and each step a `wizard.step` * span under that. Tags go on the same scope as the CLI's. Telemetry is off * when the CLI's is (`SENTRY_CLI_NO_TELEMETRY`, `DO_NOT_TRACK`, or - * `sentry cli defaults telemetry off`), and `--disable-telemetry` turns it - * off for the run. + * `sentry cli defaults telemetry off`). * * The old wizard sent its telemetry to a project of its own; the tag names * stay the same so its dashboards can move over. @@ -26,7 +25,7 @@ export const Sentry = { setTag, setUser }; /** * Run a wizard flow in a `wizard.flow` span, tagged with the integration and - * which of `--org`, `--project`, and `--saas` were passed. + * the kind of `/` target passed (`auto-detect` for none). */ export async function withTelemetry( options: { @@ -38,9 +37,7 @@ export async function withTelemetry( callback: () => F | Promise, ): Promise { setTag("integration", options.integration); - setTag("args.project", Boolean(options.wizardOptions.projectSlug)); - setTag("args.org", Boolean(options.wizardOptions.orgSlug)); - setTag("args.saas", Boolean(options.wizardOptions.saas)); + setTag("args.target", options.wizardOptions.target?.type ?? "auto-detect"); return await startSpan( { diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index a076b5049b..35282ec08e 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -169,8 +169,8 @@ export function printWelcome(options: { This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard. You can turn this off at any time by running ${chalk.cyanBright( - sentry`wizard --disable-telemetry`, - )}.`; + sentry`cli defaults telemetry off`, + )}, or by setting SENTRY_CLI_NO_TELEMETRY=1.`; } clack.note(welcomeText); @@ -200,7 +200,7 @@ export async function confirmContinueIfNoOrDirtyGitRepo({ ) { if (nonInteractive) { clack.log.error( - "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --ignore-git-changes to skip this safety check.", + "Project is not inside a git repository in non-interactive mode. Run from a git repository or pass --force to skip this safety check.", ); Sentry.setTag("continue-without-git", false); await abort(); @@ -237,7 +237,7 @@ The wizard will create and update files.`, if (nonInteractive) { clack.log.error( - "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --ignore-git-changes to skip this safety check.", + "Project has uncommitted or untracked files in non-interactive mode. Commit or stash your changes, or pass --force to skip this safety check.", ); Sentry.setTag("continue-with-dirty-repo", false); await abort(); diff --git a/packages/cli/src/lib/wizard/utils/debug.ts b/packages/cli/src/lib/wizard/utils/debug.ts index c8668c78ce..a8fb70f99a 100644 --- a/packages/cli/src/lib/wizard/utils/debug.ts +++ b/packages/cli/src/lib/wizard/utils/debug.ts @@ -1,32 +1,13 @@ /** - * Debug output of the setup wizards, shown with `sentry wizard --debug`. + * Debug output of the setup wizards, shown with the CLI's global `--verbose` + * or `--log-level debug`. */ -import chalk from "chalk"; -import { clack } from "./clack/prompts.js"; +import { logger } from "../../logger.js"; -let debugEnabled = false; +const log = logger.withTag("wizard"); -/** Render one debug argument: strings as-is, errors with their stack. */ -function prepareMessage(msg: unknown): string { - if (typeof msg === "string") { - return msg; - } - if (msg instanceof Error) { - return msg.stack ?? msg.message; - } - return JSON.stringify(msg, null, "\t"); -} - -/** Log `args` in the wizard's output when `--debug` is on. */ +/** Log `args` at the CLI logger's debug level. */ export function debug(...args: unknown[]): void { - if (!debugEnabled) { - return; - } - clack.log.info(chalk.dim(args.map((a) => prepareMessage(a)).join(" "))); -} - -/** Turn on {@link debug} output for the rest of the run. */ -export function enableDebugLogs(): void { - debugEnabled = true; + log.debug(...args); } diff --git a/packages/cli/src/lib/wizard/utils/project-data.ts b/packages/cli/src/lib/wizard/utils/project-data.ts index 0e4b856c32..c44faa30a0 100644 --- a/packages/cli/src/lib/wizard/utils/project-data.ts +++ b/packages/cli/src/lib/wizard/utils/project-data.ts @@ -9,8 +9,11 @@ * agent handoff from `SENTRY_HANDOFF`) when there is none. A new login asks * for `org:tokens` and `org:ci` too, so the auth token below needs no second * approval. - * - The org from `--org`, the handoff, or a prompt; then the project from - * `--project` or a prompt that can also create one for the wizard's + * - The Sentry instance the rest of the CLI uses: `SENTRY_URL`, or the + * stored login's. + * - The org and project of the `/` target, resolved like other + * commands' targets; else the org from the handoff or a prompt, then the + * project from a prompt that can also create one for the wizard's * platform, like the old browser page could. * - The project's DSN from its client keys. * - A new org auth token for the build plugins and `sentry` commands that @@ -33,21 +36,18 @@ import { MEMBER_PROJECT_CREATION_DISABLED_DETAIL, } from "../../api/projects.js"; import { assertAutoLoginHostTrusted } from "../../auto-auth.js"; -import { DEFAULT_SENTRY_URL } from "../../constants.js"; import { getAuthConfig } from "../../db/auth.js"; import { getEnv } from "../../env.js"; import { ApiError } from "../../errors.js"; import { runInteractiveLogin } from "../../interactive-login.js"; import { logger } from "../../logger.js"; import { OAUTH_SCOPES, resolveOAuthScopeString } from "../../oauth.js"; +import { resolveOrgOptionalTarget } from "../../resolve-target.js"; import { resolveOrCreateTeam } from "../../resolve-team.js"; import { ensureScopesForAction } from "../../scope-recovery.js"; import { isSentrySaasUrl } from "../../sentry-urls.js"; import { getApiBaseUrl } from "../../sentry-client.js"; -import { - isRequestOriginTrusted, - registerLoginTrustAnchor, -} from "../../token-host.js"; +import { isRequestOriginTrusted } from "../../token-host.js"; import { slugify } from "../../utils.js"; import { sentry } from "../../app-identity.js"; import type { @@ -104,7 +104,7 @@ export type WizardProjectData = * `options.preSelectedProject`, or one the user picks (or creates) after * logging in. * - * @param options - Wizard options (`--url`, `--saas`, `--org`, `--project`, …) + * @param options - Wizard options (the `/` target, Spotlight, …) * @param platform - Platform for a project the user creates */ export async function getOrAskForProjectData( @@ -122,29 +122,33 @@ export async function getOrAskForProjectData( if (options.preSelectedProject) { return { selfHosted: options.preSelectedProject.selfHosted, - sentryUrl: withTrailingSlash(options.url ?? DEFAULT_SENTRY_URL), + sentryUrl: withTrailingSlash(getApiBaseUrl()), authToken: options.preSelectedProject.authToken, selectedProject: options.preSelectedProject.project, spotlight: false, }; } - await traceStep("ask-self-hosted", () => - selectSentryUrl(options.url, options.saas), - ); const handoffOrg = await traceStep("login", ensureLoggedIn); - // The chosen instance, or the stored login's when none was chosen. + // `SENTRY_URL`, or the stored login's instance. const sentryUrl = withTrailingSlash(getApiBaseUrl()); const selfHosted = !isSentrySaasUrl(sentryUrl); Sentry.setTag("url", sentryUrl); Sentry.setTag("self-hosted", selfHosted); + const parsedTarget = options.target; + const target = + parsedTarget && parsedTarget.type !== "auto-detect" + ? await traceStep("resolve-target", () => + resolveOrgOptionalTarget(parsedTarget, process.cwd(), "wizard"), + ) + : undefined; const org = await traceStep("select-org", () => - selectOrganization(options.orgSlug ?? handoffOrg), + selectOrganization(target?.org ?? handoffOrg), ); const project = await traceStep("select-project", () => - selectProject(org, options.projectSlug, platform), + selectProject(org, target?.project, platform), ); Sentry.setTag("project", project.slug); Sentry.setUser({ id: org.slug }); @@ -168,90 +172,6 @@ export async function getOrAskForProjectData( }; } -/** - * Point this run at the Sentry instance the user chose: SaaS for `--saas`, - * the `--url` instance, or the answer to a SaaS/self-hosted prompt. Without - * any of them and with a stored login, the login's instance is used. - * - * An instance the user names here (flag or prompt) is trusted for login, the - * same as `sentry auth login --url`. - */ -async function selectSentryUrl( - urlFromArgs: string | undefined, - saas: boolean | undefined, -): Promise { - if (saas) { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - if (!urlFromArgs && getAuthConfig()) { - return; - } - - if (!urlFromArgs) { - const choice = await abortIfCancelled( - clack.select({ - message: "Are you using Sentry SaaS or self-hosted Sentry?", - options: [ - { value: "saas", label: "Sentry SaaS (sentry.io)" }, - { - value: "self-hosted", - label: "Self-hosted/on-premise/single-tenant", - }, - ], - }), - ); - if (choice === "saas") { - useSentryUrl(DEFAULT_SENTRY_URL); - return; - } - } - - let pending = urlFromArgs; - for (;;) { - const url = - pending || - (await abortIfCancelled( - clack.text({ - message: `Please enter the URL of your ${ - urlFromArgs ? "" : "self-hosted " - }Sentry instance.`, - placeholder: "https://sentry.io/", - }), - )); - pending = undefined; - const origin = parseOrigin(url); - if (origin) { - useSentryUrl(origin); - return; - } - clack.log.error( - `Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/", got ${url})`, - ); - } -} - -/** The origin of `url`, or `undefined` when it isn't an HTTP(S) URL. */ -function parseOrigin(url: string): string | undefined { - try { - const parsed = new URL(url); - return parsed.protocol === "https:" || parsed.protocol === "http:" - ? parsed.origin - : undefined; - } catch (error) { - log.debug(`Invalid Sentry URL ${url}`, error); - return; - } -} - -/** Send this run's API requests and login to `url`, trusted as user input. */ -function useSentryUrl(url: string): void { - const env = getEnv(); - env["SENTRY_HOST"] = url; - env["SENTRY_URL"] = url; - registerLoginTrustAnchor(url); -} - /** * Make sure the CLI has a login for the selected instance: claim the agent * handoff in `SENTRY_HANDOFF`, keep a stored login, or run the device flow. @@ -405,7 +325,7 @@ async function createProject( spinner.start("Creating your Sentry project"); try { const team = await resolveOrCreateTeam(orgSlug, { - usageHint: sentry`wizard --org `, + usageHint: sentry`wizard /`, autoCreateSlug: slugify(body.name), }); const { project } = await createProjectWithDsn(orgSlug, team.slug, body); diff --git a/packages/cli/src/lib/wizard/utils/types.ts b/packages/cli/src/lib/wizard/utils/types.ts index d349678578..1f53c0e364 100644 --- a/packages/cli/src/lib/wizard/utils/types.ts +++ b/packages/cli/src/lib/wizard/utils/types.ts @@ -3,6 +3,8 @@ * flow, the Sentry project a flow sets up, and feature prompts. */ +import type { ParsedOrgProject } from "../../arg-parsing.js"; + export interface SentryProjectData { id: string; slug: string; @@ -27,30 +29,11 @@ export type WizardOptions = { telemetryEnabled: boolean; /** - * The url of the Sentry instance to use. - * This can be passed via the `-u` or `--url` arg. - */ - url?: string | undefined; - - /** - * The org to pre-select in the wizard. - * This can be passed via the `--org` arg. - * Example: `--org my-org` - */ - orgSlug?: string | undefined; - - /** - * Project slug to pre-select in the wizard. - * This can be passed via the `--project` arg. - * Example: `--project my-project` - */ - projectSlug?: string | undefined; - - /** - * If this option is set, the wizard will skip the self-hosted or SaaS - * selection step and directly assume that the wizard is used for Sentry SaaS. + * The org and project from `sentry wizard /`, resolved after + * the login: an org and project skip both pickers, an org (`/`) skips + * the org picker. Unset or auto-detect: the user picks both. */ - saas?: boolean | undefined; + target?: ParsedOrgProject | undefined; /** * If this is set, the wizard will skip the login and project selection step. @@ -69,6 +52,7 @@ export type WizardOptions = { /** * If this is set, the wizard will ignore any git changes in the project and not prompt for confirmation. + * `sentry wizard --force` sets it, together with {@link forceInstall}. */ ignoreGitChanges?: boolean | undefined; @@ -78,7 +62,7 @@ export type WizardOptions = { * - Skips login and project selection * - Uses empty DSN * - Skips auth token file creation - * This can be passed via the `--spotlight` arg. + * `sentry wizard` turns it on when `SENTRY_SPOTLIGHT` is set. */ spotlight?: boolean | undefined; }; diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 46be02ce14..3705740bb9 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -1,40 +1,38 @@ /** - * Tests for `sentry wizard`: integration selection, the flags it passes to a - * wizard flow, and how a stopped wizard sets the exit code. + * Tests for `sentry wizard`: its command line (`[/] + * []` and `--force`, nothing else), what it passes to a wizard + * flow, and how a stopped wizard sets the exit code. */ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { runNextjsWizard } = vi.hoisted(() => ({ +const { runNextjsWizard, isTelemetryEnabled } = vi.hoisted(() => ({ runNextjsWizard: vi.fn<(options: unknown) => Promise>(), + isTelemetryEnabled: vi.fn<() => boolean>(), })); vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ runNextjsWizard, })); +vi.mock("../../src/lib/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + isTelemetryEnabled, +})); -import { wizardCommand } from "../../src/commands/wizard.js"; +import { + parseWizardArguments, + wizardCommand, +} from "../../src/commands/wizard.js"; import type { SentryContext } from "../../src/context.js"; +import { buildCommand } from "../../src/lib/command.js"; import { ValidationError, WizardExitError } from "../../src/lib/errors.js"; import type { Writer } from "../../src/types/index.js"; import { loadCommand, useTestConfigDir } from "../helpers.js"; useTestConfigDir("wizard-test-"); -const DEFAULT_FLAGS = { - saas: false, - debug: false, - spotlight: false, - "disable-telemetry": false, - "force-install": false, - "ignore-git-changes": false, - signup: false, - "skip-connect": false, - quiet: false, - uninstall: false, -}; - async function runWizardCommand( flags: Record = {}, + ...args: string[] ): Promise { const context = { process, @@ -47,12 +45,21 @@ async function runWizardCommand( configDir: "/tmp", } as unknown as SentryContext; const func = await loadCommand(wizardCommand); - await func.call(context, { ...DEFAULT_FLAGS, ...flags }); + await func.call(context, { force: false, ...flags }, ...args); +} + +/** The options the Next.js flow was called with. */ +function nextjsOptions(): Record { + expect(runNextjsWizard).toHaveBeenCalledTimes(1); + return runNextjsWizard.mock.calls[0]?.[0] as Record; } beforeEach(() => { runNextjsWizard.mockReset(); runNextjsWizard.mockResolvedValue(undefined); + isTelemetryEnabled.mockReset(); + isTelemetryEnabled.mockReturnValue(true); + vi.stubEnv("SENTRY_SPOTLIGHT", ""); process.exitCode = undefined; }); @@ -61,72 +68,182 @@ afterEach(() => { process.exitCode = undefined; }); -describe("sentry wizard", () => { - test("runs the -i integration with the @sentry/wizard flags", async () => { - await runWizardCommand({ +describe("sentry wizard flags", () => { + /** Flags and aliases `buildCommand` adds to every command. */ + const injected = buildCommand({ + auth: false, + docs: { brief: "probe" }, + parameters: {}, + // oxlint-disable-next-line require-yield -- A probe; it never runs. + async *func() { + await Promise.resolve(); + }, + }).parameters; + + test("--force (-f) is the wizard's only flag, and it is not hidden", () => { + const { flags = {}, aliases = {} } = wizardCommand.parameters as { + flags?: Record; + aliases?: Record; + }; + const ownFlags = Object.keys(flags).filter( + (name) => !(name in (injected.flags ?? {})), + ); + const ownAliases = Object.entries(aliases).filter( + ([alias]) => !(alias in (injected.aliases ?? {})), + ); + + expect(ownFlags).toEqual(["force"]); + expect(flags["force"]?.hidden).toBeUndefined(); + expect(Object.fromEntries(ownAliases)).toEqual({ f: "force" }); + }); +}); + +describe("parseWizardArguments", () => { + test("no arguments: the user picks the integration and the project", () => { + expect(parseWizardArguments([])).toEqual({ + target: { type: "auto-detect" }, + }); + }); + + test("an integration alone", () => { + expect(parseWizardArguments(["nextjs"])).toEqual({ + target: { type: "auto-detect" }, integration: "nextjs", - org: "acme", - project: "web", - url: "https://sentry.example.com", - spotlight: true, - "force-install": true, - "ignore-git-changes": true, - "disable-telemetry": true, }); + }); - expect(runNextjsWizard).toHaveBeenCalledWith({ - telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", - saas: false, - forceInstall: true, - ignoreGitChanges: true, - spotlight: true, + test("a target alone", () => { + expect(parseWizardArguments(["my-org/my-project"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + }); + expect(parseWizardArguments(["my-org/"])).toEqual({ + target: { type: "org-all", org: "my-org" }, + }); + expect(parseWizardArguments(["/my-project"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, }); }); - test.each([ - [{ signup: true }, "--signup is no longer supported."], - [{ "promo-code": "PROMO" }, "--promo-code is no longer supported."], - [{ "coming-from": "vercel" }, "--coming-from is no longer supported."], - [ - { signup: true, "promo-code": "PROMO" }, - "--signup, --promo-code are no longer supported.", - ], - ])("rejects the removed sign-up flags %o", async (flags, message) => { - const error = await runWizardCommand({ integration: "nextjs", ...flags }) - .then(() => undefined) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(ValidationError); - expect((error as ValidationError).message).toContain(message); - expect((error as ValidationError).message).toContain( - "https://sentry.io/signup/", + test("a target, then an integration", () => { + expect(parseWizardArguments(["my-org/my-project", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare project or org slug before an integration is the target", () => { + expect(parseWizardArguments(["my-project", "nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "my-project" }, + integration: "nextjs", + }); + }); + + test("a bare slug alone is read as an integration, so it must be one", () => { + expect(() => parseWizardArguments(["my-project"])).toThrow( + new ValidationError( + "Unknown integration 'my-project'. Pick one of: reactNative, flutter, ios, appleSnapshots, angular, android, nextjs, nuxt, remix, reactRouter, sveltekit, cloudflare, sourcemaps.\n" + + " To name an org or project instead, write it as /, / or /.\n" + + " Usage: sentry wizard [/] []", + "integration", + ), + ); + }); + + test("a project named like an integration is written with its org", () => { + expect(parseWizardArguments(["my-org/nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + }); + expect(parseWizardArguments(["my-org/nextjs", "nextjs"])).toEqual({ + target: { type: "explicit", org: "my-org", project: "nextjs" }, + integration: "nextjs", + }); + expect(parseWizardArguments(["/nextjs"])).toEqual({ + target: { type: "project-search", projectSlug: "nextjs" }, + }); + }); + + test("an unknown integration after a target", () => { + expect(() => parseWizardArguments(["my-org/my-project", "cobol"])).toThrow( + "Unknown integration 'cobol'.", ); - expect(runNextjsWizard).not.toHaveBeenCalled(); }); - test("reads the integration and URL from SENTRY_WIZARD_* variables", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "nextjs"); - vi.stubEnv("SENTRY_WIZARD_URL", "https://self-hosted.example.com"); + test("integration ids are matched exactly", () => { + expect(() => parseWizardArguments(["NextJS"])).toThrow( + "Unknown integration 'NextJS'.", + ); + expect(() => parseWizardArguments(["nextjs,remix"])).toThrow( + "Unknown integration 'nextjs,remix'.", + ); + }); - await runWizardCommand(); + test("exactly one integration", () => { + expect(() => parseWizardArguments(["nextjs", "remix"])).toThrow( + "'nextjs' is an integration, and the wizard sets up one at a time.\n" + + " To name a project or org called 'nextjs', write it as /nextjs, nextjs/ or /nextjs.", + ); + }); - expect(runNextjsWizard).toHaveBeenCalledWith( - expect.objectContaining({ url: "https://self-hosted.example.com" }), + test("too many arguments", () => { + expect(() => + parseWizardArguments(["my-org/my-project", "nextjs", "remix"]), + ).toThrow( + "Too many arguments: remix. Expected: sentry wizard [/] []", ); }); +}); + +describe("sentry wizard", () => { + test("runs the integration for the target", async () => { + await runWizardCommand({}, "my-org/my-project", "nextjs"); + + expect(nextjsOptions()).toEqual({ + telemetryEnabled: true, + target: { type: "explicit", org: "my-org", project: "my-project" }, + forceInstall: false, + ignoreGitChanges: false, + spotlight: false, + }); + }); - test("rejects an unknown SENTRY_WIZARD_INTEGRATION", async () => { - vi.stubEnv("SENTRY_WIZARD_INTEGRATION", "cobol"); + test("--force both force-installs and skips the uncommitted changes prompt", async () => { + await runWizardCommand({ force: true }, "nextjs"); - await expect(runWizardCommand()).rejects.toThrow(ValidationError); - expect(runNextjsWizard).not.toHaveBeenCalled(); + expect(nextjsOptions()).toMatchObject({ + forceInstall: true, + ignoreGitChanges: true, + }); }); + test.each([ + ["1", true], + ["true", true], + ["http://localhost:8969/stream", true], + ["0", false], + ["false", false], + ["off", false], + ["", false], + ])("SENTRY_SPOTLIGHT=%j sets Spotlight mode to %s", async (value, on) => { + vi.stubEnv("SENTRY_SPOTLIGHT", value); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ spotlight: on }); + }); + + test.each([true, false])( + "telemetry follows isTelemetryEnabled() (%s)", + async (enabled) => { + isTelemetryEnabled.mockReturnValue(enabled); + + await runWizardCommand({}, "nextjs"); + + expect(nextjsOptions()).toMatchObject({ telemetryEnabled: enabled }); + }, + ); + test("reports an integration this version can't set up yet", async () => { - await expect(runWizardCommand({ integration: "remix" })).rejects.toThrow( + await expect(runWizardCommand({}, "remix")).rejects.toThrow( "The remix wizard is not available in this version yet.", ); }); @@ -134,7 +251,7 @@ describe("sentry wizard", () => { test("exits with the wizard's code when it stops", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(0)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(0); }); @@ -142,7 +259,7 @@ describe("sentry wizard", () => { test("exits with code 1 when the wizard can't continue", async () => { runNextjsWizard.mockRejectedValue(new WizardExitError(1)); - await runWizardCommand({ integration: "nextjs" }); + await runWizardCommand({}, "nextjs"); expect(process.exitCode).toBe(1); }); diff --git a/packages/cli/test/lib/wizard/utils/project-data.test.ts b/packages/cli/test/lib/wizard/utils/project-data.test.ts index 152d7adb29..b2baab05be 100644 --- a/packages/cli/test/lib/wizard/utils/project-data.test.ts +++ b/packages/cli/test/lib/wizard/utils/project-data.test.ts @@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({ text: vi.fn(), isRequestOriginTrusted: vi.fn(), getApiBaseUrl: vi.fn(), + resolveOrgOptionalTarget: vi.fn(), warn: vi.fn(), })); @@ -73,6 +74,11 @@ vi.mock("../../../../src/lib/api/organizations.js", () => ({ vi.mock("../../../../src/lib/api/org-auth-tokens.js", () => ({ createOrgAuthToken: mocks.createOrgAuthToken, })); +// Target resolution has its own tests; these check what the wizard does +// with the resolved org and project. +vi.mock("../../../../src/lib/resolve-target.js", () => ({ + resolveOrgOptionalTarget: mocks.resolveOrgOptionalTarget, +})); vi.mock("../../../../src/lib/resolve-team.js", () => ({ resolveOrCreateTeam: mocks.resolveOrCreateTeam, })); @@ -87,6 +93,7 @@ vi.mock("../../../../src/lib/api/projects.js", async (importOriginal) => ({ createProjectWithAutoTeam: mocks.createProjectWithAutoTeam, })); +import type { ParsedOrgProject } from "../../../../src/lib/arg-parsing.js"; import { ApiError, WizardExitError } from "../../../../src/lib/errors.js"; import { DUMMY_AUTH_TOKEN, @@ -96,6 +103,11 @@ import type { SentryProjectData } from "../../../../src/lib/wizard/utils/types.j const ORG = { id: "1", slug: "acme", name: "Acme" }; const PROJECT = { id: "42", slug: "web", name: "web", platform: "javascript" }; +const ACME_WEB: ParsedOrgProject = { + type: "explicit", + org: "acme", + project: "web", +}; const KEY = { id: "k1", name: "Default", @@ -117,6 +129,20 @@ beforeEach(async () => { mocks.getProjectKeys.mockResolvedValue([KEY]); mocks.ensureScopesForAction.mockResolvedValue("ready"); mocks.createOrgAuthToken.mockResolvedValue({ token: "sntrys_new" }); + mocks.resolveOrgOptionalTarget.mockImplementation( + (parsed: ParsedOrgProject) => { + switch (parsed.type) { + case "explicit": + return Promise.resolve({ org: parsed.org, project: parsed.project }); + case "org-all": + return Promise.resolve({ org: parsed.org }); + case "project-search": + return Promise.resolve({ org: "acme", project: parsed.projectSlug }); + default: + return Promise.reject(new Error("auto-detect is not resolved")); + } + }, + ); }); describe("getOrAskForProjectData", () => { @@ -153,16 +179,19 @@ describe("getOrAskForProjectData", () => { expect(mocks.listOrganizations).not.toHaveBeenCalled(); }); - it("uses the stored login and the --org and --project slugs", async () => { + it("uses the stored login and the / target", async () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + ACME_WEB, + process.cwd(), + "wizard", + ); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); expect(result).toEqual({ spotlight: false, @@ -178,16 +207,14 @@ describe("getOrAskForProjectData", () => { }); }); - it("asks for the project when the --project slug is not found", async () => { + it("asks for the project when the target's project is not found", async () => { mocks.getProject.mockRejectedValue(new ApiError("Not found", 404)); mocks.listProjects.mockResolvedValue([PROJECT]); mocks.select.mockResolvedValueOnce(PROJECT); const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "missing", + target: { type: "explicit", org: "acme", project: "missing" }, }); expect(mocks.listProjects).toHaveBeenCalledWith("acme"); @@ -207,7 +234,7 @@ describe("getOrAskForProjectData", () => { }); const result = await getOrAskForProjectData( - { telemetryEnabled: false, saas: true, orgSlug: "acme" }, + { telemetryEnabled: false, target: { type: "org-all", org: "acme" } }, "javascript-nextjs", ); @@ -223,9 +250,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.createOrgAuthToken).not.toHaveBeenCalled(); @@ -238,9 +263,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalledWith({ @@ -253,7 +276,7 @@ describe("getOrAskForProjectData", () => { mocks.runInteractiveLogin.mockResolvedValue(null); await expect( - getOrAskForProjectData({ telemetryEnabled: false, saas: true }), + getOrAskForProjectData({ telemetryEnabled: false }), ).rejects.toThrow(WizardExitError); }); @@ -263,9 +286,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - url: "https://sentry.example.com", - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).toHaveBeenCalled(); @@ -276,8 +297,7 @@ describe("getOrAskForProjectData", () => { const result = await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.runInteractiveLogin).not.toHaveBeenCalled(); @@ -293,8 +313,7 @@ describe("getOrAskForProjectData", () => { await getOrAskForProjectData({ telemetryEnabled: false, - orgSlug: "acme", - projectSlug: "web", + target: ACME_WEB, }); expect(mocks.warn).toHaveBeenCalledWith( @@ -307,14 +326,68 @@ describe("getOrAskForProjectData", () => { it("claims an agent handoff and uses its org", async () => { vi.stubEnv("SENTRY_HANDOFF", "handoff-code"); mocks.completeAgentHandoff.mockResolvedValue({ organizationSlug: "acme" }); + mocks.listOrganizations.mockResolvedValue([ + ORG, + { id: "2", slug: "other", name: "Other" }, + ]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(PROJECT); - await getOrAskForProjectData({ + await getOrAskForProjectData({ telemetryEnabled: false }); + + expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + expect(mocks.select).toHaveBeenCalledTimes(1); + expect(mocks.listProjects).toHaveBeenCalledWith("acme"); + }); + + it("asks for the org and project when no target is given", async () => { + const other = { id: "2", slug: "other", name: "Other" }; + mocks.listOrganizations.mockResolvedValue([ORG, other]); + mocks.listProjects.mockResolvedValue([PROJECT]); + mocks.select.mockResolvedValueOnce(ORG).mockResolvedValueOnce(PROJECT); + + const result = await getOrAskForProjectData({ telemetryEnabled: false, - saas: true, - projectSlug: "web", + target: { type: "auto-detect" }, }); - expect(mocks.completeAgentHandoff).toHaveBeenCalledWith("handoff-code"); + // Nothing is detected from the project's files or the CLI defaults. + expect(mocks.resolveOrgOptionalTarget).not.toHaveBeenCalled(); + expect(mocks.select).toHaveBeenCalledTimes(2); + expect(result).toMatchObject({ selectedProject: { slug: "web" } }); + }); + + it("resolves a bare project slug like other commands' targets", async () => { + const target: ParsedOrgProject = { + type: "project-search", + projectSlug: "web", + }; + + await getOrAskForProjectData({ telemetryEnabled: false, target }); + + expect(mocks.resolveOrgOptionalTarget).toHaveBeenCalledWith( + target, + process.cwd(), + "wizard", + ); + expect(mocks.select).not.toHaveBeenCalled(); expect(mocks.getProject).toHaveBeenCalledWith("acme", "web"); }); + + it("uses the CLI's instance for a preselected project", async () => { + mocks.getApiBaseUrl.mockReturnValue("https://sentry.example.com"); + const project: SentryProjectData = { + id: "7", + slug: "app", + organization: { id: "1", name: "Acme", slug: "acme" }, + keys: [{ dsn: { public: "https://k@sentry.example.com/7" } }], + }; + + const result = await getOrAskForProjectData({ + telemetryEnabled: false, + preSelectedProject: { project, authToken: "tok", selfHosted: true }, + }); + + expect(result).toMatchObject({ sentryUrl: "https://sentry.example.com/" }); + }); }); From 4c93aa845158ef8dff95134aa339c58c31b1af02 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:23:37 +0000 Subject: [PATCH 07/18] fix(cli): use the credential host for the project issues URL Re-export buildProjectIssuesUrl from lib/sentry-web-urls.ts through withSentryBaseUrl(getApiBaseUrl()), like the other user-facing link builders, so self-hosted and regional logins get links on the host they are authenticated against. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/sentry-web-urls.ts | 8 ++++++++ packages/cli/test/lib/sentry-urls.credential.test.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/packages/cli/src/lib/sentry-web-urls.ts b/packages/cli/src/lib/sentry-web-urls.ts index 2207e6a9d1..f4805167f0 100644 --- a/packages/cli/src/lib/sentry-web-urls.ts +++ b/packages/cli/src/lib/sentry-web-urls.ts @@ -11,6 +11,7 @@ import { buildMetricAlertsUrl as buildMetricAlertsUrlPure, buildOrgSettingsUrl as buildOrgSettingsUrlPure, buildOrgUrl as buildOrgUrlPure, + buildProjectIssuesUrl as buildProjectIssuesUrlPure, buildProjectUrl as buildProjectUrlPure, buildReleaseUrl as buildReleaseUrlPure, buildReplayUrl as buildReplayUrlPure, @@ -56,6 +57,13 @@ export function buildEventSearchUrl(orgSlug: string, eventId: string): string { return render(() => buildEventSearchUrlPure(orgSlug, eventId)); } +export function buildProjectIssuesUrl( + orgSlug: string, + projectId: string, +): string { + return render(() => buildProjectIssuesUrlPure(orgSlug, projectId)); +} + export function buildOrgSettingsUrl(orgSlug: string, hash?: string): string { return render(() => buildOrgSettingsUrlPure(orgSlug, hash)); } diff --git a/packages/cli/test/lib/sentry-urls.credential.test.ts b/packages/cli/test/lib/sentry-urls.credential.test.ts index 38e9d87bed..e5000fe361 100644 --- a/packages/cli/test/lib/sentry-urls.credential.test.ts +++ b/packages/cli/test/lib/sentry-urls.credential.test.ts @@ -3,6 +3,7 @@ import { setAuthToken } from "../../src/lib/db/auth.js"; import { resetEnvTokenHostForTesting } from "../../src/lib/env-token-host.js"; import { buildOrgUrl, + buildProjectIssuesUrl, buildProjectUrl, getSentryBaseUrl, isSaaS, @@ -40,6 +41,9 @@ describe("web URLs for active credential hosts", () => { expect(buildProjectUrl("acme", "site")).toBe( "https://sentry.example.com/settings/acme/projects/site/", ); + expect(buildProjectIssuesUrl("acme", "42")).toBe( + "https://sentry.example.com/organizations/acme/issues/?project=42", + ); }); test("stored OAuth host wins over an inactive environment token", () => { From cbdf2f7659cf53c238e1f51385a68c61ec1fd61a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:42:38 +0000 Subject: [PATCH 08/18] feat(cli): add iOS, Apple Snapshots and React Native to sentry wizard Port the `ios`, `appleSnapshots` and `reactNative` flows of @sentry/wizard 9.1.0 into `sentry wizard`, with their tests and Xcode fixtures, and register them in WIZARD_RUNNERS. The command gains the Apple flags of the old wizard (`--app-target`, `--hosted-test-target`, `--non-interactive`, hidden `--xcode-project-dir`), so existing `npx @sentry/wizard -i ios ...` command lines keep parsing. The flows no longer depend on the `sentry-cli` binary, because sentry.io/get-cli installs `sentry` once v4 ships: - The Xcode build phase runs `sentry debug-files upload` with SENTRY_ORG and SENTRY_PROJECT exported, checks for a v4 `sentry` with `sentry debug-files --help`, and turns failures into Xcode warnings with v4 install instructions. - The wizard checks only that `sentry` is on the PATH Xcode build phases see, and prints the Homebrew, curl and npm install commands when it is not. It no longer installs a CLI itself. - `.sentryclirc` gets `[defaults]` org and project next to the token, since v4 reads both. - The Apple Snapshots hint and preflight use `sentry snapshots upload`. - Existing-script detection recognizes both the v2 and v4 command forms, in the Apple and React Native Xcode code. xml-js is replaced by a small scanner for the two XML shapes the Snapshots flow reads (scheme TestAction blueprints and xcschememanagement.plist keys). xcode stays as a devDependency until the init/wizard unification. --- packages/cli/package.json | 1 + .../skills/sentry-cli/references/wizard.md | 3 + packages/cli/src/commands/wizard.ts | 37 + .../cli/src/lib/wizard/apple/apple-wizard.ts | 132 + .../lib/wizard/apple/check-installed-cli.ts | 77 + .../cli/src/lib/wizard/apple/code-tools.ts | 184 ++ .../lib/wizard/apple/configure-fastlane.ts | 57 + .../lib/wizard/apple/configure-sentry-cli.ts | 88 + .../wizard/apple/configure-xcode-project.ts | 35 + packages/cli/src/lib/wizard/apple/fastlane.ts | 175 + .../lib/wizard/apple/inject-code-snippet.ts | 49 + .../lib/wizard/apple/lookup-xcode-project.ts | 127 + .../lib/wizard/apple/macos-system-helper.ts | 92 + packages/cli/src/lib/wizard/apple/options.ts | 15 + .../apple/search-xcode-project-at-path.ts | 61 + .../lib/wizard/apple/sentry-swift-package.ts | 25 + .../apple/snapshots/apple-snapshots-wizard.ts | 352 ++ ...onfigure-snapshotpreviews-xcode-project.ts | 82 + .../apple/snapshots/snapshot-test-file.ts | 157 + .../snapshots/snapshot-verification-scheme.ts | 119 + .../snapshots/snapshotpreviews-package.ts | 12 + .../snapshots/snapshots-cli-preflight.ts | 147 + .../lib/wizard/apple/snapshots/xml-scan.ts | 92 + .../cli/src/lib/wizard/apple/templates.ts | 132 + .../cli/src/lib/wizard/apple/xcode-manager.ts | 2117 ++++++++++++ .../apple/xcode-project-object-with-id.ts | 9 + .../src/lib/wizard/react-native/cocoapod.ts | 139 + .../lib/wizard/react-native/expo-env-file.ts | 67 + .../src/lib/wizard/react-native/expo-metro.ts | 268 ++ .../cli/src/lib/wizard/react-native/expo.ts | 231 ++ .../cli/src/lib/wizard/react-native/git.ts | 69 + .../cli/src/lib/wizard/react-native/glob.ts | 26 + .../cli/src/lib/wizard/react-native/gradle.ts | 35 + .../src/lib/wizard/react-native/javascript.ts | 439 +++ .../cli/src/lib/wizard/react-native/metro.ts | 493 +++ .../src/lib/wizard/react-native/options.ts | 7 + .../react-native/react-native-wizard.ts | 538 ++++ .../cli/src/lib/wizard/react-native/xcode.ts | 246 ++ packages/cli/src/lib/wizard/run.ts | 20 + .../abort-if-sportlight-not-supported.ts | 20 + packages/cli/src/lib/wizard/utils/bash.ts | 23 + packages/cli/src/lib/wizard/utils/files.ts | 52 + .../wizard/utils/find-files-with-extension.ts | 21 + packages/cli/src/lib/wizard/utils/types.ts | 24 + packages/cli/src/lib/wizard/xcode.d.ts | 566 ++++ .../cli/test/fixtures/wizard/apple/.gitignore | 2 + .../Project.xcodeproj/project.pbxproj | 52 + .../xcshareddata/xcschemes/Project1.xcscheme | 78 + .../Project.xcodeproj/project.pbxproj | 330 ++ .../xcshareddata/xcschemes/Project.xcscheme | 78 + .../Project.xcodeproj/project.pbxproj | 62 + .../xcshareddata/xcschemes/Project1.xcscheme | 78 + .../Subfolder 1-1-1/File-1-1-1-1.swift | 7 + .../Subfolder 1-1-1/File-1-1-1-2.swift | 1 + .../Subgroup 1-1-2/File-1-1-2-1.swift | 2 + .../Group 1/Subgroup 1-2/File-1-2-1.swift | 2 + .../Group 1/Subgroup 1-2/File-1-2-2.swift | 2 + .../File-1-2-3--relative-to-group.swift | 1 + .../File-1-2-3--relative-to-project.swift | 1 + .../Group Reference 1-3/File-1-3-1.swift | 1 + .../Project.xcodeproj/project.pbxproj | 633 ++++ .../xcshareddata/xcschemes/Project.xcscheme | 78 + .../Project_2/AppDelegate.swift | 15 + .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 35 + .../Project_2/Assets.xcassets/Contents.json | 6 + .../Base.lproj/LaunchScreen.storyboard | 25 + .../Project_2/Base.lproj/Main.storyboard | 24 + .../Project_2/Info.plist | 25 + .../Project_2/SceneDelegate.swift | 8 + .../Project_2/ViewController.swift | 8 + .../Sources/MainApp.swift | 14 + .../Sources/Subfolder 1/ContentView.swift | 7 + .../Sources/Subfolder 1/Excluded-File.swift | 1 + .../Sources/Subfolder 2/File.swift | 2 + .../Project.xcodeproj/project.pbxproj | 470 +++ .../xcshareddata/xcschemes/Project1.xcscheme | 78 + .../Project1/ContentView.swift | 7 + .../Project1/Project1App.swift | 10 + .../Project2/ContentView.swift | 7 + .../Project2/Project2App.swift | 10 + .../Project.xcodeproj/project.pbxproj | 336 ++ .../xcshareddata/xcschemes/Project.xcscheme | 78 + .../Sources/MainApp.swift | 10 + .../Sources/Subfolder 1/ContentView.swift | 7 + .../Project.xcodeproj/project.pbxproj | 338 ++ .../xcshareddata/xcschemes/Project.xcscheme | 78 + .../Sources/ContentView.swift | 7 + .../Sources/MainApp.swift | 10 + .../wizard/apple/check-installed-cli.test.ts | 62 + .../test/lib/wizard/apple/code-tools.test.ts | 1255 ++++++++ .../wizard/apple/configure-sentry-cli.test.ts | 149 + .../test/lib/wizard/apple/fastfile.test.ts | 542 ++++ .../wizard/apple/lookup-xcode-project.test.ts | 216 ++ .../apple/macos-system-helper-mocked.test.ts | 55 + .../wizard/apple/macos-system-helper.test.ts | 147 + .../snapshots/apple-snapshots-wizard.test.ts | 583 ++++ .../snapshots/hosted-test-target-fixture.ts | 225 ++ .../snapshots/snapshot-test-file.test.ts | 121 + .../snapshot-verification-scheme.test.ts | 183 ++ .../snapshotpreviews-xcode-smoke.test.ts | 263 ++ .../snapshots/snapshots-cli-preflight.test.ts | 179 ++ .../snapshots/source-file-insertion.test.ts | 80 + .../wizard/apple/snapshots/xml-scan.test.ts | 109 + .../test/lib/wizard/apple/templates.test.ts | 269 ++ .../lib/wizard/apple/xcode-manager.test.ts | 2824 +++++++++++++++++ .../lib/wizard/react-native/cocoapod.test.ts | 428 +++ .../wizard/react-native/expo-metro.test.ts | 81 + .../test/lib/wizard/react-native/expo.test.ts | 256 ++ .../test/lib/wizard/react-native/git.test.ts | 246 ++ .../lib/wizard/react-native/gradle.test.ts | 184 ++ .../wizard/react-native/javascript.test.ts | 1024 ++++++ .../lib/wizard/react-native/metro.test.ts | 454 +++ .../lib/wizard/react-native/xcode.test.ts | 474 +++ packages/cli/test/tsconfig.json | 2 +- pnpm-lock.yaml | 82 + 116 files changed, 21188 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/lib/wizard/apple/apple-wizard.ts create mode 100644 packages/cli/src/lib/wizard/apple/check-installed-cli.ts create mode 100644 packages/cli/src/lib/wizard/apple/code-tools.ts create mode 100644 packages/cli/src/lib/wizard/apple/configure-fastlane.ts create mode 100644 packages/cli/src/lib/wizard/apple/configure-sentry-cli.ts create mode 100644 packages/cli/src/lib/wizard/apple/configure-xcode-project.ts create mode 100644 packages/cli/src/lib/wizard/apple/fastlane.ts create mode 100644 packages/cli/src/lib/wizard/apple/inject-code-snippet.ts create mode 100644 packages/cli/src/lib/wizard/apple/lookup-xcode-project.ts create mode 100644 packages/cli/src/lib/wizard/apple/macos-system-helper.ts create mode 100644 packages/cli/src/lib/wizard/apple/options.ts create mode 100644 packages/cli/src/lib/wizard/apple/search-xcode-project-at-path.ts create mode 100644 packages/cli/src/lib/wizard/apple/sentry-swift-package.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/configure-snapshotpreviews-xcode-project.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/snapshot-test-file.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/snapshot-verification-scheme.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/snapshotpreviews-package.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/snapshots-cli-preflight.ts create mode 100644 packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts create mode 100644 packages/cli/src/lib/wizard/apple/templates.ts create mode 100644 packages/cli/src/lib/wizard/apple/xcode-manager.ts create mode 100644 packages/cli/src/lib/wizard/apple/xcode-project-object-with-id.ts create mode 100644 packages/cli/src/lib/wizard/react-native/cocoapod.ts create mode 100644 packages/cli/src/lib/wizard/react-native/expo-env-file.ts create mode 100644 packages/cli/src/lib/wizard/react-native/expo-metro.ts create mode 100644 packages/cli/src/lib/wizard/react-native/expo.ts create mode 100644 packages/cli/src/lib/wizard/react-native/git.ts create mode 100644 packages/cli/src/lib/wizard/react-native/glob.ts create mode 100644 packages/cli/src/lib/wizard/react-native/gradle.ts create mode 100644 packages/cli/src/lib/wizard/react-native/javascript.ts create mode 100644 packages/cli/src/lib/wizard/react-native/metro.ts create mode 100644 packages/cli/src/lib/wizard/react-native/options.ts create mode 100644 packages/cli/src/lib/wizard/react-native/react-native-wizard.ts create mode 100644 packages/cli/src/lib/wizard/react-native/xcode.ts create mode 100644 packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts create mode 100644 packages/cli/src/lib/wizard/utils/bash.ts create mode 100644 packages/cli/src/lib/wizard/utils/files.ts create mode 100644 packages/cli/src/lib/wizard/utils/find-files-with-extension.ts create mode 100644 packages/cli/src/lib/wizard/xcode.d.ts create mode 100644 packages/cli/test/fixtures/wizard/apple/.gitignore create mode 100644 packages/cli/test/fixtures/wizard/apple/damaged-missing-configuration-list/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/damaged-missing-configuration-list/Project.xcodeproj/xcshareddata/xcschemes/Project1.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/no-files-in-target/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/no-files-in-target/Project.xcodeproj/xcshareddata/xcschemes/Project.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/no-targets/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/no-targets/Project.xcodeproj/xcshareddata/xcschemes/Project1.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-1/Subfolder 1-1-1/File-1-1-1-1.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-1/Subfolder 1-1-1/File-1-1-1-2.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-1/Subgroup 1-1-2/File-1-1-2-1.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-2/File-1-2-1.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-2/File-1-2-2.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-2/File-1-2-3--relative-to-group.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group 1/Subgroup 1-2/File-1-2-3--relative-to-project.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Group Reference 1-3/File-1-3-1.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project.xcodeproj/xcshareddata/xcschemes/Project.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/AppDelegate.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Assets.xcassets/Contents.json create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Base.lproj/LaunchScreen.storyboard create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Base.lproj/Main.storyboard create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/Info.plist create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/SceneDelegate.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Project_2/ViewController.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Sources/MainApp.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Sources/Subfolder 1/ContentView.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Sources/Subfolder 1/Excluded-File.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/project-with-synchronized-folders/Sources/Subfolder 2/File.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project.xcodeproj/xcshareddata/xcschemes/Project1.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project1/ContentView.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project1/Project1App.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project2/ContentView.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-multi-targets/Project2/Project2App.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-single-target/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-single-target/Project.xcodeproj/xcshareddata/xcschemes/Project.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-single-target/Sources/MainApp.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/spm-swiftui-single-target/Sources/Subfolder 1/ContentView.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/xcode-15-compatible-project/Project.xcodeproj/project.pbxproj create mode 100644 packages/cli/test/fixtures/wizard/apple/xcode-15-compatible-project/Project.xcodeproj/xcshareddata/xcschemes/Project.xcscheme create mode 100644 packages/cli/test/fixtures/wizard/apple/xcode-15-compatible-project/Sources/ContentView.swift create mode 100644 packages/cli/test/fixtures/wizard/apple/xcode-15-compatible-project/Sources/MainApp.swift create mode 100644 packages/cli/test/lib/wizard/apple/check-installed-cli.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/code-tools.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/configure-sentry-cli.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/fastfile.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/lookup-xcode-project.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/macos-system-helper-mocked.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/macos-system-helper.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/apple-snapshots-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/hosted-test-target-fixture.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/snapshot-test-file.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/snapshot-verification-scheme.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/snapshotpreviews-xcode-smoke.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/snapshots-cli-preflight.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/source-file-insertion.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/snapshots/xml-scan.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/apple/xcode-manager.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/cocoapod.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/expo-metro.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/expo.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/git.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/gradle.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/javascript.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/metro.test.ts create mode 100644 packages/cli/test/lib/wizard/react-native/xcode.test.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index 0e1e679f24..504f8adc57 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -153,6 +153,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/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index 7e8405f3e0..b38f01b4f2 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -26,6 +26,9 @@ Set up the Sentry SDK in your project interactively - `--ignore-git-changes - Don't ask before changing a project with uncommitted changes` - `--disable-telemetry - Don't send telemetry about this run to Sentry` - `--debug - Print the wizard's debug output` +- `--app-target - Xcode app target that hosts Swift previews (Apple Snapshots)` +- `--hosted-test-target - Hosted XCTest target to configure (Apple Snapshots)` +- `--non-interactive - Fail instead of prompting when a choice is ambiguous` **Examples:** diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 71f4b7fefd..50647fec93 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -14,6 +14,7 @@ import type { SentryContext } from "../context.js"; import { buildCommand } from "../lib/command.js"; import { + parseDirectoryPath, parseOrgSlug, parseProjectSlug, parseText, @@ -45,6 +46,10 @@ type WizardFlags = { readonly "skip-connect": boolean; readonly quiet: boolean; readonly uninstall: boolean; + readonly "xcode-project-dir"?: string; + readonly "app-target"?: string; + readonly "hosted-test-target"?: string; + readonly "non-interactive": boolean; }; /** @@ -173,6 +178,34 @@ export const wizardCommand = buildCommand({ brief: "Print the wizard's debug output", default: false, }, + "app-target": { + kind: "parsed", + parse: parseText, + brief: "Xcode app target that hosts Swift previews (Apple Snapshots)", + placeholder: "target", + optional: true, + }, + "hosted-test-target": { + kind: "parsed", + parse: parseText, + brief: "Hosted XCTest target to configure (Apple Snapshots)", + placeholder: "target", + optional: true, + }, + "non-interactive": { + kind: "boolean", + brief: "Fail instead of prompting when a choice is ambiguous", + default: false, + }, + // Internal `@sentry/wizard` option: where the Xcode project lives. + "xcode-project-dir": { + kind: "parsed", + parse: parseDirectoryPath, + brief: "Directory that contains the Xcode project (Apple wizards)", + placeholder: "dir", + optional: true, + hidden: true as const, + }, // `@sentry/wizard`'s sign-up and partner flags. The wizard logs in // with the CLI's login, which has no sign-up or partner step, so these // fail with an explanation instead of being dropped silently. @@ -241,6 +274,10 @@ export const wizardCommand = buildCommand({ forceInstall: flags["force-install"], ignoreGitChanges: flags["ignore-git-changes"], spotlight: flags.spotlight, + xcodeProjectDir: flags["xcode-project-dir"], + appTarget: flags["app-target"], + hostedTestTarget: flags["hosted-test-target"], + nonInteractive: flags["non-interactive"], }, }); } catch (error) { 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 0000000000..71a33d2050 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/apple-wizard.ts @@ -0,0 +1,132 @@ +/** + * The iOS wizard (`sentry wizard -i 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 0000000000..67c62a6f6e --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/check-installed-cli.ts @@ -0,0 +1,77 @@ +/** + * 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}). When `sentry` is in none of them, the wizard + * 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", + ]; +} + +/** How to install the Sentry CLI where an Xcode build phase finds it. */ +export const SENTRY_CLI_INSTALL_INSTRUCTIONS = [ + "Install the Sentry CLI with one of:", + " brew install getsentry/tools/sentry", + " curl https://cli.sentry.dev/install -fsS | bash", + " npm install -g sentry", +].join("\n"); + +/** 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`, warning with install + * instructions when it doesn't. + * + * @param warning - Explains what doesn't work without `sentry`. + * @returns The path of the `sentry` 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 cliPath = + whichSync("sentry", { PATH: searchDirs.join(path.delimiter) }) ?? undefined; + Sentry.setTag("has-cli", cliPath !== undefined); + if (cliPath) { + debug(`Xcode build phases will run ${cliPath}`); + return cliPath; + } + + clack.log.warn( + [ + warning, + "Xcode doesn't use your shell's PATH: it looks in", + `${searchDirs.join(", ")}.`, + "", + SENTRY_CLI_INSTALL_INSTRUCTIONS, + ].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 0000000000..24c4b0e110 --- /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 0000000000..ac2fd65f98 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/configure-fastlane.ts @@ -0,0 +1,57 @@ +/** + * 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 { 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 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 0000000000..5e5488e7a2 --- /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 0000000000..bc82e92680 --- /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 0000000000..de12622c36 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/fastlane.ts @@ -0,0 +1,175 @@ +/** + * 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); + lanes?.forEach((l) => (l.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 0000000000..bb5d6b641d --- /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 0000000000..7db9284cf6 --- /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 from a directory with a single .xcodeproj or pass --xcode-project-dir with a narrower project directory.", + ].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 0000000000..86e31be857 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/macos-system-helper.ts @@ -0,0 +1,92 @@ +/** + * Read macOS developer paths the Xcode project manager resolves group paths + * against: Xcode's developer directory, SDK roots, and derived data. + */ + +import { 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 { + // The child_process.execSync() method is generally identical to exec with the exception that the method will not return until the child process has fully closed. + // When a timeout has been encountered and killSignal is sent, the method won't return until the process has completely exited. + // If the child process intercepts and handles the SIGTERMsignal and doesn't exit, the parent process will wait until the child process has exited. + // + // If the process times out or has a non-zero exit code, this method will throw. + // The Error object will contain the entire result from spawnSync. + // + // IMPORTANT: + // Never pass unsanitized user input to this function. + // Any input containing shell metacharacters may be used to trigger arbitrary command execution. + const output = execSync( + [ + `xcodebuild`, + `-project`, + projectPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"'), + `-showBuildSettings`, + ] + .map((arg) => `"${arg.trim()}"`) + .join(" "), + { + 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 = {}; + lines.forEach((line) => { + 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 0000000000..6385312d21 --- /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 { + projectDir: string | undefined; +} + +export interface AppleSnapshotsWizardOptions extends AppleWizardOptions { + appTarget?: string | undefined; + hostedTestTarget?: string | undefined; + 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 0000000000..f5d55b872c --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/search-xcode-project-at-path.ts @@ -0,0 +1,61 @@ +/** + * 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:"); + projs.forEach((proj) => 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:"); + projs.forEach((proj) => 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 0000000000..6813180383 --- /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 0000000000..691c589dd6 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts @@ -0,0 +1,352 @@ +/** + * The Apple Snapshots wizard (`sentry wizard -i 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 (options.appTarget) { + if (appTargetNames.includes(options.appTarget)) { + return options.appTarget; + } + + clack.log.error( + `Xcode app target ${ + options.appTarget + } was not found. Available app targets: ${formatList(appTargetNames)}.`, + ); + return undefined; + } + + 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)}.`, + "Pass --app-target to select 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(); + if (options.hostedTestTarget) { + if (hostedTestTargetNames.includes(options.hostedTestTarget)) { + return options.hostedTestTarget; + } + + clack.log.error( + [ + `Hosted XCTest target ${options.hostedTestTarget} was not found or does not define TEST_HOST.`, + `Available hosted XCTest targets: ${formatList( + hostedTestTargetNames, + )}.`, + ].join(" "), + ); + return undefined; + } + + 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, + )}.`, + "Pass --hosted-test-target to select the target explicitly.", + 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 0000000000..0d9e5524f4 --- /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 0000000000..3f3f06704f --- /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 0000000000..a465d2fbf3 --- /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 0000000000..5318f81c84 --- /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 0000000000..99dc87c557 --- /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 0000000000..6bace0869c --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/snapshots/xml-scan.ts @@ -0,0 +1,92 @@ +/** + * 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. */ +function stripIgnoredMarkup(xml: string): string { + return xml.replace(IGNORED_MARKUP_RE, ""); +} + +/** + * 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 0000000000..2d437a695a --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/templates.ts @@ -0,0 +1,132 @@ +/** + * 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`. + * + * 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 + if ! ERROR=$(sentry debug-files upload ${ + uploadSource ? "--include-sources " : "" + }"$DWARF_DSYM_FOLDER_PATH" 2>&1 >/dev/null); then + echo "warning: sentry - $ERROR" + fi +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/)" +fi +`; +} + +/** + * Whether `shellScript` is a Sentry debug-file upload build phase: one the + * wizard generated with `sentry debug-files upload`, or an older one that + * runs `sentry-cli`. + */ +export function isSentryUploadScript(shellScript: string): boolean { + return ( + shellScript.includes("sentry-cli") || + /\bsentry\s+debug-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 0000000000..20175fa679 --- /dev/null +++ b/packages/cli/src/lib/wizard/apple/xcode-manager.ts @@ -0,0 +1,2117 @@ +/** + * 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, "") : ""; +} + +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(); + const escapedScript = script.replace(/"/g, '\\"'); + + // Create the shell script build phase object + const buildPhase = { + isa: "PBXShellScriptBuildPhase" as const, + buildActionMask: 2147483647, + files: [], + inputPaths, + outputPaths: [], + runOnlyForDeploymentPostprocessing: 0, + shellPath: "/bin/sh", + shellScript: `"${escapedScript}"`, + 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; + } + + const escapedScript = script.replace(/"/g, '\\"'); + buildPhase.shellScript = `"${escapedScript}"`; + 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 0000000000..804c3d321d --- /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 0000000000..53e97c6857 --- /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 0000000000..76b29d1a2b --- /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 0000000000..3c3d12df9f --- /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 0000000000..6031c72bf3 --- /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 0000000000..e1470c5b4e --- /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 0000000000..2836ace224 --- /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 0000000000..369d94e1ac --- /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 0000000000..113619e135 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/javascript.ts @@ -0,0 +1,439 @@ +/** + * 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; + } + + traceStep("add-sentry-init", () => { + const newContent = addSentryInitWithSdkImport(js, { + dsn, + enableSessionReplay, + enableFeedbackWidget, + enableLogs, + }); + + 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( + /^([^]*)(import\s+[^;]*?;$)/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 0000000000..bc50b7bc68 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/metro.ts @@ -0,0 +1,493 @@ +/** + * 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 { + 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 { + return b.callExpression(b.identifier("withSentryConfig"), [configObj]); +} + +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 0000000000..08853d3039 --- /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 0000000000..dfc627d517 --- /dev/null +++ b/packages/cli/src/lib/wizard/react-native/react-native-wizard.ts @@ -0,0 +1,538 @@ +/** + * The React Native wizard (`sentry wizard -i reactNative`): installs + * `@sentry/react-native`, initializes it, and sets up source map and debug + * file uploads for Xcode, Gradle, Metro and Expo. + */ + +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 { getIssueStreamUrl } from "../utils/url.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( + sentryUrl, + 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", + ), + ); + } +} + +async function confirmFirstSentryException( + url: string, + orgSlug: string, + projectId: string, +) { + const issuesStreamUrl = getIssueStreamUrl({ url, 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(` +