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/26] 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/26] 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/26] 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 16e618914ddb9d88886227cc97779712bab14a63 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:14:42 +0000 Subject: [PATCH 04/26] feat(cli): add Nuxt and Angular to sentry wizard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port the Nuxt and Angular flows of sentry-wizard 9.1.0 into `sentry wizard -i nuxt` and `sentry wizard -i angular`, with their tests. Angular uploads source maps with `sentry` commands. sentry-wizard ran its source maps wizard here with the Angular tool preselected; the flow now calls that tool's setup (`sourcemaps/tools/sentry-cli.ts`) and the CI step directly, since the other source maps steps are already done by then. The tool installs `sentry@^4` instead of `@sentry/cli@^2` and its `sentry:sourcemaps` script runs `sentry sourcemap inject` and `sentry sourcemap upload --org … --project …` instead of `sentry-cli sourcemaps …`. v4 has no `--url`, so self-hosted users are told to set `SENTRY_URL`. The CI step asks to run that script in CI again, as it did upstream. Errors that sentry-wizard sent with a raw `captureException` go through `reportCliError`; a missing or unparsable `angular.json` is logged with `debug()` instead, since it is not a bug. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 6 + .../src/lib/wizard/angular/angular-wizard.ts | 313 +++++++++++ .../lib/wizard/angular/codemods/app-config.ts | 267 ++++++++++ .../src/lib/wizard/angular/codemods/main.ts | 129 +++++ .../lib/wizard/angular/codemods/sourcemaps.ts | 110 ++++ .../lib/wizard/angular/example-component.ts | 295 ++++++++++ .../cli/src/lib/wizard/angular/sdk-setup.ts | 150 ++++++ .../cli/src/lib/wizard/nuxt/nuxt-wizard.ts | 238 +++++++++ .../cli/src/lib/wizard/nuxt/sdk-example.ts | 140 +++++ packages/cli/src/lib/wizard/nuxt/sdk-setup.ts | 322 +++++++++++ packages/cli/src/lib/wizard/nuxt/templates.ts | 503 ++++++++++++++++++ packages/cli/src/lib/wizard/nuxt/utils.ts | 54 ++ packages/cli/src/lib/wizard/run.ts | 8 + packages/cli/src/lib/wizard/sourcemaps/ci.ts | 9 +- .../lib/wizard/sourcemaps/tools/angular.ts | 49 ++ .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 360 +++++++++++++ .../src/lib/wizard/sourcemaps/tools/types.ts | 11 + .../abort-if-sportlight-not-supported.ts | 19 + .../lib/wizard/angular/angular-wizard.test.ts | 100 ++++ .../angular/codemods/app-config.test.ts | 52 ++ .../lib/wizard/angular/codemods/main.test.ts | 127 +++++ .../angular/codemods/sourcemaps.test.ts | 256 +++++++++ .../wizard/angular/example-component.test.ts | 105 ++++ .../test/lib/wizard/nuxt/sdk-setup.test.ts | 61 +++ .../test/lib/wizard/nuxt/templates.test.ts | 483 +++++++++++++++++ .../sourcemaps/tools/sentry-cli.test.ts | 91 ++++ 26 files changed, 4257 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/lib/wizard/angular/angular-wizard.ts create mode 100644 packages/cli/src/lib/wizard/angular/codemods/app-config.ts create mode 100644 packages/cli/src/lib/wizard/angular/codemods/main.ts create mode 100644 packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts create mode 100644 packages/cli/src/lib/wizard/angular/example-component.ts create mode 100644 packages/cli/src/lib/wizard/angular/sdk-setup.ts create mode 100644 packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts create mode 100644 packages/cli/src/lib/wizard/nuxt/sdk-example.ts create mode 100644 packages/cli/src/lib/wizard/nuxt/sdk-setup.ts create mode 100644 packages/cli/src/lib/wizard/nuxt/templates.ts create mode 100644 packages/cli/src/lib/wizard/nuxt/utils.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts create mode 100644 packages/cli/src/lib/wizard/sourcemaps/tools/types.ts create mode 100644 packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts create mode 100644 packages/cli/test/lib/wizard/angular/angular-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts create mode 100644 packages/cli/test/lib/wizard/angular/codemods/main.test.ts create mode 100644 packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts create mode 100644 packages/cli/test/lib/wizard/angular/example-component.test.ts create mode 100644 packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts create mode 100644 packages/cli/test/lib/wizard/nuxt/templates.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 1e49305bdb..92fa0dec46 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -22,3 +22,9 @@ changes nothing. `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. + +Flows that uploaded source maps with `@sentry/cli`, such as Angular, now +install the `sentry` package instead. The `sentry:sourcemaps` script they add +to `package.json` runs `sentry sourcemap inject` and `sentry sourcemap upload` +on your build output. On self-hosted Sentry, set `SENTRY_URL` wherever that +script runs. diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts new file mode 100644 index 0000000000..d4568669b5 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -0,0 +1,313 @@ +/** + * The Angular setup wizard: installs `@sentry/angular`, initializes it in + * `src/main.ts`, adds the Sentry providers to the app config, turns on + * source maps in `angular.json`, sets up their upload with `sentry + * sourcemap` commands, and optionally creates an example component. + */ + +import path from "node:path"; +import chalk from "chalk"; +import { gte, minVersion } from "semver"; +import { setupCI } from "../sourcemaps/ci.js"; +import { configureAngularSourcemapGenerationFlow } from "../sourcemaps/tools/angular.js"; +import { configureSentryCLI } from "../sourcemaps/tools/sentry-cli.js"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + abort, + abortIfCancelled, + askShouldCreateExampleComponent, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + featureSelectionPrompt, + getOrAskForProjectData, + getPackageDotJson, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { debug } from "../utils/debug.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { WizardOptions } from "../utils/types.js"; +import { addSourcemapEntryToAngularJSON } from "./codemods/sourcemaps.js"; +import { createExampleComponent } from "./example-component.js"; +import { + initializeSentryOnApplicationEntry, + updateAppConfig, +} from "./sdk-setup.js"; + +const MIN_SUPPORTED_ANGULAR_VERSION = "14.0.0"; +const MIN_SUPPORTED_WIZARD_ANGULAR_VERSION = "17.0.0"; + +/** Run the Angular wizard (`sentry wizard -i angular`). */ +export async function runAngularWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "angular", + wizardOptions: options, + }, + () => runAngularWizardWithTelemetry(options), + ); +} + +async function runAngularWizardWithTelemetry( + options: WizardOptions, +): Promise { + printWelcome({ + wizardName: "Sentry Angular Wizard", + promoCode: options.promoCode, + telemetryEnabled: options.telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "@angular/core", "Angular"); + + let installedAngularVersion = getPackageVersion("@angular/core", packageJson); + + if (!installedAngularVersion) { + clack.log.warn("Could not determine installed Angular version."); + + installedAngularVersion = await abortIfCancelled( + clack.text({ + message: `Please enter your installed Angular major version (e.g. ${chalk.cyan( + "18", + )} for Angular 18)`, + validate(value) { + if (!value) { + return "Angular version is required"; + } + + try { + if (!minVersion(value)) { + return `Invalid Angular version provided: ${value}`; + } + } catch (error) { + // Not fatal: an unparsable version is reported as invalid input. + debug(error); + return `Invalid Angular version provided: ${value}`; + } + return undefined; + }, + }), + ); + } + + Sentry.setTag("angular-version", installedAngularVersion); + + const installedMinVersion = minVersion(installedAngularVersion); + if (!installedMinVersion) { + clack.log.warn( + `Could not parse the Angular version ${chalk.cyan(installedAngularVersion)}.`, + ); + return await abort("Exiting the wizard."); + } + + const sdkSupportsAngularVersion = gte( + installedMinVersion, + MIN_SUPPORTED_ANGULAR_VERSION, + ); + + const wizardSupportsAngularVersion = gte( + installedMinVersion, + MIN_SUPPORTED_WIZARD_ANGULAR_VERSION, + ); + + if (!sdkSupportsAngularVersion) { + Sentry.setTag("angular-version-compatible", false); + + clack.log.warn( + `Angular version ${chalk.cyan( + MIN_SUPPORTED_ANGULAR_VERSION, + )} or higher is required for the Sentry SDK.`, + ); + clack.log.warn( + `Please refer to Sentry's version compatibility table for more information: + +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#angular-version-compatibility", +)} +`, + ); + + return await abort("Exiting the wizard.", 0); + } + + if (!wizardSupportsAngularVersion) { + Sentry.setTag("angular-wizard-version-compatible", false); + + clack.log.warn( + `The Sentry Angular Wizard requires Angular version ${chalk.cyan( + MIN_SUPPORTED_WIZARD_ANGULAR_VERSION, + )} or higher.`, + ); + clack.log.warn( + `Your Angular version (${installedAngularVersion}) is compatible with the Sentry SDK but you need to set it up manually by following our documentation: + +${chalk.underline("https://docs.sentry.io/platforms/javascript/guides/angular")} + +Apologies for the inconvenience!`, + ); + + return await abort("Exiting the wizard.", 0); + } + + const projectData = await getOrAskForProjectData( + options, + "javascript-angular", + ); + + if (projectData.spotlight) { + return await abortIfSpotlightNotSupported("Angular"); + } + + const { selectedProject, authToken, sentryUrl, selfHosted } = projectData; + + const dsn = selectedProject.keys[0].dsn.public; + + const sdkAlreadyInstalled = hasPackageInstalled( + "@sentry/angular", + packageJson, + ); + + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/angular", packageJson); + + await installPackage({ + packageName: "@sentry/angular@^11", + packageNameDisplayLabel: "@sentry/angular", + alreadyInstalled: sdkAlreadyInstalled, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/angular", + await getPackageDotJson(), + ); + + // 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") && + (await askShouldReduceDataCollection()); + + 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); + + await traceStep( + "Initialize Sentry on Angular application entry point", + async () => { + await initializeSentryOnApplicationEntry( + dsn, + selectedFeatures, + reduceDataCollection, + ); + }, + ); + + await traceStep("Update Angular project configuration", async () => { + await updateAppConfig(installedMinVersion, selectedFeatures.performance); + }); + + await traceStep("Setup for sourcemap uploads", async () => { + await addSourcemapEntryToAngularJSON(); + + // sentry-wizard ran its source maps wizard with the Angular tool + // preselected here. Its other steps (redirect to a framework wizard, SDK + // version check, project selection) are already done by this point, so + // run the Angular tool setup and the CI step directly. + await configureSentryCLI( + { + orgSlug: selectedProject.organization.slug, + projectSlug: selectedProject.slug, + selfHosted, + url: sentryUrl, + authToken, + defaultArtifactPath: `.${path.sep}dist`, + }, + configureAngularSourcemapGenerationFlow, + true, + ); + + await setupCI("angular", authToken, options.comingFrom); + }); + + const shouldCreateExampleComponent = await askShouldCreateExampleComponent(); + + Sentry.setTag("create-example-component", shouldCreateExampleComponent); + + if (shouldCreateExampleComponent) { + await traceStep( + "create-example-component", + async () => + await createExampleComponent({ + url: sentryUrl, + orgSlug: selectedProject.organization.slug, + projectId: selectedProject.id, + }), + ); + } + + await traceStep("Run Prettier", async () => { + await runPrettierIfInstalled({ cwd: undefined }); + }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro(buildOutroMessage(shouldCreateExampleComponent)); +} + +/** The closing message, with how to test the example component if one was created. */ +export function buildOutroMessage(createdExampleComponent: boolean): string { + let msg = chalk.green("Successfully installed the Sentry Angular SDK!"); + + if (createdExampleComponent) { + msg += `\n\nYou can validate your setup by starting your dev environment (${chalk.cyan( + "ng serve", + )}) and throwing an error in the example component.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: +https://docs.sentry.io/platforms/javascript/guides/angular/`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/app-config.ts b/packages/cli/src/lib/wizard/angular/codemods/app-config.ts new file mode 100644 index 0000000000..3b0b41974f --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/app-config.ts @@ -0,0 +1,267 @@ +/** + * Codemod for the Angular app config (`src/app/app.config.ts`): adds the + * Sentry `ErrorHandler` provider and, with tracing, the `TraceService` and + * its app initializer (`provideAppInitializer` from Angular 19 on, + * `APP_INITIALIZER` before). + */ + +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import type { ProxifiedModule } from "magicast"; +import recast from "recast"; +import { gte, type SemVer } from "semver"; +import { clack } from "../../utils/clack/prompts.js"; + +/** Add the Sentry imports and providers to the app config module. */ +export function updateAppConfigMod( + originalAppConfigMod: ProxifiedModule, + angularVersion: SemVer, + isTracingEnabled: boolean, +): ProxifiedModule { + const isAboveAngularV19 = gte(angularVersion, "19.0.0"); + + addImports(originalAppConfigMod, isAboveAngularV19, isTracingEnabled); + addProviders(originalAppConfigMod, isAboveAngularV19, isTracingEnabled); + + return originalAppConfigMod; +} +function addSentryImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasSentryImport = imports.$items.some( + (item) => item.from === "@sentry/angular", + ); + + if (!hasSentryImport) { + imports.$add({ + from: "@sentry/angular", + imported: "*", + local: "Sentry", + }); + } +} + +function addErrorHandlerImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasErrorHandler = imports.$items.some( + (item) => item.local === "ErrorHandler" && item.from === "@angular/core", + ); + + if (!hasErrorHandler) { + imports.$add({ + from: "@angular/core", + imported: "ErrorHandler", + local: "ErrorHandler", + }); + } +} +function addRouterImport(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + const hasRouter = imports.$items.some( + (item) => item.local === "Router" && item.from === "@angular/router", + ); + + if (!hasRouter) { + imports.$add({ + from: "@angular/router", + imported: "Router", + local: "Router", + }); + } +} + +function addMissingImportsV19(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + + const hasProvideAppInitializer = imports.$items.some( + (item) => + item.local === "provideAppInitializer" && item.from === "@angular/core", + ); + + if (!hasProvideAppInitializer) { + imports.$add({ + from: "@angular/core", + imported: "provideAppInitializer", + local: "provideAppInitializer", + }); + } + + const hasInject = imports.$items.some( + (item) => item.local === "inject" && item.from === "@angular/core", + ); + + if (!hasInject) { + imports.$add({ + from: "@angular/core", + imported: "inject", + local: "inject", + }); + } +} +function addAppInitializer(originalAppConfigMod: ProxifiedModule): void { + const imports = originalAppConfigMod.imports; + + const hasAppInitializer = imports.$items.some( + (item) => item.local === "APP_INITIALIZER" && item.from === "@angular/core", + ); + + if (!hasAppInitializer) { + imports.$add({ + from: "@angular/core", + imported: "APP_INITIALIZER", + local: "APP_INITIALIZER", + }); + } +} + +function addImports( + originalAppConfigMod: ProxifiedModule, + isAboveAngularV19: boolean, + isTracingEnabled: boolean, +): void { + addSentryImport(originalAppConfigMod); + addErrorHandlerImport(originalAppConfigMod); + + if (isTracingEnabled) { + addRouterImport(originalAppConfigMod); + } + + if (isAboveAngularV19) { + addMissingImportsV19(originalAppConfigMod); + } else if (isTracingEnabled) { + addAppInitializer(originalAppConfigMod); + } +} + +function addProviders( + originalAppConfigMod: ProxifiedModule, + isAboveAngularV19: boolean, + isTracingEnabled: boolean, +): void { + const b = recast.types.builders; + + recast.visit(originalAppConfigMod.exports.$ast, { + visitExportNamedDeclaration(path) { + if ( + path.node.declaration?.type !== "VariableDeclaration" || + path.node.declaration.declarations[0]?.type !== "VariableDeclarator" || + path.node.declaration.declarations[0].id.type !== "Identifier" || + path.node.declaration.declarations[0].id.name !== "appConfig" || + path.node.declaration.declarations[0].init?.type !== "ObjectExpression" + ) { + return; + } + + const appConfigProps = + path.node.declaration.declarations[0].init.properties; + + const providersProperty = appConfigProps.find( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "providers", + // type cast is safe because we already check the type in the find condition + ) as t.ObjectProperty | undefined; + + const validProviders = + providersProperty?.value.type === "ArrayExpression" + ? providersProperty.value + : undefined; + + if (!validProviders) { + return; + } + + // Check if there is already an ErrorHandler provider + const hasErrorHandlerProvider = validProviders.elements.some( + (element) => + element?.type === "ObjectExpression" && + element.properties.some( + (prop) => + prop.type === "ObjectProperty" && + prop.key.type === "Identifier" && + prop.key.name === "provide" && + prop.value.type === "Identifier" && + prop.value.name === "ErrorHandler", + ), + ); + + // If there is already an ErrorHandler provider, we skip adding it and log a message + if (hasErrorHandlerProvider) { + clack.log.warn(`ErrorHandler provider already exists in your app config. +Please refer to the Sentry Angular SDK documentation to combine it manually with Sentry's ErrorHandler. +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/features/error-handler/", +)} +`); + } else { + const errorHandlerObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("ErrorHandler"), + ), + b.objectProperty( + b.identifier("useValue"), + b.identifier("Sentry.createErrorHandler()"), + ), + ]); + + validProviders.elements.push(errorHandlerObject); + } + + if (isTracingEnabled) { + const traceServiceObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("Sentry.TraceService"), + ), + b.objectProperty( + b.identifier("deps"), + b.arrayExpression([b.identifier("Router")]), + ), + ]); + validProviders.elements.push(traceServiceObject); + + if (isAboveAngularV19) { + const provideAppInitializerCall = b.callExpression( + b.identifier("provideAppInitializer"), + [ + b.arrowFunctionExpression( + [], + b.blockStatement([ + b.expressionStatement( + b.callExpression(b.identifier("inject"), [ + b.identifier("Sentry.TraceService"), + ]), + ), + ]), + ), + ], + ); + validProviders.elements.push(provideAppInitializerCall); + } else { + const provideAppInitializerObject = b.objectExpression([ + b.objectProperty( + b.identifier("provide"), + b.identifier("APP_INITIALIZER"), + ), + b.objectProperty( + b.identifier("useFactory"), + b.arrowFunctionExpression( + [], + b.arrowFunctionExpression([], b.blockStatement([])), + ), + ), + b.objectProperty( + b.identifier("deps"), + b.arrayExpression([b.identifier("Sentry.TraceService")]), + ), + b.objectProperty(b.identifier("multi"), b.booleanLiteral(true)), + ]); + validProviders.elements.push(provideAppInitializerObject); + } + } + + this.traverse(path); + }, + }); +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/main.ts b/packages/cli/src/lib/wizard/angular/codemods/main.ts new file mode 100644 index 0000000000..637f9ba3b5 --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/main.ts @@ -0,0 +1,129 @@ +/** + * Codemod for the Angular application entry (`src/main.ts`): imports + * `@sentry/angular` and inserts `Sentry.init()` after the imports. + */ + +import type { namedTypes as t } from "ast-types"; +import { + builders, + generateCode, + type Proxified, + type ProxifiedModule, +} from "magicast"; +import { getDataCollectionSnippet } from "../../utils/data-collection.js"; + +/** Add the Sentry import and `Sentry.init()` call to the entry module. */ +export function updateAppEntryMod( + originalAppModuleMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): ProxifiedModule { + originalAppModuleMod.imports.$add({ + from: "@sentry/angular", + imported: "*", + local: "Sentry", + }); + + insertInitCall( + originalAppModuleMod, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + return originalAppModuleMod; +} + +/** Insert `Sentry.init()` with the selected features after the last import. */ +function insertInitCall( + originalAppModuleMod: ProxifiedModule, + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): void { + const initCallArgs = getInitCallArgs(dsn, selectedFeatures); + const initCall = builders.functionCall("Sentry.init", initCallArgs); + const originalAppModuleModAst = originalAppModuleMod.$ast as t.Program; + + const initCallInsertionIndex = getAfterImportsInsertionIndex( + originalAppModuleModAst, + ); + const generatedInitCode = generateCode(initCall).code; + // Magicast can't express comments inside an options object, so splice the + // commented `dataCollection` preset into the generated code before the + // closing `})`. + const initCode = reduceDataCollection + ? generatedInitCode.replace( + /\n\}\)$/, + `,\n${getDataCollectionSnippet(" ")}\n})`, + ) + : generatedInitCode; + + // magicast's proxied AST turns a code string into its statement node. + originalAppModuleModAst.body.splice( + initCallInsertionIndex, + 0, + initCode as unknown as (typeof originalAppModuleModAst.body)[number], + ); +} + +type InitCallArgs = Record< + string, + string | number | boolean | Array | Record +>; + +/** The options object of `Sentry.init()` for the selected features. */ +export function getInitCallArgs( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, +): InitCallArgs { + const initCallArgs: InitCallArgs = { + dsn, + }; + + if (selectedFeatures.replay || selectedFeatures.performance) { + const integrations: Proxified[] = []; + initCallArgs["integrations"] = integrations; + + if (selectedFeatures.performance) { + integrations.push( + builders.functionCall("Sentry.browserTracingIntegration"), + ); + initCallArgs["tracesSampleRate"] = 1.0; + } + + if (selectedFeatures.replay) { + integrations.push(builders.functionCall("Sentry.replayIntegration")); + + initCallArgs["replaysSessionSampleRate"] = 0.1; + initCallArgs["replaysOnErrorSampleRate"] = 1.0; + } + } + + return initCallArgs; +} + +/** + * We want to insert the handleError function just after all imports + */ +function getAfterImportsInsertionIndex( + originalEntryServerModAST: t.Program, +): number { + for (let x = originalEntryServerModAST.body.length - 1; x >= 0; x--) { + if (originalEntryServerModAST.body[x]?.type === "ImportDeclaration") { + return x + 1; + } + } + + return 0; +} diff --git a/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts b/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts new file mode 100644 index 0000000000..2c7768696c --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/codemods/sourcemaps.ts @@ -0,0 +1,110 @@ +/** + * Turn on source maps for the production build of every project in + * `angular.json`, or show the manual steps when that file can't be edited. + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { reportCliError } from "../../../error-reporting.js"; +import { configureAngularSourcemapGenerationFlow } from "../../sourcemaps/tools/angular.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; + +interface PartialAngularJson { + projects?: Record< + string, + { + architect?: { + build?: { + configurations?: { + production?: { + sourceMap?: boolean; + } & Record; + }; + }; + }; + } + >; +} + +/** Set `sourceMap: true` on the production build of each `angular.json` project. */ +export async function addSourcemapEntryToAngularJSON(): Promise { + const angularJsonPath = path.join(process.cwd(), "angular.json"); + const angularJson = getParsedAngularJson(angularJsonPath); + + if (!angularJson || typeof angularJson !== "object") { + await configureAngularSourcemapGenerationFlow(); + return; + } + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + if (!updatedAngularJson) { + await configureAngularSourcemapGenerationFlow(); + return; + } + + try { + writeFileSync(angularJsonPath, JSON.stringify(updatedAngularJson, null, 2)); + } catch (error) { + clack.log.error(`Failed to write sourcemap configuration to angular.json`); + reportCliError(error); + await configureAngularSourcemapGenerationFlow(); + } +} + +/** + * Extracted from `addSourcemapEntryToAngularJSON` and exported to allow for easier testing. + */ +export function addSourceMapsSetting( + angularJson: PartialAngularJson, +): PartialAngularJson | undefined { + const newAngularJson = { ...angularJson }; + + const projectKeys = Object.keys(newAngularJson.projects || {}); + + if (!projectKeys.length || !newAngularJson.projects) { + return undefined; + } + + // Emit sourcemaps from all projects in angular.json + for (const projectKey of projectKeys) { + const projectConfig = newAngularJson.projects[projectKey]; + if (!projectConfig) { + continue; + } + + if (!projectConfig.architect) { + projectConfig.architect = {}; + } + + if (!projectConfig.architect.build) { + projectConfig.architect.build = {}; + } + + if (!projectConfig.architect.build.configurations) { + projectConfig.architect.build.configurations = {}; + } + + projectConfig.architect.build.configurations.production = { + ...projectConfig.architect.build.configurations.production, + sourceMap: true, + }; + } + + return newAngularJson; +} + +function getParsedAngularJson( + angularJsonPath: string, +): PartialAngularJson | undefined { + try { + const angularJSONFile = readFileSync(angularJsonPath, "utf-8"); + return JSON.parse(angularJSONFile) as PartialAngularJson | undefined; + } catch (error) { + // Not fatal: without a readable angular.json, the caller shows the + // manual steps instead. A missing or hand-broken file is not a bug. + debug(error); + return undefined; + } +} diff --git a/packages/cli/src/lib/wizard/angular/example-component.ts b/packages/cli/src/lib/wizard/angular/example-component.ts new file mode 100644 index 0000000000..e0d3a81f8f --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/example-component.ts @@ -0,0 +1,295 @@ +/** + * Create an example Angular component that throws a test error, and show + * how to add it to a page. + */ + +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import chalk from "chalk"; +import { + abortIfCancelled, + makeCodeSnippet, + showCopyPasteInstructions, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { getIssueStreamUrl } from "../utils/url.js"; + +interface ExampleComponentOptions { + url: string; + orgSlug: string; + projectId: string; +} + +/** Write `sentry-example.component.ts` and show how to use it. */ +export async function createExampleComponent( + options: ExampleComponentOptions, +): Promise { + const componentName = "sentry-example"; + const appRootPath = "./src/app"; + + let componentDirPath = appRootPath; + const hasAppRoot = existsSync(appRootPath); + if (!hasAppRoot) { + componentDirPath = await abortIfCancelled( + clack.text({ + message: "Where should we create the example component?", + placeholder: appRootPath, + }), + ); + } + + if (!existsSync(componentDirPath)) { + mkdirSync(componentDirPath, { recursive: true }); + } + + const componentCode = getSentryExampleComponentCode(options); + + const componentFilePath = `${componentDirPath}/${componentName}.component.ts`; + + writeFileSync(componentFilePath, componentCode); + + clack.log.success( + `Created example component at ${chalk.cyan(componentFilePath)}`, + ); + + const addComponentCodeSnippet = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`${plus( + "import { SentryExample } from './sentry-example.component'", + )} + +@Component({ + selector: 'app-root', + standalone: true, + imports: [RouterOutlet, ${plus("SentryExample")}], + template: \` +
+

Your Application

+ ${plus("")} +
+ \`, +}) +`), + ); + + await showCopyPasteInstructions({ + instructions: `Add the example component one of your pages or components (for example, in ${chalk.cyan( + "app.component.ts", + )}).`, + codeSnippet: addComponentCodeSnippet, + }); +} + +/** The source of the example component. */ +export function getSentryExampleComponentCode( + options: ExampleComponentOptions, +): string { + const issueStreamUrl = getIssueStreamUrl(options); + + return `import { NgIf } from '@angular/common'; +import { Component, OnInit } from '@angular/core'; +import * as Sentry from '@sentry/angular'; + +/** + * This is just a very simple component that throws an example error. + * Feel free to delete this file once you verify that Sentry is working. + */ + +@Component({ + selector: 'app-sentry-example', + standalone: true, + imports: [NgIf], + template: \` + + + + +

app-sentry-example

+ +

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

+ + + +
+ Sample error was sent to Sentry. +
+
+ +
+

+ The Sentry SDK is not able to reach Sentry right now - this may be due + to an adblocker. For more information, see + the troubleshooting guide. +

+
+ +

+ Adblockers will prevent errors from being sent to Sentry. +

+ \`, + styles: \` + :host { + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + border: 2px solid #553DB8; + border-radius: 8px; + padding: 1em; + margin: 0.5em; + width: 500px; + height: 495px; + gap: 1em; + } + + h1 { + padding: 0px 4px; + border-radius: 4px; + background-color: rgba(24, 20, 35, 0.03); + font-family: monospace; + font-size: 20px; + line-height: 1.2; + } + + p { + margin: 0; + font-size: 20px; + } + + a { + color: #6341F0; + text-decoration: underline; + cursor: pointer; + + @media (prefers-color-scheme: dark) { + color: #B3A1FF; + } + } + + button { + border-radius: 8px; + color: white; + cursor: pointer; + background-color: #553DB8; + border: none; + padding: 0; + margin-top: 4px; + + & > span { + display: inline-block; + padding: 12px 16px; + border-radius: inherit; + font-size: 20px; + font-weight: bold; + line-height: 1; + background-color: #7553FF; + border: 1px solid #553DB8; + transform: translateY(-4px); + } + + &:hover > span { + transform: translateY(-8px); + } + + &:active > span { + transform: translateY(0); + } + } + + .success { + padding: 12px 16px; + border-radius: 8px; + font-size: 20px; + line-height: 1; + background-color: #00F261; + border: 1px solid #00BF4D; + color: #181423; + } + + .success_placeholder { + height: 46px; + } + + .description { + text-align: center; + color: #6E6C75; + max-width: 500px; + line-height: 1.5; + font-size: 20px; + + @media (prefers-color-scheme: dark) { + color: #A49FB5; + } + } + + .connectivity-error { + padding: 12px 16px; + background-color: #E50045; + border-radius: 8px; + width: 500px; + color: #FFFFFF; + border: 1px solid #A80033; + text-align: center; + margin: 0; + max-width: 400px; + } + + .connectivity-error a { + color: #FFFFFF; + text-decoration: underline; + } + \`, +}) +export class SentryExample implements OnInit { + sentError = false; + isConnected = true; + + async ngOnInit(): Promise { + const res = await Sentry.diagnoseSdkConnectivity(); + this.isConnected = res !== 'sentry-unreachable'; + console.log({ res }); + } + + throwError() { + Sentry.startSpan( + { + name: 'Example Frontend Span', + op: 'test', + }, + () => { + this.sentError = true; + throw new SentryExampleError( + 'This error was thrown by the Sentry example component.' + ); + } + ); + } +} + +class SentryExampleError extends Error { + constructor(message: string | undefined) { + super(message); + this.name = 'SentryExampleError'; + } +} +`; +} diff --git a/packages/cli/src/lib/wizard/angular/sdk-setup.ts b/packages/cli/src/lib/wizard/angular/sdk-setup.ts new file mode 100644 index 0000000000..210d7d73be --- /dev/null +++ b/packages/cli/src/lib/wizard/angular/sdk-setup.ts @@ -0,0 +1,150 @@ +/** + * Add Sentry to an Angular app: `Sentry.init()` in `src/main.ts` and the + * Sentry providers in `src/app/app.config.ts`. + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; +import type { namedTypes as t } from "ast-types"; +import chalk from "chalk"; +import { loadFile, writeFile } from "magicast"; +import type { SemVer } from "semver"; +import { Sentry } from "../telemetry.js"; +import { hasSentryContent } from "../utils/ast-utils.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; +import { updateAppConfigMod } from "./codemods/app-config.js"; +import { updateAppEntryMod } from "./codemods/main.js"; + +/** Import Sentry and call `Sentry.init()` in `src/main.ts`. */ +export async function initializeSentryOnApplicationEntry( + dsn: string, + selectedFeatures: { + performance: boolean; + replay: boolean; + }, + reduceDataCollection: boolean, +): Promise { + const appEntryFilename = "main.ts"; + const appEntryPath = path.join(process.cwd(), "src", appEntryFilename); + + const originalAppEntry = await loadFile(appEntryPath); + + if (hasSentryContent(originalAppEntry.$ast as t.Program)) { + clack.log.warn( + `File ${chalk.cyan(appEntryFilename)} already contains Sentry. +Skipping adding Sentry functionality to ${chalk.cyan(appEntryFilename)}.`, + ); + + return; + } + + const updatedAppEntryMod = updateAppEntryMod( + originalAppEntry, + dsn, + selectedFeatures, + reduceDataCollection, + ); + + try { + await writeFile(updatedAppEntryMod.$ast, appEntryPath); + } catch (error: unknown) { + // Not fatal: the user gets the manual setup steps instead. + debug(error); + clack.log.error( + `Error while adding Sentry to ${chalk.cyan(appEntryFilename)}`, + ); + + clack.log.warn( + `Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`, + ); + + return; + } + + clack.log.success( + `Successfully initialized Sentry in ${chalk.cyan(appEntryFilename)}`, + ); +} + +/** Add the Sentry providers to `src/app/app.config.ts`. */ +export async function updateAppConfig( + angularVersion: SemVer, + isTracingEnabled: boolean, +): Promise { + const appConfigFilename = "app.config.ts"; + const appConfigPath = path.join( + process.cwd(), + "src", + "app", + appConfigFilename, + ); + + if (!existsSync(appConfigPath)) { + Sentry.setTag("angular-app-config-found", false); + + clack.log.warn( + `File ${chalk.cyan( + appConfigFilename, + )} not found. Skipping adding Sentry functionality.`, + ); + + clack.log.warn(`Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`); + + return; + } + + Sentry.setTag("angular-app-config-found", true); + + const appConfig = await loadFile(appConfigPath); + + if (hasSentryContent(appConfig.$ast as t.Program)) { + clack.log.warn( + `File ${chalk.cyan(appConfigFilename)} already contains Sentry. + Skipping adding Sentry functionality to ${chalk.cyan(appConfigFilename)}.`, + ); + + return; + } + + try { + const updatedAppConfigMod = updateAppConfigMod( + appConfig, + angularVersion, + isTracingEnabled, + ); + + await writeFile(updatedAppConfigMod.$ast, appConfigPath); + } catch (error: unknown) { + clack.log.error( + `Error while updating your app config ${chalk.cyan(appConfigFilename)}.`, + ); + + clack.log.info( + chalk.dim( + error instanceof Error + ? error.toString() + : typeof error === "string" + ? error + : "", + ), + ); + + clack.log.warn(`Please refer to the documentation for manual setup: +${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/angular/#configure", +)}`); + + return; + } + + clack.log.success( + `Successfully updated your app config ${chalk.cyan(appConfigFilename)}`, + ); +} diff --git a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts new file mode 100644 index 0000000000..8294edb63e --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts @@ -0,0 +1,238 @@ +/** + * The Nuxt setup wizard: installs `@sentry/nuxt`, adds the Sentry Nuxt + * module to the Nuxt config, writes the client and server SDK configs and + * the auth token for source map uploads, and optionally creates an example + * page or component. + */ + +import chalk from "chalk"; +import { lt, minVersion } from "semver"; +import { Sentry, traceStep, withTelemetry } from "../telemetry.js"; +import { abortIfSpotlightNotSupported } from "../utils/abort-if-sportlight-not-supported.js"; +import { + abort, + abortIfCancelled, + addDotEnvSentryBuildPluginFile, + askShouldCreateExampleComponent, + askShouldCreateExamplePage, + confirmContinueIfNoOrDirtyGitRepo, + ensurePackageIsInstalled, + getOrAskForProjectData, + getPackageDotJson, + getPackageManager, + installPackage, + printSdkV11MigrationGuideIfOutdated, + printWelcome, + runPrettierIfInstalled, +} from "../utils/clack/index.js"; +import { offerProjectScopedMcpConfig } from "../utils/clack/mcp-config.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + askShouldReduceDataCollection, + sdkSupportsDataCollection, +} from "../utils/data-collection.js"; +import { warnIfNodeVersionUnsupportedBySdkV11 } from "../utils/node-version.js"; +import { + getPackageVersion, + hasPackageInstalled, +} from "../utils/package-json.js"; +import type { WizardOptions } from "../utils/types.js"; +import { + createExampleComponent, + createExamplePage, + supportsExamplePage, +} from "./sdk-example.js"; +import { + addNuxtOverrides, + addSDKModule, + createConfigFiles, + getNuxtConfig, +} from "./sdk-setup.js"; +import { isNuxtV4 } from "./utils.js"; + +/** Run the Nuxt wizard (`sentry wizard -i nuxt`). */ +export async function runNuxtWizard(options: WizardOptions): Promise { + return await withTelemetry( + { + enabled: options.telemetryEnabled, + integration: "nuxt", + wizardOptions: options, + }, + () => runNuxtWizardWithTelemetry(options), + ); +} + +async function runNuxtWizardWithTelemetry( + options: WizardOptions, +): Promise { + const { promoCode, telemetryEnabled, forceInstall } = options; + + printWelcome({ + wizardName: "Sentry Nuxt Wizard", + promoCode, + telemetryEnabled, + }); + + warnIfNodeVersionUnsupportedBySdkV11(); + + await confirmContinueIfNoOrDirtyGitRepo({ + ignoreGitChanges: options.ignoreGitChanges, + cwd: undefined, + }); + + const packageJson = await getPackageDotJson(); + + await ensurePackageIsInstalled(packageJson, "nuxt", "Nuxt"); + + const nuxtVersion = getPackageVersion("nuxt", packageJson); + Sentry.setTag("nuxt-version", nuxtVersion); + + const minVer = minVersion(nuxtVersion || "0.0.0"); + + if (!nuxtVersion || !minVer || lt(minVer, "3.7.0")) { + clack.log.warn( + "It seems you're using a Nuxt version <3.7.0 which is not supported by Sentry.\nWe recommend upgrading to the latest version before you continue.", + ); + const shouldContinue = await abortIfCancelled( + clack.select({ + message: "Do you want to continue anyway?", + options: [ + { + label: "Yes, continue", + hint: "The SDK might not work correctly", + value: true, + }, + { label: "No, I'll upgrade first", value: false }, + ], + }), + ); + if (!shouldContinue) { + await abort("Exiting Wizard", 0); + return; + } + } + + const projectDataResult = await getOrAskForProjectData( + options, + "javascript-nuxt", + ); + + if (projectDataResult.spotlight) { + return await abortIfSpotlightNotSupported("Nuxt"); + } + + const { authToken, selectedProject, selfHosted, sentryUrl } = + projectDataResult; + + const packageManager = await getPackageManager(); + + await addNuxtOverrides(packageManager, minVer); + + const sdkAlreadyInstalled = hasPackageInstalled("@sentry/nuxt", packageJson); + Sentry.setTag("sdk-already-installed", sdkAlreadyInstalled); + + printSdkV11MigrationGuideIfOutdated("@sentry/nuxt", packageJson); + + await installPackage({ + packageName: "@sentry/nuxt@^11", + alreadyInstalled: sdkAlreadyInstalled, + packageManager, + forceInstall, + }); + + // The install may have been skipped (user declined the update prompt), so + // re-read package.json to learn which SDK major is actually installed. + const installedSdkVersion = getPackageVersion( + "@sentry/nuxt", + await getPackageDotJson(), + ); + + // 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") && + (await askShouldReduceDataCollection()); + + await addDotEnvSentryBuildPluginFile(authToken); + + const nuxtConfig = await traceStep("load-nuxt-config", getNuxtConfig); + + const projectData = { + org: selectedProject.organization.slug, + project: selectedProject.slug, + projectId: selectedProject.id, + url: sentryUrl, + selfHosted, + }; + + await traceStep("configure-sdk", async () => { + await addSDKModule(nuxtConfig, projectData); + await createConfigFiles( + selectedProject.keys[0].dsn.public, + reduceDataCollection, + ); + }); + + let shouldCreateExamplePage = false; + let shouldCreateExampleButton = false; + + const isV4 = await isNuxtV4(nuxtConfig, nuxtVersion); + const canCreateExamplePage = await supportsExamplePage(isV4); + Sentry.setTag("supports-example-page-creation", canCreateExamplePage); + + if (canCreateExamplePage) { + shouldCreateExamplePage = await askShouldCreateExamplePage(); + + if (shouldCreateExamplePage) { + await traceStep( + "create-example-page", + async () => await createExamplePage(isV4, projectData), + ); + } + } else { + shouldCreateExampleButton = await askShouldCreateExampleComponent(); + + if (shouldCreateExampleButton) { + await traceStep( + "create-example-component", + async () => await createExampleComponent(isV4), + ); + } + } + + await runPrettierIfInstalled({ cwd: undefined }); + + // Offer optional project-scoped MCP config for Sentry with org and project scope + await offerProjectScopedMcpConfig( + selectedProject.organization.slug, + selectedProject.slug, + ); + + clack.outro( + buildOutroMessage(shouldCreateExamplePage, shouldCreateExampleButton), + ); +} + +function buildOutroMessage( + shouldCreateExamplePage: boolean, + shouldCreateExampleButton: boolean, +): string { + let msg = chalk.green("Successfully installed the Sentry Nuxt SDK!"); + + if (shouldCreateExamplePage) { + msg += `\n\nYou can validate your setup by visiting ${chalk.cyan( + '"/sentry-example-page"', + )}.`; + } + if (shouldCreateExampleButton) { + msg += `\n\nYou can validate your setup by adding the ${chalk.cyan( + "`SentryExampleButton`", + )} component to a page and triggering it.`; + } + + msg += `\n\nCheck out the SDK documentation for further configuration: ${chalk.underline( + "https://docs.sentry.io/platforms/javascript/guides/nuxt/", + )}`; + + return msg; +} diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-example.ts b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts new file mode 100644 index 0000000000..2dce84431a --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts @@ -0,0 +1,140 @@ +/** + * Create the Nuxt example page (with its API route) or the example error + * button component that the user can trigger to test Sentry. + */ + +import { existsSync, mkdirSync, promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { reportCliError } from "../../error-reporting.js"; +import { abort, isUsingTypeScript } from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { + getIndexRouteTemplate, + getSentryErrorButtonTemplate, + getSentryExampleApiTemplate, + getSentryExamplePageTemplate, +} from "./templates.js"; + +function getSrcDirectory(isNuxtV4: boolean): string { + // In nuxt v4, the src directory is `app/` unless + // users already had a `pages` directory + return isNuxtV4 && !existsSync(path.resolve("pages")) ? "app" : "."; +} + +/** Whether the app renders pages, so an example page would be reachable. */ +export async function supportsExamplePage(isNuxtV4: boolean): Promise { + // We currently only support creating an example page + // if users can reliably access it without having to + // add code changes themselves. + // + // If users have an `app.vue` layout without the + // needed component to render routes (), + // we bail out of creating an example page altogether. + const src = getSrcDirectory(isNuxtV4); + const app = path.join(src, "app.vue"); + + // If there's no `app.vue` layout, nuxt automatically renders + // the routes. + if (!existsSync(path.resolve(app))) { + return true; + } + + const content = await promises.readFile(path.resolve(app), "utf8"); + return !!content.match(/ { + try { + const src = getSrcDirectory(isNuxtV4); + const pages = path.join(src, "pages"); + + if (!existsSync(path.resolve(pages))) { + mkdirSync(path.resolve(pages), { recursive: true }); + + const indexPage = path.join(pages, "index.vue"); + + await promises.writeFile( + path.resolve(indexPage), + getIndexRouteTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(indexPage)}.`); + } + + const examplePage = path.join(pages, "sentry-example-page.vue"); + + if (existsSync(path.resolve(examplePage))) { + clack.log.warn( + `It seems like a sentry example page already exists. Skipping creation of example page.`, + ); + return; + } + + await promises.writeFile( + path.resolve(examplePage), + getSentryExamplePageTemplate(options), + ); + + clack.log.success(`Created ${chalk.cyan(examplePage)}.`); + + const api = path.join("server", "api"); + + if (!existsSync(path.resolve(api))) { + mkdirSync(path.resolve(api), { recursive: true }); + } + + const exampleApi = path.join( + api, + isUsingTypeScript() ? "sentry-example-api.ts" : "sentry-example-api.js", + ); + + await promises.writeFile( + path.resolve(exampleApi), + getSentryExampleApiTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(exampleApi)}.`); + } catch (e: unknown) { + clack.log.error("Error while creating an example page to test Sentry:"); + clack.log.info( + chalk.dim( + e instanceof Error + ? e.toString() + : typeof e === "string" + ? e + : "Unknown error", + ), + ); + reportCliError(e); + await abort("Exiting Wizard"); + } +} + +/** Write the `SentryErrorButton` example component. */ +export async function createExampleComponent(isNuxtV4: boolean): Promise { + const src = getSrcDirectory(isNuxtV4); + const components = path.join(src, "components"); + + if (!existsSync(path.resolve(components))) { + mkdirSync(path.resolve(components), { recursive: true }); + } + + const exampleComponent = path.join(components, "SentryErrorButton.vue"); + + await promises.writeFile( + path.resolve(exampleComponent), + getSentryErrorButtonTemplate(), + ); + + clack.log.success(`Created ${chalk.cyan(exampleComponent)}.`); +} diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts new file mode 100644 index 0000000000..597be6f9cf --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -0,0 +1,322 @@ +/** + * Set up `@sentry/nuxt` in a Nuxt project: the Sentry Nuxt module in the + * Nuxt config, the client and server SDK configs, and the `ofetch` override + * that Nuxt before 3.14 needs. + */ + +import { existsSync, promises, unlinkSync } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { generateCode, loadFile, type ProxifiedModule } from "magicast"; +import { addNuxtModule } from "magicast/helpers"; +import { lt, type SemVer } from "semver"; +import { Sentry, traceStep } from "../telemetry.js"; +import { + abortIfCancelled, + askShouldAddPackageOverride, + featureSelectionPrompt, + isUsingTypeScript, +} from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import type { PackageManager } from "../utils/package-manager.js"; +import { + getConfigBody, + getDefaultNuxtConfig, + getNuxtModuleFallbackTemplate, + getSentryConfigContents, +} from "./templates.js"; + +const possibleNuxtConfig = [ + "nuxt.config.js", + "nuxt.config.mjs", + "nuxt.config.cjs", + "nuxt.config.ts", + "nuxt.config.mts", + "nuxt.config.cts", +]; + +/** + * The path of the Nuxt config file, after creating `nuxt.config.ts` when + * there is none. + */ +export async function getNuxtConfig(): Promise { + let configFile = possibleNuxtConfig.find((fileName) => + existsSync(path.join(process.cwd(), fileName)), + ); + + if (!configFile) { + clack.log.info("No Nuxt config file found, creating a new one."); + Sentry.setTag("nuxt-config-strategy", "create"); + // nuxt recommends its config to be .ts by default + configFile = "nuxt.config.ts"; + + await promises.writeFile( + path.join(process.cwd(), configFile), + getDefaultNuxtConfig(), + { encoding: "utf-8", flag: "w" }, + ); + + clack.log.success(`Created ${chalk.cyan("nuxt.config.ts")}.`); + } + + return path.join(process.cwd(), configFile); +} + +/** Add `@sentry/nuxt/module` and its options to the Nuxt config. */ +export async function addSDKModule( + config: string, + options: { org: string; project: string; url: string; selfHosted: boolean }, +): Promise { + const failureTagKey = "modify-nuxt-config-error"; + + let module: ProxifiedModule; + + try { + module = await loadFile(config); + } catch (e) { + if (e instanceof Error) { + if (e instanceof SyntaxError || e.message.includes("Unexpected token")) { + Sentry.setTag(failureTagKey, "loadFile-failed-syntax-error"); + } else if ( + e.message.includes("ENOENT") || + e.message.includes("no such file") + ) { + Sentry.setTag(failureTagKey, "loadFile-failed-file-not-found"); + } + } else { + Sentry.setTag(failureTagKey, "loadFile-failed"); + } + + clack.log.error( + `Error while loading Nuxt config file: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + throw e; + } + + try { + addNuxtModule(module, "@sentry/nuxt/module", "sentry", { + org: options.org, + project: options.project, + ...(options.selfHosted && { sentryUrl: options.url }), + }); + } catch (e) { + Sentry.setTag(failureTagKey, "adding-sentry-options-failed"); + + clack.log.error( + `Error while modifying 'sentry' in Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + throw e; + } + + try { + addNuxtModule(module, "@sentry/nuxt/module", "sourcemap", { + client: "hidden", + }); + } catch (e) { + Sentry.setTag(failureTagKey, "adding-sourcemap-options-failed"); + + clack.log.error( + `Error while modifying 'sourcemap' in Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + throw e; + } + + let code: string; + + try { + ({ code } = generateCode(module)); + } catch (e) { + Sentry.setTag(failureTagKey, "generateCode-failed"); + + clack.log.error( + `Error while generating module code: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + throw e; + } + + try { + await promises.writeFile(config, code, { encoding: "utf-8", flag: "w" }); + + clack.log.success( + `Added Sentry Nuxt Module to ${chalk.cyan(path.basename(config))}.`, + ); + } catch (e: unknown) { + Sentry.setTag(failureTagKey, "writeFile-failed"); + + clack.log.error( + `Error while writing Nuxt config: ${ + e instanceof Error ? e.message : "Unknown" + }`, + ); + + showFallbackInstructions(config, options); + throw e; + } +} + +function showFallbackInstructions( + config: string, + options: { org: string; project: string; url: string; selfHosted: boolean }, +): void { + clack.log.warn( + `Please add the following settings to ${chalk.cyan( + path.basename(config), + )}:`, + ); + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(`\n\n${getNuxtModuleFallbackTemplate(options)}\n\n`); +} + +/** Ask for the features to enable, then write `sentry.{client,server}.config.{ts,js}`. */ +export async function createConfigFiles( + dsn: string, + reduceDataCollection: boolean, +): Promise { + 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", "client"] 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: string[] = []; + + 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), + getSentryConfigContents( + dsn, + configVariant, + selectedFeatures, + reduceDataCollection, + ), + { encoding: "utf8", flag: "w" }, + ); + clack.log.success( + `Created new ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )}.`, + ); + Sentry.setTag(`created-${configVariant}-config`, true); + } else { + clack.log.info( + `Okay, here are the changes your ${chalk.cyan( + typeScriptDetected ? tsConfig : jsConfig, + )} should contain:`, + ); + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput( + `\n\n ${getConfigBody(dsn, configVariant, selectedFeatures)}\n\n`, + ); + } + }); + } +} + +/** + * On Nuxt before 3.14, offer to override `ofetch` to `^1.4.0`, which Sentry + * needs to instrument the app. + */ +export async function addNuxtOverrides( + packageManager: PackageManager, + nuxtMinVer: SemVer | null, +): Promise { + if (!nuxtMinVer || !lt(nuxtMinVer, "3.14.0")) { + return; + } + + const pkgName = "ofetch"; + const pkgVersion = "^1.4.0"; + + clack.log.warn( + `To ensure Sentry can properly instrument your code it needs to add a version override for ${chalk.cyan( + pkgName, + )}.\n\nFor more info see: ${chalk.underline( + "https://github.com/getsentry/sentry-javascript/issues/14514", + )}`, + ); + + const shouldAddOverride = await askShouldAddPackageOverride( + pkgName, + pkgVersion, + ); + + if (shouldAddOverride) { + await packageManager.addOverride(pkgName, pkgVersion); + } +} diff --git a/packages/cli/src/lib/wizard/nuxt/templates.ts b/packages/cli/src/lib/wizard/nuxt/templates.ts new file mode 100644 index 0000000000..8b63a9ae2e --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/templates.ts @@ -0,0 +1,503 @@ +/** + * Code templates of the Nuxt wizard: the Nuxt config, the Sentry SDK + * configs, and the example page, API route, and component. + */ + +import { getDataCollectionSnippet } from "../utils/data-collection.js"; +import { getIssueStreamUrl } from "../utils/url.js"; + +type SelectedSentryFeatures = { + performance: boolean; + replay: boolean; +}; + +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/nuxt/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; +} + +export function getDefaultNuxtConfig(): string { + return `// https://nuxt.com/docs/api/configuration/nuxt-config +export default defineNuxtConfig({ + compatibilityDate: '2024-04-03', + devtools: { enabled: true } +}) +`; +} + +export function getNuxtModuleFallbackTemplate(options: { + org: string; + project: string; + url: string; + selfHosted: boolean; +}): string { + return ` modules: ["@sentry/nuxt/module"], + sentry: { + org: "${options.org}", + project: "${options.project}",${ + options.selfHosted ? `\n sentryUrl: "${options.url}",` : "" + } + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" },`; +} + +export function getSentryConfigContents( + dsn: string, + config: "client" | "server", + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + if (config === "client") { + return getSentryClientConfigContents( + dsn, + selectedFeatures, + reduceDataCollection, + ); + } + + return getSentryServerConfigContents( + dsn, + selectedFeatures, + reduceDataCollection, + ); +} + +const featuresConfigMap: Record = { + performance: [ + " // We recommend adjusting this value in production, or using tracesSampler", + " // for finer control", + " tracesSampleRate: 1.0,", + ].join("\n"), + replay: [ + " // 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,", + " ", + " // If the entire session is not sampled, use the below sample rate to sample", + " // sessions when an error occurs.", + " replaysOnErrorSampleRate: 1.0,", + " ", + " // If you don't want to use Session Replay, just remove the line below:", + " integrations: [Sentry.replayIntegration()],", + ].join("\n"), +}; + +const featuresMap: Record< + "client" | "server", + Array +> = { + client: ["performance", "replay"], + server: ["performance"], +}; + +export function getConfigBody( + dsn: string, + variant: "client" | "server", + selectedFeatures: SelectedSentryFeatures, +): string { + const features = Object.keys(selectedFeatures) as Array< + keyof SelectedSentryFeatures + >; + return [ + `dsn: "${dsn}",`, + features + .map((feature) => { + return featuresMap[variant].includes(feature) && + selectedFeatures[feature] + ? featuresConfigMap[feature] + : null; + }) + .filter(Boolean) + .join("\n\n"), + ] + .filter(Boolean) + .join("\n\n"); +} + +function getSentryClientConfigContents( + dsn: string, + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from "@sentry/nuxt"; + +Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + ${getConfigBody(dsn, "client", selectedFeatures)} + +${getDataCollectionBlock(reduceDataCollection)} + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, +}); +`; +} + +function getSentryServerConfigContents( + dsn: string, + selectedFeatures: SelectedSentryFeatures, + reduceDataCollection: boolean, +): string { + return `import * as Sentry from "@sentry/nuxt"; + +Sentry.init({ + ${getConfigBody(dsn, "server", selectedFeatures)} + +${getDataCollectionBlock(reduceDataCollection)} + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, +}); +`; +} + +export function getIndexRouteTemplate(): string { + return ` + +`; +} + +export function getSentryExamplePageTemplate(options: { + url: string; + org: string; + projectId: string; +}): string { + const { url, org, projectId } = options; + const issuesPageLink = getIssueStreamUrl({ url, orgSlug: org, projectId }); + + return ` + + + + + + + +`; +} + +export function getSentryExampleApiTemplate(): string { + return `// This is just a very simple API route that throws an example error. +// Feel free to delete this file. +import { defineEventHandler } from '#imports'; + +export default defineEventHandler(() => { + throw new Error("Sentry Example API Route Error"); +}); +`; +} + +export function getSentryErrorButtonTemplate(): string { + return ` + + + + + + +`; +} diff --git a/packages/cli/src/lib/wizard/nuxt/utils.ts b/packages/cli/src/lib/wizard/nuxt/utils.ts new file mode 100644 index 0000000000..4aabd45e28 --- /dev/null +++ b/packages/cli/src/lib/wizard/nuxt/utils.ts @@ -0,0 +1,54 @@ +/** + * Detect whether a Nuxt project runs Nuxt 4, either by its installed + * version or by `future.compatibilityVersion: 4` in its config. + */ + +import { gte, minVersion } from "semver"; +import { loadFile } from "magicast"; +import { abortIfCancelled } from "../utils/clack/index.js"; +import { clack } from "../utils/clack/prompts.js"; +import { debug } from "../utils/debug.js"; + +/** + * Whether the project uses Nuxt 4. + * + * @param nuxtConfig - Path of the Nuxt config file + * @param packageVersion - The `nuxt` version range from `package.json` + */ +export async function isNuxtV4( + nuxtConfig: string, + packageVersion: string | undefined, +): Promise { + if (!packageVersion) { + return false; + } + + const minVer = minVersion(packageVersion); + if (minVer && gte(minVer, "4.0.0")) { + return true; + } + + // At the time of writing, nuxt 4 is not on its own + // major yet. We must read the `compatibilityVersion` + // from the nuxt config. + try { + const mod = await loadFile(nuxtConfig); + const defaultExport = mod.exports["default"]; + const config = + defaultExport.$type === "function-call" + ? defaultExport.$args[0] + : defaultExport; + + if (config?.future?.compatibilityVersion === 4) { + return true; + } + } catch (error) { + // Not fatal: when the config can't be parsed, ask instead. + debug(error); + return await abortIfCancelled( + clack.confirm({ message: "Are you using Nuxt version 4?" }), + ); + } + + return false; +} diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 8bd377980b..7d9d6819d0 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -51,10 +51,18 @@ type WizardRunner = (options: WizardOptions) => Promise; * moved over from sentry-wizard. */ const WIZARD_RUNNERS: Partial> = { + angular: async (options) => { + const { runAngularWizard } = await import("./angular/angular-wizard.js"); + await runAngularWizard(options); + }, nextjs: async (options) => { const { runNextjsWizard } = await import("./nextjs/nextjs-wizard.js"); await runNextjsWizard(options); }, + nuxt: async (options) => { + const { runNuxtWizard } = await import("./nuxt/nuxt-wizard.js"); + await runNuxtWizard(options); + }, }; /** What `sentry wizard` passes to {@link runWizard}. */ diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index e725f44a51..310724de9b 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -14,6 +14,7 @@ import { } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; import type { WizardOptions } from "../utils/types.js"; +import { setupNpmScriptInCI } from "./tools/sentry-cli.js"; /** Tools that upload with `sentry` commands and read `.sentryclirc`. */ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ @@ -72,7 +73,9 @@ async function configureCI( Sentry.setTag("using-ci", isUsingCI); - const authTokenFile = CLI_BASED_FLOW_TOOLS.includes(selectedTool) + const isCliBasedFlowTool = CLI_BASED_FLOW_TOOLS.includes(selectedTool); + + const authTokenFile = isCliBasedFlowTool ? SENTRY_CLI_RC_FILE : SENTRY_DOT_ENV_FILE; @@ -85,6 +88,10 @@ async function configureCI( return; } + if (isCliBasedFlowTool) { + await traceStep("ci-npm-script-setup", setupNpmScriptInCI); + } + await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); } diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts new file mode 100644 index 0000000000..0a5a2485d3 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/angular.ts @@ -0,0 +1,49 @@ +/** + * The source map generation step for Angular: shows the `angular.json` + * setting that turns on source maps and asks the user to check it. + */ + +import { clack } from "../../utils/clack/prompts.js"; +import chalk from "chalk"; +import { abortIfCancelled, makeCodeSnippet } from "../../utils/clack/index.js"; + +/** The `angular.json` change that turns on source maps. */ +const angularJsonTemplate = makeCodeSnippet(true, (unchanged, plus) => + unchanged(`{ + "projects": { + 'your-project': { + "architect": { + "build": { + "options": { + ${plus(`"sourceMap": true`)} + }, + }, + } + } + } +}`), +); + +/** Show the `angular.json` change and wait until the user confirms it. */ +export async function configureAngularSourcemapGenerationFlow(): Promise { + clack.log.info( + `Enable generating source maps in your ${chalk.bold("angular.json")} file:`, + ); + + // Printed outside clack's gutter so that it can be copied/pasted directly + clack.rawOutput(angularJsonTemplate); + + await abortIfCancelled( + clack.select({ + message: `Verify that you are generating source maps when building your Angular app.`, + options: [ + { + label: "I checked!", + hint: "My build output folder contains .js.map files after a build.", + value: true, + }, + ], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts new file mode 100644 index 0000000000..b2d0b889f4 --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -0,0 +1,360 @@ +/** + * Source map upload with `sentry` commands, for build tools that have no + * Sentry bundler plugin (Angular, tsc, Create React App, …). + * + * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script + * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the + * build output, optionally appends it to the production build script, and + * writes the auth token to `.sentryclirc`. Ported from sentry-wizard's + * `src/sourcemaps/tools/sentry-cli.ts`, which installed `@sentry/cli` and + * ran `sentry-cli sourcemaps …`. + */ + +import { promises } from "node:fs"; +import path from "node:path"; +import chalk from "chalk"; +import { Sentry, traceStep } from "../../telemetry.js"; +import { + abortIfCancelled, + addSentryCliConfig, + artifactsExist, + askToRunBuildOrEnterPathOrProceed, + getPackageDotJson, + getPackageManager, + installPackage, +} from "../../utils/clack/index.js"; +import { clack } from "../../utils/clack/prompts.js"; +import { hasPackageInstalled } from "../../utils/package-json.js"; +import { NPM } from "../../utils/package-manager.js"; +import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; + +const SENTRY_NPM_SCRIPT_NAME = "sentry:sourcemaps"; + +let addedToBuildCommand = false; + +type configureSentryCLIOptions = SourceMapUploadToolConfigurationOptions & { + defaultArtifactPath?: string | undefined; +}; + +/** + * Set up source map upload with `sentry sourcemap` commands. + * + * @param options - The Sentry project to upload to, and the build output + * path to suggest + * @param configureSourcemapGenerationFlow - Asks the user to turn on source + * map generation in their build tool + * @param skipValidation - Skip `configureSourcemapGenerationFlow`, for flows + * that already turned source maps on + */ +export async function configureSentryCLI( + options: configureSentryCLIOptions, + configureSourcemapGenerationFlow: () => Promise = defaultConfigureSourcemapGenerationFlow, + skipValidation = false, +): Promise { + const packageDotJson = await getPackageDotJson(); + + await installPackage({ + packageName: "sentry@^4", + alreadyInstalled: hasPackageInstalled("sentry", packageDotJson), + }); + + let validPath = false; + let relativeArtifactPath: string | undefined; + do { + const rawArtifactPath = await abortIfCancelled( + clack.text({ + message: "Where are your build artifacts located?", + placeholder: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + initialValue: + relativeArtifactPath ?? + options.defaultArtifactPath ?? + `.${path.sep}out`, + validate(value) { + if (!value) { + return "Please enter a path."; + } + return undefined; + }, + }), + ); + + if (path.isAbsolute(rawArtifactPath)) { + relativeArtifactPath = path.relative(process.cwd(), rawArtifactPath); + } else { + relativeArtifactPath = rawArtifactPath; + } + + if (artifactsExist(relativeArtifactPath)) { + validPath = true; + continue; + } + + const runBuildOrEnterPathOrProceed = + await askToRunBuildOrEnterPathOrProceed({ + relativeArtifactPath, + }); + + validPath = runBuildOrEnterPathOrProceed.validPath; + relativeArtifactPath = + runBuildOrEnterPathOrProceed.relativeArtifactPath ?? relativeArtifactPath; + } while (!validPath); + + const relativePosixArtifactPath = relativeArtifactPath + .split(path.sep) + .join(path.posix.sep); + + if (!skipValidation) { + await configureSourcemapGenerationFlow(); + } + + await createAndAddNpmScript(options, relativePosixArtifactPath); + + if (await askShouldAddToBuildCommand()) { + await traceStep("sentry-cli-add-to-build-cmd", () => + addSentryCommandToBuildCommand(), + ); + } else { + clack.log.info( + `No problem, just make sure to run this script ${chalk.bold( + "after", + )} building your application but ${chalk.bold("before")} deploying!`, + ); + } + + await addSentryCliConfig({ authToken: options.authToken }); + + if (options.selfHosted) { + clack.log.info( + `Set ${chalk.cyan(`SENTRY_URL=${options.url}`)} wherever ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} runs, such as in CI, so that it uploads to your Sentry instance.`, + ); + } +} + +/** + * Ask the user to run the `sentry:sourcemaps` script in CI, unless the + * wizard already appended it to the build script. + */ +export async function setupNpmScriptInCI(): Promise { + if (addedToBuildCommand) { + // No need to tell users to add it manually to their CI + // if the script is already added to the build command + return; + } + + const addedToCI = await abortIfCancelled( + clack.select({ + message: `Add a step to your CI pipeline that runs the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script ${chalk.bold("right after")} building your application.`, + options: [ + { label: "I did, continue!", value: true }, + { + label: "I'll do it later...", + value: false, + hint: chalk.yellow( + `You need to run ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} after each build for source maps to work properly.`, + ), + }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("added-ci-script", addedToCI); + + if (!addedToCI) { + clack.log.info("Don't forget! :)"); + } +} + +/** + * The `sentry:sourcemaps` script: inject debug IDs into the build output, + * then upload it. v4 takes the org and project as flags on any command and + * the self-hosted URL from `SENTRY_URL` (or `.sentryclirc`), so the script + * has no `--url`. + */ +export function getSentryCliNpmScript( + options: Pick< + SourceMapUploadToolConfigurationOptions, + "orgSlug" | "projectSlug" + >, + relativePosixArtifactPath: string, +): string { + // The script runs the `sentry` binary of the package installed above, so + // it names `sentry` itself, not the program running the wizard. + // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint. + return `sentry sourcemap inject ${relativePosixArtifactPath} && sentry sourcemap upload --org ${options.orgSlug} --project ${options.projectSlug} ${relativePosixArtifactPath}`; +} + +async function createAndAddNpmScript( + options: SourceMapUploadToolConfigurationOptions, + relativePosixArtifactPath: string, +): Promise { + const sentryCliNpmScript = getSentryCliNpmScript( + options, + relativePosixArtifactPath, + ); + + const packageDotJson = await getPackageDotJson(); + + packageDotJson.scripts = packageDotJson.scripts || {}; + packageDotJson.scripts[SENTRY_NPM_SCRIPT_NAME] = sentryCliNpmScript; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + clack.log.info( + `Added a ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + "package.json", + )}.`, + ); +} + +async function askShouldAddToBuildCommand(): Promise { + const shouldAddToBuildCommand = await abortIfCancelled( + clack.select({ + message: `Do you want to automatically run the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script after each production build?`, + options: [ + { + label: "Yes", + value: true, + hint: "This will modify your prod build command", + }, + { label: "No", value: false }, + ], + initialValue: true, + }), + ); + + Sentry.setTag("modify-build-command", shouldAddToBuildCommand); + + return shouldAddToBuildCommand; +} + +/** + * Add the sentry:sourcemaps command to the prod build command in the package.json + * - Detect the user's build command + * - Append the sentry:sourcemaps command to it + * + * @param packageDotJson The package.json which will be modified. + */ +export async function addSentryCommandToBuildCommand(): Promise { + const packageDotJson = await getPackageDotJson(); + // This usually shouldn't happen because earlier we added the + // SENTRY_NPM_SCRIPT_NAME script but just to be sure + packageDotJson.scripts = packageDotJson.scripts || {}; + + const allNpmScripts = Object.keys(packageDotJson.scripts).filter( + (s) => s !== SENTRY_NPM_SCRIPT_NAME, + ); + + const packageManager = await getPackageManager(NPM); + + // Heuristic to pre-select the build command: + // Often, 'build' is the prod build command, so we favour it. + // If it's not there, commands that include 'build' might be the prod build command. + let buildCommand = + typeof packageDotJson.scripts["build"] === "string" + ? "build" + : allNpmScripts.find((s) => s.toLocaleLowerCase().includes("build")); + + const isProdBuildCommand = + !!buildCommand && + (await abortIfCancelled( + clack.confirm({ + message: `Is ${chalk.cyan( + `${packageManager.runScriptCommand} ${buildCommand}`, + )} your production build command?`, + }), + )); + + if (allNpmScripts.length && (!buildCommand || !isProdBuildCommand)) { + buildCommand = await abortIfCancelled( + clack.select({ + message: `Which ${packageManager.name} command in your ${chalk.cyan( + "package.json", + )} builds your application for production?`, + options: [ + ...allNpmScripts.map((script) => ({ + label: script, + value: script, + })), + { label: "None of the above", value: "none" }, + ], + }), + ); + } + + if (!buildCommand || buildCommand === "none") { + clack.log.warn( + `We can only add the ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} script to another \`script\` in your ${chalk.cyan("package.json")}. +Please add it manually to your prod build command.`, + ); + return; + } + + const oldCommand = packageDotJson.scripts[buildCommand]; + if (!oldCommand) { + // very unlikely to happen but nevertheless + clack.log.warn( + `\`${buildCommand}\` doesn't seem to be part of your package.json scripts`, + ); + return; + } + + const newCommand = `${oldCommand} && ${packageManager.runScriptCommand} ${SENTRY_NPM_SCRIPT_NAME}`; + + if (oldCommand.endsWith(SENTRY_NPM_SCRIPT_NAME)) { + clack.log.info( + `It seems like ${chalk.cyan( + SENTRY_NPM_SCRIPT_NAME, + )} is already part of your ${chalk.cyan( + buildCommand, + )} command. Will not add it again. +Current command: ${chalk.dim(oldCommand)} +Would have injected: ${chalk.dim(newCommand)}`, + ); + + return; + } + + packageDotJson.scripts[buildCommand] = newCommand; + + await promises.writeFile( + path.join(process.cwd(), "package.json"), + JSON.stringify(packageDotJson, null, 2), + ); + + addedToBuildCommand = true; + + clack.log.info( + `Added ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} script to your ${chalk.cyan( + buildCommand, + )} command.`, + ); +} + +async function defaultConfigureSourcemapGenerationFlow(): Promise { + await abortIfCancelled( + clack.select({ + message: `Verify that your build tool is generating source maps. ${chalk.dim( + "(Your build output folder should contain .js.map files after a build)", + )}`, + options: [{ label: "I checked. Continue!", value: true }], + initialValue: true, + }), + ); +} diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts new file mode 100644 index 0000000000..b1f26ce05a --- /dev/null +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/types.ts @@ -0,0 +1,11 @@ +/** + * Options the source map upload tool setups take. + */ + +export type SourceMapUploadToolConfigurationOptions = { + selfHosted: boolean; + url: string; + authToken: string; + orgSlug: string; + projectSlug: string; +}; diff --git a/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts new file mode 100644 index 0000000000..0aed208bf2 --- /dev/null +++ b/packages/cli/src/lib/wizard/utils/abort-if-sportlight-not-supported.ts @@ -0,0 +1,19 @@ +/** + * Stop a wizard flow that has no Spotlight mode yet. + */ + +import { abort } from "./clack/index.js"; +import { clack } from "./clack/prompts.js"; + +/** + * Aborts the wizard with a message that Spotlight mode is not yet supported + * for the given platform. + */ +export async function abortIfSpotlightNotSupported( + platform: string, +): Promise { + clack.log.warn(`Spotlight mode is not yet supported for ${platform}.`); + clack.log.info("Spotlight is currently only available for Next.js."); + + return await abort("Exiting wizard", 0); +} diff --git a/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts b/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts new file mode 100644 index 0000000000..dcde4e85a0 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/angular-wizard.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildOutroMessage } from "../../../../src/lib/wizard/angular/angular-wizard.js"; +import { getInitCallArgs } from "../../../../src/lib/wizard/angular/codemods/main.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("angular-wizard", () => { + describe("buildOutroMessage", () => { + it("returns the correct outro message if example component was created", () => { + expect(buildOutroMessage(true)).toMatchInlineSnapshot(` + "Successfully installed the Sentry Angular SDK! + + You can validate your setup by starting your dev environment (ng serve) and throwing an error in the example component. + + Check out the SDK documentation for further configuration: + https://docs.sentry.io/platforms/javascript/guides/angular/" + `); + }); + it("returns the correct outro message if example component creation was skipped", () => { + expect(buildOutroMessage(false)).toMatchInlineSnapshot(` + "Successfully installed the Sentry Angular SDK! + + Check out the SDK documentation for further configuration: + https://docs.sentry.io/platforms/javascript/guides/angular/" + `); + }); + }); + + describe("getInitCallArgs", () => { + it("returns the correct init call arguments when all features are enabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: true, + replay: true, + }); + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + {}, + ], + "replaysOnErrorSampleRate": 1, + "replaysSessionSampleRate": 0.1, + "tracesSampleRate": 1, + } + `); + }); + + it("returns the correct init call arguments when performance is disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: false, + replay: true, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + ], + "replaysOnErrorSampleRate": 1, + "replaysSessionSampleRate": 0.1, + } + `); + }); + + it("returns the correct init call arguments when replay is disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: true, + replay: false, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + "integrations": [ + {}, + ], + "tracesSampleRate": 1, + } + `); + }); + + it("returns the correct init call arguments when all features are disabled", () => { + const args = getInitCallArgs("https://example.com", { + performance: false, + replay: false, + }); + + expect(args).toMatchInlineSnapshot(` + { + "dsn": "https://example.com", + } + `); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts b/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts new file mode 100644 index 0000000000..2688dc5488 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/app-config.test.ts @@ -0,0 +1,52 @@ +import { generateCode, parseModule } from "magicast"; +import { SemVer } from "semver"; +import { describe, expect, it, vi } from "vitest"; +import { updateAppConfigMod } from "../../../../../src/lib/wizard/angular/codemods/app-config.js"; + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn() }, +})); + +const APP_CONFIG = `import { ApplicationConfig } from '@angular/core'; +import { provideRouter } from '@angular/router'; + +export const appConfig: ApplicationConfig = { + providers: [provideRouter(routes)], +}; +`; + +describe("updateAppConfigMod", () => { + it("adds the ErrorHandler, TraceService, and provideAppInitializer on Angular 19+", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("19.0.0"), true), + ); + + expect(code).toContain("import * as Sentry from '@sentry/angular';"); + expect(code).toContain("provide: ErrorHandler"); + expect(code).toContain("useValue: Sentry.createErrorHandler()"); + expect(code).toContain("provide: Sentry.TraceService"); + expect(code).toContain("provideAppInitializer(() => {"); + expect(code).not.toContain("APP_INITIALIZER"); + }); + + it("uses APP_INITIALIZER before Angular 19", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("18.2.0"), true), + ); + + expect(code).toContain("provide: APP_INITIALIZER"); + expect(code).not.toContain("provideAppInitializer"); + }); + + it("only adds the ErrorHandler without tracing", () => { + const mod = parseModule(APP_CONFIG); + const { code } = generateCode( + updateAppConfigMod(mod, new SemVer("19.0.0"), false), + ); + + expect(code).toContain("provide: ErrorHandler"); + expect(code).not.toContain("TraceService"); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/main.test.ts b/packages/cli/test/lib/wizard/angular/codemods/main.test.ts new file mode 100644 index 0000000000..279e7d2eac --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/main.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from "vitest"; +import { parseModule } from "magicast"; + +import { updateAppEntryMod } from "../../../../../src/lib/wizard/angular/codemods/main.js"; + +function getOriginalAppEntryMod() { + return parseModule(` + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); + `); +} + +describe("updateAppEntryMod", () => { + it("generates the init call without dataCollection when reduceDataCollection is false", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: true, replay: true }, + false, + ); + + const result = mod.generate().code; + + expect(result).not.toContain("dataCollection"); + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()], + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1 + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); + + it("generates the init call with the dataCollection preset when reduceDataCollection is true", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: true, replay: true }, + true, + ); + + const result = mod.generate().code; + + expect(result).toContain("userInfo: false"); + expect(result).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] }', + ); + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + integrations: [Sentry.browserTracingIntegration(), Sentry.replayIntegration()], + tracesSampleRate: 1, + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1, + // 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"] }, + }, + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); + + it("includes the dataCollection preset when all features are disabled", () => { + const mod = updateAppEntryMod( + getOriginalAppEntryMod(), + "https://sentry.io/123", + { performance: false, replay: false }, + true, + ); + + const result = mod.generate().code; + + expect(result).toMatchInlineSnapshot(` + "import * as Sentry from '@sentry/angular'; + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { AppComponent } from './app/app.component'; + + Sentry.init({ + dsn: "https://sentry.io/123", + // 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"] }, + }, + }) + + bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));" + `); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts b/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts new file mode 100644 index 0000000000..288bdcffa0 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/codemods/sourcemaps.test.ts @@ -0,0 +1,256 @@ +import { describe, it, vi, expect, beforeEach } from "vitest"; +import { + addSourcemapEntryToAngularJSON, + addSourceMapsSetting, +} from "../../../../../src/lib/wizard/angular/codemods/sourcemaps.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as AngularSourceMapsWizard from "../../../../../src/lib/wizard/sourcemaps/tools/angular.js"; + +const { readFileSyncMock, writeFileSyncMock } = vi.hoisted(() => { + return { + readFileSyncMock: vi.fn(), + writeFileSyncMock: vi.fn(), + }; +}); + +vi.mock("node:fs", async () => { + return { + ...(await vi.importActual("node:fs")), + readFileSync: readFileSyncMock, + writeFileSync: writeFileSyncMock, + }; +}); + +describe("addSourcemapEntryToAngularJSON", () => { + const configureAngularSourcemapGenerationFlowSpy = vi + .spyOn(AngularSourceMapsWizard, "configureAngularSourcemapGenerationFlow") + .mockImplementation(() => Promise.resolve()); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("reads and writes the `angular.json` file correctly", async () => { + const angularJsonPath = "angular.json"; + const angularJsonContent = JSON.stringify({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { + someKey: "someValue", + }, + }, + }, + }, + }, + }, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + + await addSourcemapEntryToAngularJSON(); + + expect(readFileSyncMock).toHaveBeenCalledWith( + expect.stringContaining(angularJsonPath), + "utf-8", + ); + expect(writeFileSyncMock).toHaveBeenCalledWith( + expect.stringContaining(angularJsonPath), + JSON.stringify( + { + projects: { + project1: { + architect: { + build: { + configurations: { + production: { + someKey: "someValue", + sourceMap: true, + }, + }, + }, + }, + }, + }, + }, + null, + 2, + ), + ); + }); + + it("falls back to printing copy/paste instructions when reading fails", async () => { + readFileSyncMock.mockImplementation(() => { + throw new Error("File not found"); + }); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).not.toHaveBeenCalled(); + }); + + it("falls back to printing copy/paste instructions when writing fails", async () => { + const angularJsonContent = JSON.stringify({ + projects: { + project1: {}, + }, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + writeFileSyncMock.mockImplementation(() => { + throw new Error("Write failed"); + }); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).toHaveBeenCalled(); + }); + + it("falls back to printing copy/paste instructions when angular.json` has no projects", async () => { + const angularJsonContent = JSON.stringify({ + projects: {}, + }); + + readFileSyncMock.mockReturnValue(angularJsonContent); + + await addSourcemapEntryToAngularJSON(); + + expect(configureAngularSourcemapGenerationFlowSpy).toHaveBeenCalledOnce(); + expect(writeFileSyncMock).not.toHaveBeenCalled(); + }); +}); + +describe("addSourceMapsSetting", () => { + it("adds sourceMap setting to angular.json", () => { + const angularJson = { + projects: { + project1: { + architect: { + build: { + configurations: { + production: {}, + }, + }, + }, + }, + project2: { + architect: {}, + }, + }, + }; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toEqual({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { sourceMap: true }, + }, + }, + }, + }, + project2: { + architect: { + build: { + configurations: { + production: { + sourceMap: true, + }, + }, + }, + }, + }, + }, + }); + }); + + it("returns `undefined` if no projects are found", () => { + const angularJson = {}; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toBeUndefined(); + }); + + it("returns `undefined` if projects have no architect", () => { + const angularJson = { + projects: {}, + }; + + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toBeUndefined(); + }); + + it.each([ + { + projects: { + project1: { + architect: { + build: { + configurations: { + production: {}, + }, + }, + }, + }, + }, + }, + { + projects: { + project1: { + architect: { + build: { + configurations: {}, + }, + }, + }, + }, + }, + { + projects: { + project1: { + architect: { + build: {}, + }, + }, + }, + }, + { + projects: { + project1: { + architect: {}, + }, + }, + }, + { + projects: { + project1: {}, + }, + }, + ])("handles incomplete project declarations (%s)", (angularJson) => { + const updatedAngularJson = addSourceMapsSetting(angularJson); + + expect(updatedAngularJson).toEqual({ + projects: { + project1: { + architect: { + build: { + configurations: { + production: { sourceMap: true }, + }, + }, + }, + }, + }, + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/angular/example-component.test.ts b/packages/cli/test/lib/wizard/angular/example-component.test.ts new file mode 100644 index 0000000000..70bf3bcc8d --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/example-component.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + createExampleComponent, + getSentryExampleComponentCode, +} from "../../../../src/lib/wizard/angular/example-component.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as clackUtils from "../../../../src/lib/wizard/utils/clack/index.js"; + +const fsMocks = vi.hoisted(() => ({ + existsSyncMock: vi.fn(() => true), + writeFileSyncMock: vi.fn(), + mkdirSyncMock: vi.fn(), +})); + +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + existsSync: fsMocks.existsSyncMock, + writeFileSync: fsMocks.writeFileSyncMock, + mkdirSync: fsMocks.mkdirSyncMock, +})); + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + step: 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(), +})); + +describe("createExampleComponent", () => { + const showCopyPasteSnippetSpy = vi.spyOn( + clackUtils, + "showCopyPasteInstructions", + ); + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("creates an example component file", async () => { + const options = { + url: "https://sentry.io", + orgSlug: "myOrg", + projectId: "123456789", + }; + + // Mock the abortIfCancelled function to return the appRootPath + vi.spyOn(clackUtils, "abortIfCancelled").mockResolvedValue("src/app"); + + // Mock the getSentryExampleComponentCode function + const exampleComponentCode = getSentryExampleComponentCode(options); + + // Call the function to create the example component + await createExampleComponent(options); + + expect(fsMocks.writeFileSyncMock).toHaveBeenCalledWith( + "./src/app/sentry-example.component.ts", + exampleComponentCode, + ); + expect(showCopyPasteSnippetSpy).toHaveBeenCalledWith({ + codeSnippet: `import { SentryExample } from './sentry-example.component' + +@Component({ + selector: 'app-root', + standalone: true, + imports: [RouterOutlet, SentryExample], + template: \` +
+

Your Application

+ +
+ \`, +}) +`, + instructions: + "Add the example component one of your pages or components (for example, in app.component.ts).", + }); + }); +}); + +describe("getSentryExampleComponentCode", () => { + it("includes the correct issue stream URL", () => { + const exampleComponentCode = getSentryExampleComponentCode({ + orgSlug: "myOrg", + projectId: "123456789", + url: "https://sentry.io", + }); + expect(exampleComponentCode).toContain( + "https://myorg.sentry.io/issues/?project=123456789", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts new file mode 100644 index 0000000000..82c6d0fa66 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { SemVer } from "semver"; +import { addNuxtOverrides } from "../../../../src/lib/wizard/nuxt/sdk-setup.js"; +import type { PackageManager } from "../../../../src/lib/wizard/utils/package-manager.js"; + +const { askShouldAddPackageOverrideMock } = vi.hoisted(() => ({ + askShouldAddPackageOverrideMock: vi.fn(), +})); + +vi.mock("@clack/prompts", () => ({ + log: { warn: vi.fn() }, +})); + +vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), + askShouldAddPackageOverride: askShouldAddPackageOverrideMock, +})); + +describe("addNuxtOverrides", () => { + const addOverride = vi.fn(); + const packageManager = { addOverride } as unknown as PackageManager; + + beforeEach(() => { + vi.clearAllMocks(); + askShouldAddPackageOverrideMock.mockResolvedValue(true); + }); + + it("adds an ofetch override for Nuxt < 3.14.0", async () => { + await addNuxtOverrides(packageManager, new SemVer("3.13.2")); + + expect(askShouldAddPackageOverrideMock).toHaveBeenCalledWith( + "ofetch", + "^1.4.0", + ); + expect(addOverride).toHaveBeenCalledWith("ofetch", "^1.4.0"); + }); + + it("does not add the override if the user declines", async () => { + askShouldAddPackageOverrideMock.mockResolvedValue(false); + + await addNuxtOverrides(packageManager, new SemVer("3.13.2")); + + expect(addOverride).not.toHaveBeenCalled(); + }); + + it.each(["3.14.0", "4.0.0"])( + "does not prompt for Nuxt %s", + async (version) => { + await addNuxtOverrides(packageManager, new SemVer(version)); + + expect(askShouldAddPackageOverrideMock).not.toHaveBeenCalled(); + expect(addOverride).not.toHaveBeenCalled(); + }, + ); + + it("does not prompt if the Nuxt version is unknown", async () => { + await addNuxtOverrides(packageManager, null); + + expect(askShouldAddPackageOverrideMock).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/templates.test.ts b/packages/cli/test/lib/wizard/nuxt/templates.test.ts new file mode 100644 index 0000000000..3d7a020aa8 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/templates.test.ts @@ -0,0 +1,483 @@ +import { describe, expect, it, vi } from "vitest"; +import { + getDefaultNuxtConfig, + getNuxtModuleFallbackTemplate, + getSentryConfigContents, +} from "../../../../src/lib/wizard/nuxt/templates.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("Nuxt code templates", () => { + describe("getDefaultNuxtConfig", () => { + it("returns a default nuxt config", () => { + expect(getDefaultNuxtConfig()).toMatchInlineSnapshot(` + "// https://nuxt.com/docs/api/configuration/nuxt-config + export default defineNuxtConfig({ + compatibilityDate: '2024-04-03', + devtools: { enabled: true } + }) + " +`); + }); + }); + + describe("getSentryConfigContents", () => { + describe("client config", () => { + it("generates Sentry config with all features enabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // 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, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // 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, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with session replay disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 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/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring and session replay disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with all features disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with reduced data collection", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "client", + { + performance: true, + replay: true, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain( + "// To disable sending user data and HTTP bodies, uncomment the lines below.", + ); + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + // If set up, you can use your runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn, + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // 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, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + + // If you don't want to use Session Replay, just remove the line below: + integrations: [Sentry.replayIntegration()], + + // 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"] }, + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + }); + + describe("server config", () => { + it("generates Sentry config with all features enabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: true, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 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/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with performance monitoring disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: false, + replay: true, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with all features disabled", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: false, + replay: false, + }, + false, + ); + + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + dataCollection: { + // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit: + // https://docs.sentry.io/platforms/javascript/guides/nuxt/configuration/options/#dataCollection + // userInfo: false, + // httpBodies: [], + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + + it("generates Sentry config with reduced data collection", () => { + const template = getSentryConfigContents( + "https://sentry.io/123", + "server", + { + performance: true, + replay: false, + }, + true, + ); + + expect(template).toContain("userInfo: false,"); + expect(template).toContain( + 'httpHeaders: { deny: ["forwarded", "-ip", "remote-", "via", "-user"] },', + ); + expect(template).not.toContain( + "// To disable sending user data and HTTP bodies, uncomment the lines below.", + ); + expect(template).toMatchInlineSnapshot(` + "import * as Sentry from "@sentry/nuxt"; + + Sentry.init({ + dsn: "https://sentry.io/123", + + // We recommend adjusting this value in production, or using tracesSampler + // for finer control + tracesSampleRate: 1.0, + + // 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"] }, + }, + + // Setting this option to true will print useful information to the console while you're setting up Sentry. + debug: false, + }); + " + `); + }); + }); + }); + + describe("getNuxtModuleFallbackTemplate", () => { + it("generates configuration options for the nuxt config", () => { + const template = getNuxtModuleFallbackTemplate({ + org: "my-org", + project: "my-project", + url: "https://sentry.io", + selfHosted: false, + }); + + expect(template).toMatchInlineSnapshot(` + " modules: ["@sentry/nuxt/module"], + sentry: { + org: "my-org", + project: "my-project", + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" }," + `); + }); + + it("generates configuration options for the nuxt config with self-hosted url", () => { + const template = getNuxtModuleFallbackTemplate({ + org: "my-org", + project: "my-project", + url: "https://sentry.example.com", + selfHosted: true, + }); + + expect(template).toMatchInlineSnapshot(` + " modules: ["@sentry/nuxt/module"], + sentry: { + org: "my-org", + project: "my-project", + sentryUrl: "https://sentry.example.com", + sourcemaps: { + // This will delete all .map files in the build output after uploading them to Sentry. Modify as needed. + // For more information, see: https://docs.sentry.io/platforms/javascript/guides/nuxt/sourcemaps/ + filesToDeleteAfterUpload: ['.*/**/*.map'] + }, + }, + sourcemap: { client: "hidden" }," + `); + }); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts new file mode 100644 index 0000000000..46498412d4 --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -0,0 +1,91 @@ +import { promises } from "node:fs"; + +import { + addSentryCommandToBuildCommand, + getSentryCliNpmScript, +} from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as packageManagerHelpers from "../../../../../src/lib/wizard/utils/package-manager.js"; +import { getPackageDotJson } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +import { vi, it, describe, expect, afterEach } from "vitest"; + +const writeFileSpy = vi + .spyOn(promises, "writeFile") + .mockImplementation(() => Promise.resolve()); + +vi.mock("@clack/prompts", () => { + return { + log: { + info: vi.fn(), + success: vi.fn(), + }, + confirm: vi.fn().mockResolvedValue(true), + isCancel: vi.fn().mockReturnValue(false), + }; +}); +vi.mock("../../../../../src/lib/wizard/utils/clack/index.js", async () => ({ + ...(await vi.importActual( + "../../../../../src/lib/wizard/utils/clack/index.js", + )), + getPackageDotJson: vi.fn().mockResolvedValue({ + scripts: { + build: "tsc", + }, + version: "1.0.0", + }), +})); + +describe("addSentryCommandToBuildCommand", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + it.each([ + [ + packageManagerHelpers.NPM, + packageManagerHelpers.PNPM, + packageManagerHelpers.YARN_V1, + packageManagerHelpers.YARN_V2, + packageManagerHelpers.BUN, + packageManagerHelpers.DENO, + ], + ])("adds the cli command to the script command (%s)", async (_, pacMan) => { + vi.spyOn(packageManagerHelpers, "_detectPackageManger").mockReturnValue( + pacMan, + ); + await addSentryCommandToBuildCommand(); + expect(writeFileSpy).toHaveBeenCalledWith( + expect.stringContaining("package.json"), + expect.stringContaining( + `tsc && ${pacMan.runScriptCommand} sentry:sourcemaps`, + ), + ); + }); + + it("does not add the cli command to the script command if it is already in there", async () => { + vi.mocked(getPackageDotJson).mockResolvedValue({ + scripts: { + build: "tsc && sentry:sourcemaps", + }, + version: "1.0.0", + }); + + await addSentryCommandToBuildCommand(); + + expect(writeFileSpy).not.toHaveBeenCalled(); + }); +}); + +describe("getSentryCliNpmScript", () => { + it("injects debug IDs and uploads with v4 sentry commands", () => { + expect( + getSentryCliNpmScript( + { orgSlug: "my-org", projectSlug: "my-project" }, + "./dist", + ), + ).toBe( + "sentry sourcemap inject ./dist && sentry sourcemap upload --org my-org --project my-project ./dist", + ); + }); +}); From 59a1bd941e4dcc55413c89d43b46f895481aacdc 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:34:10 +0000 Subject: [PATCH 05/26] feat(cli): read wizard source map upload target from .sentryclirc The `sentry:sourcemaps` script that the Angular flow adds no longer passes the hidden `--org`/`--project` compat flags. It is now `sentry sourcemap inject && sentry sourcemap upload `. The wizard writes the org and project to the `[defaults]` section of the project's `.sentryclirc`, which v4 already reads for org/project resolution. The edit keeps every other key, comment and section, including the `[auth]` token that the wizard still writes next to it, as sentry-wizard did. The file stays in `.gitignore`. For CI, `setupCI` takes an optional upload target. Angular passes it, so the CI step lists `SENTRY_ORG`, `SENTRY_PROJECT` and, for self-hosted Sentry, `SENTRY_URL` next to `SENTRY_AUTH_TOKEN`. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../cli-docs/src/fragments/commands/wizard.md | 7 +- .../src/lib/wizard/angular/angular-wizard.ts | 6 +- packages/cli/src/lib/wizard/sourcemaps/ci.ts | 63 ++++++-- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 138 +++++++++++++++--- .../cli/test/lib/wizard/sourcemaps/ci.test.ts | 34 +++++ .../sourcemaps/tools/sentry-cli.test.ts | 75 +++++++++- .../sourcemaps/tools/sentryclirc-file.test.ts | 109 ++++++++++++++ 7 files changed, 397 insertions(+), 35 deletions(-) create mode 100644 packages/cli/test/lib/wizard/sourcemaps/ci.test.ts create mode 100644 packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index a3d14efe88..c36fcb7ffc 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -31,5 +31,8 @@ changes nothing. Flows that uploaded source maps with `@sentry/cli`, such as Angular, now install the `sentry` package instead. The `sentry:sourcemaps` script they add to `package.json` runs `sentry sourcemap inject` and `sentry sourcemap upload` -on your build output. On self-hosted Sentry, set `SENTRY_URL` wherever that -script runs. +on your build output. The wizard writes your org and project to the +`[defaults]` section of the project's `.sentryclirc`, next to the auth token, +and adds the file to `.gitignore`. In CI, set `SENTRY_AUTH_TOKEN`, +`SENTRY_ORG` and `SENTRY_PROJECT` instead. On self-hosted Sentry, also set +`SENTRY_URL` wherever that script runs. diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts index f6b83566f7..545225640f 100644 --- a/packages/cli/src/lib/wizard/angular/angular-wizard.ts +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -263,7 +263,11 @@ Apologies for the inconvenience!`, true, ); - await setupCI("angular", authToken); + await setupCI("angular", authToken, { + org: selectedProject.organization.slug, + project: selectedProject.slug, + url: selfHosted ? sentryUrl : undefined, + }); }); const shouldCreateExampleComponent = await askShouldCreateExampleComponent(); diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index 1aad4564d2..04e5ff1ce6 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -24,23 +24,40 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ ]; /** - * Ask whether the user builds in CI and, if so, show the auth token to set - * there. + * Where `sentry sourcemap upload` sends source maps. In CI it comes from + * `SENTRY_ORG`, `SENTRY_PROJECT` and, for self-hosted Sentry, `SENTRY_URL`. + */ +export type SentryCliUploadTarget = { + org: string; + project: string; + /** The self-hosted Sentry URL. Unset for sentry.io. */ + url?: string | undefined; +}; + +/** + * Ask whether the user builds in CI and, if so, show the environment + * variables to set there. * * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file + * @param uploadTarget - For tools that upload with `sentry` commands, the + * org, project, and self-hosted URL that CI needs as well */ export async function setupCI( selectedTool: string, authToken: string, + uploadTarget?: SentryCliUploadTarget, ): Promise { - await traceStep("configure-ci", () => configureCI(selectedTool, authToken)); + await traceStep("configure-ci", () => + configureCI(selectedTool, authToken, uploadTarget), + ); } -/** Ask about CI and show the auth token to set there. */ +/** Ask about CI and show the environment variables to set there. */ async function configureCI( selectedTool: string, authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, ): Promise { const isUsingCI = await abortIfCancelled( clack.select({ @@ -82,19 +99,47 @@ async function configureCI( await traceStep("ci-npm-script-setup", setupNpmScriptInCI); } - await traceStep("ci-auth-token-setup", () => setupAuthTokenInCI(authToken)); + await traceStep("ci-auth-token-setup", () => + setupAuthTokenInCI( + authToken, + isCliBasedFlowTool ? uploadTarget : undefined, + ), + ); +} + +/** The `NAME=value` lines to add to the CI environment. */ +export function getCIEnvVars( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): string[] { + const lines = [`SENTRY_AUTH_TOKEN=${authToken}`]; + if (uploadTarget) { + lines.push( + `SENTRY_ORG=${uploadTarget.org}`, + `SENTRY_PROJECT=${uploadTarget.project}`, + ); + if (uploadTarget.url) { + lines.push(`SENTRY_URL=${uploadTarget.url}`); + } + } + return lines; } -/** Show the auth token to add to the CI environment. */ -async function setupAuthTokenInCI(authToken: string): Promise { +/** Show the auth token, and the upload target if any, to add to CI. */ +async function setupAuthTokenInCI( + authToken: string, + uploadTarget: SentryCliUploadTarget | undefined, +): Promise { clack.log.step( - "Add the Sentry authentication token as an environment variable to your CI setup:", + uploadTarget + ? "Add these environment variables to your CI setup:" + : "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} +${getCIEnvVars(authToken, uploadTarget).join("\n")} `), ); diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index b2d0b889f4..773abb7fc5 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -5,12 +5,16 @@ * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the * build output, optionally appends it to the production build script, and - * writes the auth token to `.sentryclirc`. Ported from sentry-wizard's - * `src/sourcemaps/tools/sentry-cli.ts`, which installed `@sentry/cli` and - * ran `sentry-cli sourcemaps …`. + * writes the org, project, and auth token to `.sentryclirc`. v4 reads that + * file: `[defaults]` feeds org/project resolution and `[auth] token` becomes + * `SENTRY_AUTH_TOKEN`. + * + * Ported from sentry-wizard's `src/sourcemaps/tools/sentry-cli.ts`, which + * installed `@sentry/cli`, ran `sentry-cli sourcemaps …`, and also wrote the + * token to `.sentryclirc`. */ -import { promises } from "node:fs"; +import { existsSync, promises, readFileSync } from "node:fs"; import path from "node:path"; import chalk from "chalk"; import { Sentry, traceStep } from "../../telemetry.js"; @@ -22,8 +26,10 @@ import { getPackageDotJson, getPackageManager, installPackage, + SENTRY_CLI_RC_FILE, } from "../../utils/clack/index.js"; import { clack } from "../../utils/clack/prompts.js"; +import { debug } from "../../utils/debug.js"; import { hasPackageInstalled } from "../../utils/package-json.js"; import { NPM } from "../../utils/package-manager.js"; import type { SourceMapUploadToolConfigurationOptions } from "./types.js"; @@ -110,7 +116,7 @@ export async function configureSentryCLI( await configureSourcemapGenerationFlow(); } - await createAndAddNpmScript(options, relativePosixArtifactPath); + await createAndAddNpmScript(relativePosixArtifactPath); if (await askShouldAddToBuildCommand()) { await traceStep("sentry-cli-add-to-build-cmd", () => @@ -124,6 +130,7 @@ export async function configureSentryCLI( ); } + await addOrgAndProjectToSentryCliRc(options); await addSentryCliConfig({ authToken: options.authToken }); if (options.selfHosted) { @@ -176,31 +183,126 @@ export async function setupNpmScriptInCI(): Promise { /** * The `sentry:sourcemaps` script: inject debug IDs into the build output, - * then upload it. v4 takes the org and project as flags on any command and - * the self-hosted URL from `SENTRY_URL` (or `.sentryclirc`), so the script - * has no `--url`. + * then upload it. `sentry sourcemap upload` reads the org and project from + * `.sentryclirc` locally and from `SENTRY_ORG` / `SENTRY_PROJECT` in CI, and + * the self-hosted URL from `SENTRY_URL`. */ export function getSentryCliNpmScript( - options: Pick< - SourceMapUploadToolConfigurationOptions, - "orgSlug" | "projectSlug" - >, relativePosixArtifactPath: string, ): string { // The script runs the `sentry` binary of the package installed above, so // it names `sentry` itself, not the program running the wizard. // oxlint-disable-next-line sentry-cli/no-hardcoded-sentry-command -- a package.json script, not a hint. - return `sentry sourcemap inject ${relativePosixArtifactPath} && sentry sourcemap upload --org ${options.orgSlug} --project ${options.projectSlug} ${relativePosixArtifactPath}`; + return `sentry sourcemap inject ${relativePosixArtifactPath} && sentry sourcemap upload ${relativePosixArtifactPath}`; } -async function createAndAddNpmScript( +/** An INI section header line, such as `[defaults]`. */ +const INI_SECTION_RE = /^\s*\[([^\]]*)\]\s*$/; + +/** The key of an INI `key = value` line. */ +const INI_KEY_RE = /^\s*([^=;#\s][^=]*?)\s*=/; + +/** + * Set `values` in the `[defaults]` section of `.sentryclirc` contents and + * keep every other line as it is. + * + * Existing keys are updated in every `[defaults]` section, since the last + * one wins when the file is read. Missing keys go into the first + * `[defaults]` section, which is appended when there is none. + * + * @param contents - The current file contents, empty for a new file + * @param values - Lowercase keys and their values, such as `{ org, project }` + */ +export function setSentryCliRcDefaults( + contents: string, + values: Record, +): string { + const lines = contents === "" ? [] : contents.split("\n"); + const missing = new Map(Object.entries(values)); + let firstDefaultsHeader = -1; + let inDefaults = false; + + lines.forEach((line, index) => { + const section = INI_SECTION_RE.exec(line); + if (section) { + inDefaults = section[1]?.trim().toLowerCase() === "defaults"; + if (inDefaults && firstDefaultsHeader === -1) { + firstDefaultsHeader = index; + } + return; + } + const key = inDefaults + ? INI_KEY_RE.exec(line)?.[1]?.toLowerCase() + : undefined; + const value = key === undefined ? undefined : values[key]; + if (key !== undefined && value !== undefined) { + lines[index] = `${key}=${value}${line.endsWith("\r") ? "\r" : ""}`; + missing.delete(key); + } + }); + + const newLines = [...missing].map(([key, value]) => `${key}=${value}`); + if (newLines.length === 0) { + return lines.join("\n"); + } + if (firstDefaultsHeader !== -1) { + lines.splice(firstDefaultsHeader + 1, 0, ...newLines); + return lines.join("\n"); + } + + const prefix = lines.join("\n"); + let separator = "\n\n"; + if (prefix === "") { + separator = ""; + } else if (prefix.endsWith("\n")) { + separator = "\n"; + } + return `${prefix}${separator}[defaults]\n${newLines.join("\n")}\n`; +} + +/** + * Write the org and project to the project's `.sentryclirc`, so that + * `sentry sourcemap upload` finds them when the script runs locally. + */ +async function addOrgAndProjectToSentryCliRc( options: SourceMapUploadToolConfigurationOptions, - relativePosixArtifactPath: string, ): Promise { - const sentryCliNpmScript = getSentryCliNpmScript( - options, - relativePosixArtifactPath, + const configPath = path.join(process.cwd(), SENTRY_CLI_RC_FILE); + const contents = existsSync(configPath) + ? readFileSync(configPath, "utf8") + : ""; + + try { + await promises.writeFile( + configPath, + setSentryCliRcDefaults(contents, { + org: options.orgSlug, + project: options.projectSlug, + }), + ); + } catch (error) { + // Not fatal, like the auth token write: CI sets SENTRY_ORG and + // SENTRY_PROJECT anyway, and the warning says what to do locally. + debug(error); + clack.log.warning( + `Failed to add the org and project to ${chalk.cyan( + SENTRY_CLI_RC_FILE, + )}. Set ${chalk.cyan("SENTRY_ORG")} and ${chalk.cyan( + "SENTRY_PROJECT", + )} wherever ${chalk.cyan(SENTRY_NPM_SCRIPT_NAME)} runs.`, + ); + return; + } + + clack.log.success( + `Added the org and project to ${chalk.cyan(SENTRY_CLI_RC_FILE)}.`, ); +} + +async function createAndAddNpmScript( + relativePosixArtifactPath: string, +): Promise { + const sentryCliNpmScript = getSentryCliNpmScript(relativePosixArtifactPath); const packageDotJson = await getPackageDotJson(); diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts new file mode 100644 index 0000000000..2b80dfd59b --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; + +import { getCIEnvVars } from "../../../../src/lib/wizard/sourcemaps/ci.js"; + +describe("getCIEnvVars", () => { + it("lists only the auth token without an upload target", () => { + expect(getCIEnvVars("tok", undefined)).toEqual(["SENTRY_AUTH_TOKEN=tok"]); + }); + + it("adds the org and project for sentry.io", () => { + expect( + getCIEnvVars("tok", { org: "my-org", project: "my-project" }), + ).toEqual([ + "SENTRY_AUTH_TOKEN=tok", + "SENTRY_ORG=my-org", + "SENTRY_PROJECT=my-project", + ]); + }); + + it("adds SENTRY_URL for self-hosted Sentry", () => { + expect( + getCIEnvVars("tok", { + org: "my-org", + project: "my-project", + url: "https://sentry.example.com/", + }), + ).toEqual([ + "SENTRY_AUTH_TOKEN=tok", + "SENTRY_ORG=my-org", + "SENTRY_PROJECT=my-project", + "SENTRY_URL=https://sentry.example.com/", + ]); + }); +}); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts index 46498412d4..22bea7aa46 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentry-cli.test.ts @@ -3,6 +3,7 @@ import { promises } from "node:fs"; import { addSentryCommandToBuildCommand, getSentryCliNpmScript, + setSentryCliRcDefaults, } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking @@ -78,14 +79,78 @@ describe("addSentryCommandToBuildCommand", () => { }); describe("getSentryCliNpmScript", () => { - it("injects debug IDs and uploads with v4 sentry commands", () => { + it("injects debug IDs and uploads with v4 sentry commands, without org or project flags", () => { + expect(getSentryCliNpmScript("./dist")).toBe( + "sentry sourcemap inject ./dist && sentry sourcemap upload ./dist", + ); + }); +}); + +describe("setSentryCliRcDefaults", () => { + const values = { org: "my-org", project: "my-project" }; + + it("creates a [defaults] section in an empty file", () => { + expect(setSentryCliRcDefaults("", values)).toBe( + "[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("appends [defaults] after other sections and keeps them", () => { + expect(setSentryCliRcDefaults("[auth]\ntoken=abc\n", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + expect(setSentryCliRcDefaults("[auth]\ntoken=abc", values)).toBe( + "[auth]\ntoken=abc\n\n[defaults]\norg=my-org\nproject=my-project\n", + ); + }); + + it("updates existing keys and keeps other keys, comments, and sections", () => { + const contents = [ + "; managed by hand", + "[defaults]", + "url = https://sentry.example.com/", + "org = old-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"); + + expect(setSentryCliRcDefaults(contents, values)).toBe( + [ + "; managed by hand", + "[defaults]", + "project=my-project", + "url = https://sentry.example.com/", + "org=my-org", + "", + "[auth]", + "token=abc", + "", + ].join("\n"), + ); + }); + + it("does not touch org or project keys outside [defaults]", () => { expect( - getSentryCliNpmScript( - { orgSlug: "my-org", projectSlug: "my-project" }, - "./dist", + setSentryCliRcDefaults("[other]\norg=keep\n[DEFAULTS]\n", values), + ).toBe("[other]\norg=keep\n[DEFAULTS]\norg=my-org\nproject=my-project\n"); + }); + + it("updates keys in every [defaults] section", () => { + expect( + setSentryCliRcDefaults( + "[defaults]\norg=a\n[auth]\ntoken=t\n[defaults]\nproject=b\n", + values, ), ).toBe( - "sentry sourcemap inject ./dist && sentry sourcemap upload --org my-org --project my-project ./dist", + "[defaults]\norg=my-org\n[auth]\ntoken=t\n[defaults]\nproject=my-project\n", ); }); + + it("keeps CRLF line endings on updated lines", () => { + expect( + setSentryCliRcDefaults("[defaults]\r\norg=a\r\nproject=b\r\n", values), + ).toBe("[defaults]\r\norg=my-org\r\nproject=my-project\r\n"); + }); }); diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts new file mode 100644 index 0000000000..9411b2ed3e --- /dev/null +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts @@ -0,0 +1,109 @@ +/** + * `.sentryclirc` written by the wizard, read back the way v4 reads it. + * + * Writes the `[defaults]` org/project and the `[auth]` token into a real + * temp dir in both orders and checks that `loadSentryCliRc` resolves all + * three, and that `.sentryclirc` ends up in `.gitignore`. + */ + +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + clearSentryCliRcCache, + loadSentryCliRc, +} from "../../../../../src/lib/sentryclirc.js"; +import { setSentryCliRcDefaults } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { addSentryCliConfig } from "../../../../../src/lib/wizard/utils/clack/index.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + }, +})); + +let projectDir: string; +let configDir: string; +let originalCwd: string; +let originalConfigDir: string | undefined; + +beforeEach(() => { + originalCwd = process.cwd(); + originalConfigDir = process.env["SENTRY_CONFIG_DIR"]; + projectDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-")); + // An empty config dir so a global ~/.sentryclirc can't leak in. + configDir = mkdtempSync(path.join(tmpdir(), "wizard-rc-config-")); + process.env["SENTRY_CONFIG_DIR"] = configDir; + writeFileSync(path.join(projectDir, ".gitignore"), "node_modules\n"); + process.chdir(projectDir); + clearSentryCliRcCache(); +}); + +afterEach(() => { + process.chdir(originalCwd); + if (originalConfigDir === undefined) { + delete process.env["SENTRY_CONFIG_DIR"]; + } else { + process.env["SENTRY_CONFIG_DIR"] = originalConfigDir; + } + clearSentryCliRcCache(); + rmSync(projectDir, { recursive: true, force: true }); + rmSync(configDir, { recursive: true, force: true }); +}); + +const rcPath = (): string => path.join(projectDir, ".sentryclirc"); + +function writeDefaults(): void { + const contents = existsSync(rcPath()) ? readFileSync(rcPath(), "utf8") : ""; + writeFileSync( + rcPath(), + setSentryCliRcDefaults(contents, { org: "my-org", project: "my-project" }), + ); +} + +async function expectV4ReadsAll(): Promise { + const config = await loadSentryCliRc(projectDir); + expect(config.org).toBe("my-org"); + expect(config.project).toBe("my-project"); + expect(config.token).toBe("sntrys_tok"); + expect( + readFileSync(path.join(projectDir, ".gitignore"), "utf8").split("\n"), + ).toContain(".sentryclirc"); +} + +describe(".sentryclirc written by the wizard", () => { + it("keeps [auth] when [defaults] is written first", async () => { + writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + }); + + it("keeps [auth] when [defaults] is written after the token", async () => { + await addSentryCliConfig({ authToken: "sntrys_tok" }); + writeDefaults(); + await expectV4ReadsAll(); + }); + + it("keeps the user's other keys", async () => { + writeFileSync(rcPath(), "[defaults]\nurl=https://sentry.example.com/\n"); + writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + }); +}); From 58d673b15de50474196d6983ddb0500c73c9b295 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:19:05 +0000 Subject: [PATCH 06/26] docs(cli): say why the wizard keeps the self-hosted URL out of .sentryclirc v4 refuses a non-SaaS `[defaults] url` from `.sentryclirc` unless the token's host or a stored login vouches for it, and the `[auth] token` in the same file doesn't count. Writing the URL there would make the generated `sentry:sourcemaps` script fail on self-hosted Sentry, so the wizard tells users to set `SENTRY_URL` instead. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 773abb7fc5..91dfb9e012 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -263,6 +263,11 @@ export function setSentryCliRcDefaults( /** * Write the org and project to the project's `.sentryclirc`, so that * `sentry sourcemap upload` finds them when the script runs locally. + * + * The self-hosted URL stays out of the file. v4 refuses a non-SaaS + * `[defaults] url` unless the token's host or a stored login vouches for it, + * and the `[auth] token` from the same file doesn't (see + * `assertRcUrlTrusted`), so users set `SENTRY_URL` instead. */ async function addOrgAndProjectToSentryCliRc( options: SourceMapUploadToolConfigurationOptions, 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 07/26] 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 09983d30fb39dc5a4c33bb34e514d0d4583648a7 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:15:33 +0000 Subject: [PATCH 08/26] fix(cli): address Warden findings in the Nuxt and Angular wizards - Angular: pass --force-install through to installPackage, like the Next.js and Nuxt flows. - Nuxt: name the generated SentryErrorButton component in the closing message. - Nuxt: still create the example API route when the example page already exists, and keep an existing API route. - Nuxt: drop ignoreResponseError from the example page so the expected 500 from the API route shows the success message. Adds regression tests for each. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/lib/wizard/angular/angular-wizard.ts | 1 + .../cli/src/lib/wizard/nuxt/nuxt-wizard.ts | 4 +- .../cli/src/lib/wizard/nuxt/sdk-example.ts | 22 +++--- packages/cli/src/lib/wizard/nuxt/templates.ts | 4 +- .../angular/angular-wizard-install.test.ts | 65 +++++++++++++++++ .../test/lib/wizard/nuxt/nuxt-wizard.test.ts | 21 ++++++ .../test/lib/wizard/nuxt/sdk-example.test.ts | 71 +++++++++++++++++++ .../test/lib/wizard/nuxt/templates.test.ts | 13 ++++ 8 files changed, 189 insertions(+), 12 deletions(-) create mode 100644 packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts create mode 100644 packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts create mode 100644 packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts index 545225640f..0db25f4d97 100644 --- a/packages/cli/src/lib/wizard/angular/angular-wizard.ts +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -196,6 +196,7 @@ Apologies for the inconvenience!`, packageName: "@sentry/angular@^11", packageNameDisplayLabel: "@sentry/angular", alreadyInstalled: sdkAlreadyInstalled, + forceInstall: options.forceInstall, }); // The install may have been skipped (user declined the update prompt), so diff --git a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts index 9e466f2f01..f43c10d6ed 100644 --- a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts +++ b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts @@ -212,7 +212,7 @@ async function runNuxtWizardWithTelemetry( ); } -function buildOutroMessage( +export function buildOutroMessage( shouldCreateExamplePage: boolean, shouldCreateExampleButton: boolean, ): string { @@ -225,7 +225,7 @@ function buildOutroMessage( } if (shouldCreateExampleButton) { msg += `\n\nYou can validate your setup by adding the ${chalk.cyan( - "`SentryExampleButton`", + "`SentryErrorButton`", )} component to a page and triggering it.`; } diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-example.ts b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts index 2dce84431a..5c84bc56e7 100644 --- a/packages/cli/src/lib/wizard/nuxt/sdk-example.ts +++ b/packages/cli/src/lib/wizard/nuxt/sdk-example.ts @@ -77,15 +77,14 @@ export async function createExamplePage( clack.log.warn( `It seems like a sentry example page already exists. Skipping creation of example page.`, ); - return; - } - - await promises.writeFile( - path.resolve(examplePage), - getSentryExamplePageTemplate(options), - ); + } else { + await promises.writeFile( + path.resolve(examplePage), + getSentryExamplePageTemplate(options), + ); - clack.log.success(`Created ${chalk.cyan(examplePage)}.`); + clack.log.success(`Created ${chalk.cyan(examplePage)}.`); + } const api = path.join("server", "api"); @@ -98,6 +97,13 @@ export async function createExamplePage( isUsingTypeScript() ? "sentry-example-api.ts" : "sentry-example-api.js", ); + if (existsSync(path.resolve(exampleApi))) { + clack.log.warn( + `It seems like a sentry example API route already exists. Skipping creation of example API route.`, + ); + return; + } + await promises.writeFile( path.resolve(exampleApi), getSentryExampleApiTemplate(), diff --git a/packages/cli/src/lib/wizard/nuxt/templates.ts b/packages/cli/src/lib/wizard/nuxt/templates.ts index 8b63a9ae2e..e85c3f61f7 100644 --- a/packages/cli/src/lib/wizard/nuxt/templates.ts +++ b/packages/cli/src/lib/wizard/nuxt/templates.ts @@ -220,9 +220,9 @@ Feel free to delete this file. op: 'test' }, async () => { - const res = await $fetch('/api/sentry-example-api', { + // The API route always throws, so $fetch rejects with its 500. + const res = await $fetch('/api/sentry-example-api', { method: 'GET', - ignoreResponseError: true }).catch(() => null); if (!res) { hasSentError.value = true; diff --git a/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts new file mode 100644 index 0000000000..da005d8728 --- /dev/null +++ b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it, vi } from "vitest"; + +import { runAngularWizard } from "../../../../src/lib/wizard/angular/angular-wizard.js"; +import { installPackage } from "../../../../src/lib/wizard/utils/clack/index.js"; + +/** Thrown by the mocked install to stop the flow right after it. */ +const { STOP } = vi.hoisted(() => ({ STOP: new Error("stop after install") })); + +vi.mock("../../../../src/lib/wizard/telemetry.js", async (importOriginal) => ({ + ...(await importOriginal()), + withTelemetry: (_options: unknown, fn: () => Promise) => fn(), +})); + +vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ + warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), +})); + +vi.mock( + "../../../../src/lib/wizard/utils/clack/index.js", + async (importOriginal) => ({ + ...(await importOriginal()), + printWelcome: vi.fn(), + confirmContinueIfNoOrDirtyGitRepo: vi.fn().mockResolvedValue(undefined), + ensurePackageIsInstalled: vi.fn().mockResolvedValue(undefined), + printSdkV11MigrationGuideIfOutdated: vi.fn(), + getPackageDotJson: vi.fn().mockResolvedValue({ + dependencies: { "@angular/core": "^19.0.0" }, + }), + getOrAskForProjectData: vi.fn().mockResolvedValue({ + spotlight: false, + selfHosted: false, + sentryUrl: "https://sentry.io/", + authToken: "sntrys_token", + selectedProject: { + id: "2", + slug: "my-project", + organization: { slug: "my-org" }, + keys: [{ dsn: { public: "https://key@o1.ingest.sentry.io/2" } }], + }, + }), + installPackage: vi.fn().mockRejectedValue(STOP), + }), +); + +describe("runAngularWizard", () => { + it.each([true, false])( + "passes forceInstall=%s to installPackage", + async (forceInstall) => { + await expect( + runAngularWizard({ + telemetryEnabled: false, + ignoreGitChanges: true, + forceInstall, + }), + ).rejects.toBe(STOP); + + expect(installPackage).toHaveBeenLastCalledWith( + expect.objectContaining({ + packageName: "@sentry/angular@^11", + forceInstall, + }), + ); + }, + ); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts new file mode 100644 index 0000000000..0d24318ecc --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/nuxt-wizard.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from "vitest"; + +import { buildOutroMessage } from "../../../../src/lib/wizard/nuxt/nuxt-wizard.js"; + +vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ + offerProjectScopedMcpConfig: vi.fn().mockResolvedValue(undefined), +})); + +describe("buildOutroMessage", () => { + it("names the SentryErrorButton component the wizard creates", () => { + const message = buildOutroMessage(false, true); + expect(message).toContain("`SentryErrorButton`"); + expect(message).not.toContain("SentryExampleButton"); + }); + + it("points to the example page when one was created", () => { + const message = buildOutroMessage(true, false); + expect(message).toContain('"/sentry-example-page"'); + expect(message).not.toContain("SentryErrorButton"); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts b/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts new file mode 100644 index 0000000000..1bb14c9948 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/sdk-example.test.ts @@ -0,0 +1,71 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createExamplePage } from "../../../../src/lib/wizard/nuxt/sdk-example.js"; + +vi.mock("@clack/prompts", () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +const options = { + org: "my-org", + project: "my-project", + projectId: "1", + url: "https://sentry.io/", +}; + +let projectDir: string; +let originalCwd: string; + +beforeEach(() => { + originalCwd = process.cwd(); + projectDir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-example-")); + process.chdir(projectDir); +}); + +afterEach(() => { + process.chdir(originalCwd); + rmSync(projectDir, { recursive: true, force: true }); +}); + +describe("createExamplePage", () => { + it("creates the API route when the example page already exists", async () => { + mkdirSync("pages"); + writeFileSync("pages/sentry-example-page.vue", ""); + + await createExamplePage(false, options); + + expect(readFileSync("pages/sentry-example-page.vue", "utf8")).toBe( + "", + ); + expect(existsSync("server/api/sentry-example-api.js")).toBe(true); + }); + + it("keeps an existing API route", async () => { + mkdirSync("server/api", { recursive: true }); + writeFileSync("tsconfig.json", "{}"); + writeFileSync("server/api/sentry-example-api.ts", "// user's route"); + + await createExamplePage(false, options); + + expect(existsSync("pages/sentry-example-page.vue")).toBe(true); + expect(readFileSync("server/api/sentry-example-api.ts", "utf8")).toBe( + "// user's route", + ); + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/templates.test.ts b/packages/cli/test/lib/wizard/nuxt/templates.test.ts index 3d7a020aa8..fb9a73dcb0 100644 --- a/packages/cli/test/lib/wizard/nuxt/templates.test.ts +++ b/packages/cli/test/lib/wizard/nuxt/templates.test.ts @@ -3,6 +3,7 @@ import { getDefaultNuxtConfig, getNuxtModuleFallbackTemplate, getSentryConfigContents, + getSentryExamplePageTemplate, } from "../../../../src/lib/wizard/nuxt/templates.js"; vi.mock("../../../../src/lib/wizard/utils/clack/mcp-config.js", () => ({ @@ -480,4 +481,16 @@ describe("Nuxt code templates", () => { `); }); }); + + describe("getSentryExamplePageTemplate", () => { + it("lets the API route's 500 reject so the page shows its success state", () => { + const template = getSentryExamplePageTemplate({ + url: "https://sentry.io/", + org: "my-org", + projectId: "1", + }); + expect(template).toContain("$fetch('/api/sentry-example-api'"); + expect(template).not.toContain("ignoreResponseError"); + }); + }); }); From e03e53f72c731be8ac510f980d315c5b5d4c70b6 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:20:00 +0000 Subject: [PATCH 09/26] feat(cli): list only the auth token for sentry.io CI, write self-hosted url On sentry.io, v4 `sentry sourcemap upload` resolves the org and project from the DSN, so the CI step now lists only SENTRY_AUTH_TOKEN. Self-hosted CI still needs SENTRY_ORG, SENTRY_PROJECT and SENTRY_URL. For self-hosted Sentry the wizard also writes `url` to the `.sentryclirc` [defaults] section, next to org/project and the [auth] token. v4 reads it once the CLI trusts an [auth] token from the same file for that URL; until that same-file trust fix lands, users set SENTRY_URL. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/wizard/sourcemaps/ci.ts | 20 +++--- .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 27 ++++---- .../cli/test/lib/wizard/sourcemaps/ci.test.ts | 10 +-- .../sourcemaps/tools/sentryclirc-file.test.ts | 62 +++++++++++++------ 4 files changed, 70 insertions(+), 49 deletions(-) diff --git a/packages/cli/src/lib/wizard/sourcemaps/ci.ts b/packages/cli/src/lib/wizard/sourcemaps/ci.ts index 04e5ff1ce6..cf666f2598 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/ci.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/ci.ts @@ -24,8 +24,9 @@ const CLI_BASED_FLOW_TOOLS: readonly string[] = [ ]; /** - * Where `sentry sourcemap upload` sends source maps. In CI it comes from - * `SENTRY_ORG`, `SENTRY_PROJECT` and, for self-hosted Sentry, `SENTRY_URL`. + * Where `sentry sourcemap upload` sends source maps. On sentry.io v4 + * resolves the org and project from the DSN, so CI needs only the token. + * Self-hosted CI also needs `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL`. */ export type SentryCliUploadTarget = { org: string; @@ -41,7 +42,7 @@ export type SentryCliUploadTarget = { * @param selectedTool - The build tool the wizard configured, such as `nextjs` * @param authToken - The token written to the local config file * @param uploadTarget - For tools that upload with `sentry` commands, the - * org, project, and self-hosted URL that CI needs as well + * org, project, and self-hosted URL to upload to */ export async function setupCI( selectedTool: string, @@ -107,20 +108,21 @@ async function configureCI( ); } -/** The `NAME=value` lines to add to the CI environment. */ +/** + * The `NAME=value` lines to add to the CI environment: the auth token, plus + * the org, project, and URL for a self-hosted upload target. + */ export function getCIEnvVars( authToken: string, uploadTarget: SentryCliUploadTarget | undefined, ): string[] { const lines = [`SENTRY_AUTH_TOKEN=${authToken}`]; - if (uploadTarget) { + if (uploadTarget?.url) { lines.push( `SENTRY_ORG=${uploadTarget.org}`, `SENTRY_PROJECT=${uploadTarget.project}`, + `SENTRY_URL=${uploadTarget.url}`, ); - if (uploadTarget.url) { - lines.push(`SENTRY_URL=${uploadTarget.url}`); - } } return lines; } @@ -131,7 +133,7 @@ async function setupAuthTokenInCI( uploadTarget: SentryCliUploadTarget | undefined, ): Promise { clack.log.step( - uploadTarget + uploadTarget?.url ? "Add these environment variables to your CI setup:" : "Add the Sentry authentication token as an environment variable to your CI setup:", ); diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index 91dfb9e012..4edaba2e42 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -5,9 +5,9 @@ * Installs the `sentry` CLI package, adds a `sentry:sourcemaps` npm script * that runs `sentry sourcemap inject` and `sentry sourcemap upload` on the * build output, optionally appends it to the production build script, and - * writes the org, project, and auth token to `.sentryclirc`. v4 reads that - * file: `[defaults]` feeds org/project resolution and `[auth] token` becomes - * `SENTRY_AUTH_TOKEN`. + * writes the org, project, self-hosted URL, and auth token to `.sentryclirc`. + * v4 reads that file: `[defaults]` feeds org/project/url resolution and + * `[auth] token` becomes `SENTRY_AUTH_TOKEN`. * * Ported from sentry-wizard's `src/sourcemaps/tools/sentry-cli.ts`, which * installed `@sentry/cli`, ran `sentry-cli sourcemaps …`, and also wrote the @@ -130,7 +130,7 @@ export async function configureSentryCLI( ); } - await addOrgAndProjectToSentryCliRc(options); + await addUploadTargetToSentryCliRc(options); await addSentryCliConfig({ authToken: options.authToken }); if (options.selfHosted) { @@ -184,8 +184,8 @@ export async function setupNpmScriptInCI(): Promise { /** * The `sentry:sourcemaps` script: inject debug IDs into the build output, * then upload it. `sentry sourcemap upload` reads the org and project from - * `.sentryclirc` locally and from `SENTRY_ORG` / `SENTRY_PROJECT` in CI, and - * the self-hosted URL from `SENTRY_URL`. + * `.sentryclirc` locally. In CI it resolves them from the DSN on sentry.io, + * and from `SENTRY_ORG`, `SENTRY_PROJECT` and `SENTRY_URL` for self-hosted. */ export function getSentryCliNpmScript( relativePosixArtifactPath: string, @@ -261,15 +261,15 @@ export function setSentryCliRcDefaults( } /** - * Write the org and project to the project's `.sentryclirc`, so that - * `sentry sourcemap upload` finds them when the script runs locally. + * Write the org, project and, for self-hosted Sentry, the URL to the + * project's `.sentryclirc`, so that `sentry sourcemap upload` finds them + * when the script runs locally. * - * The self-hosted URL stays out of the file. v4 refuses a non-SaaS - * `[defaults] url` unless the token's host or a stored login vouches for it, - * and the `[auth] token` from the same file doesn't (see - * `assertRcUrlTrusted`), so users set `SENTRY_URL` instead. + * v4 reads a self-hosted `[defaults] url` only once the CLI trusts an + * `[auth] token` from the same file for it. Until that same-file trust fix + * lands, `assertRcUrlTrusted` refuses it and users set `SENTRY_URL`. */ -async function addOrgAndProjectToSentryCliRc( +export async function addUploadTargetToSentryCliRc( options: SourceMapUploadToolConfigurationOptions, ): Promise { const configPath = path.join(process.cwd(), SENTRY_CLI_RC_FILE); @@ -283,6 +283,7 @@ async function addOrgAndProjectToSentryCliRc( setSentryCliRcDefaults(contents, { org: options.orgSlug, project: options.projectSlug, + ...(options.selfHosted ? { url: options.url } : {}), }), ); } catch (error) { diff --git a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts index 2b80dfd59b..e0f1fc16b2 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/ci.test.ts @@ -7,17 +7,13 @@ describe("getCIEnvVars", () => { expect(getCIEnvVars("tok", undefined)).toEqual(["SENTRY_AUTH_TOKEN=tok"]); }); - it("adds the org and project for sentry.io", () => { + it("lists only the auth token for sentry.io, which resolves the DSN", () => { expect( getCIEnvVars("tok", { org: "my-org", project: "my-project" }), - ).toEqual([ - "SENTRY_AUTH_TOKEN=tok", - "SENTRY_ORG=my-org", - "SENTRY_PROJECT=my-project", - ]); + ).toEqual(["SENTRY_AUTH_TOKEN=tok"]); }); - it("adds SENTRY_URL for self-hosted Sentry", () => { + it("adds the org, project, and URL for self-hosted Sentry", () => { expect( getCIEnvVars("tok", { org: "my-org", diff --git a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts index 9411b2ed3e..a672f149c9 100644 --- a/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts +++ b/packages/cli/test/lib/wizard/sourcemaps/tools/sentryclirc-file.test.ts @@ -1,18 +1,13 @@ /** * `.sentryclirc` written by the wizard, read back the way v4 reads it. * - * Writes the `[defaults]` org/project and the `[auth]` token into a real - * temp dir in both orders and checks that `loadSentryCliRc` resolves all - * three, and that `.sentryclirc` ends up in `.gitignore`. + * Writes the `[defaults]` org/project (and the self-hosted URL) and the + * `[auth]` token into a real temp dir in both orders and checks that + * `loadSentryCliRc` resolves them, and that `.sentryclirc` ends up in + * `.gitignore`. */ -import { - existsSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -22,7 +17,7 @@ import { clearSentryCliRcCache, loadSentryCliRc, } from "../../../../../src/lib/sentryclirc.js"; -import { setSentryCliRcDefaults } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; +import { addUploadTargetToSentryCliRc } from "../../../../../src/lib/wizard/sourcemaps/tools/sentry-cli.js"; import { addSentryCliConfig } from "../../../../../src/lib/wizard/utils/clack/index.js"; vi.mock("@clack/prompts", () => ({ @@ -66,12 +61,14 @@ afterEach(() => { const rcPath = (): string => path.join(projectDir, ".sentryclirc"); -function writeDefaults(): void { - const contents = existsSync(rcPath()) ? readFileSync(rcPath(), "utf8") : ""; - writeFileSync( - rcPath(), - setSentryCliRcDefaults(contents, { org: "my-org", project: "my-project" }), - ); +function writeDefaults(selfHostedUrl?: string): Promise { + return addUploadTargetToSentryCliRc({ + orgSlug: "my-org", + projectSlug: "my-project", + selfHosted: selfHostedUrl !== undefined, + url: selfHostedUrl ?? "https://sentry.io/", + authToken: "sntrys_tok", + }); } async function expectV4ReadsAll(): Promise { @@ -86,20 +83,45 @@ async function expectV4ReadsAll(): Promise { describe(".sentryclirc written by the wizard", () => { it("keeps [auth] when [defaults] is written first", async () => { - writeDefaults(); + await writeDefaults(); await addSentryCliConfig({ authToken: "sntrys_tok" }); await expectV4ReadsAll(); }); it("keeps [auth] when [defaults] is written after the token", async () => { await addSentryCliConfig({ authToken: "sntrys_tok" }); - writeDefaults(); + await writeDefaults(); + await expectV4ReadsAll(); + }); + + it("writes no URL for sentry.io", async () => { + await writeDefaults(); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect(readFileSync(rcPath(), "utf8")).not.toMatch(/^url=/m); + }); + + it("writes the self-hosted URL next to [auth], in either order", async () => { + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await writeDefaults("https://sentry.example.com/"); await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); + + rmSync(rcPath()); + clearSentryCliRcCache(); + await writeDefaults("https://sentry.example.com/"); + await addSentryCliConfig({ authToken: "sntrys_tok" }); + await expectV4ReadsAll(); + expect((await loadSentryCliRc(projectDir)).url).toBe( + "https://sentry.example.com/", + ); }); it("keeps the user's other keys", async () => { writeFileSync(rcPath(), "[defaults]\nurl=https://sentry.example.com/\n"); - writeDefaults(); + await writeDefaults(); await addSentryCliConfig({ authToken: "sntrys_tok" }); await expectV4ReadsAll(); expect((await loadSentryCliRc(projectDir)).url).toBe( 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 10/26] 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 f9c9aa30d33fe9e08a0537687c8e2e1f36fb0a22 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:04:09 +0000 Subject: [PATCH 11/26] fix(cli): address second round of Warden findings in Nuxt and Angular wizards - Nuxt: include the dataCollection preset in the snippet printed when the user keeps an existing Sentry config. - Nuxt: compare majors so 4.x prereleases count as Nuxt 4, and read `future.compatibilityVersion` even when the nuxt version is unknown. - Angular: reject an empty example component path instead of crashing in mkdirSync(''). - Angular and Nuxt: fall back to the ^11 install range in sdkSupportsDataCollection, so the data-collection prompt shows when the installed SDK version can't be read. Adds regression tests for each. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../src/lib/wizard/angular/angular-wizard.ts | 2 +- .../lib/wizard/angular/example-component.ts | 6 +++ .../cli/src/lib/wizard/nuxt/nuxt-wizard.ts | 2 +- packages/cli/src/lib/wizard/nuxt/sdk-setup.ts | 3 +- packages/cli/src/lib/wizard/nuxt/templates.ts | 3 +- packages/cli/src/lib/wizard/nuxt/utils.ts | 10 ++-- .../angular/angular-wizard-install.test.ts | 20 ++++++++ .../wizard/angular/example-component.test.ts | 20 ++++++++ .../test/lib/wizard/nuxt/sdk-setup.test.ts | 44 +++++++++++++++++- .../cli/test/lib/wizard/nuxt/utils.test.ts | 46 +++++++++++++++++++ 10 files changed, 143 insertions(+), 13 deletions(-) create mode 100644 packages/cli/test/lib/wizard/nuxt/utils.test.ts diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts index 0db25f4d97..8002918919 100644 --- a/packages/cli/src/lib/wizard/angular/angular-wizard.ts +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -209,7 +209,7 @@ Apologies for the inconvenience!`, // 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") && + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); const selectedFeatures = await featureSelectionPrompt([ diff --git a/packages/cli/src/lib/wizard/angular/example-component.ts b/packages/cli/src/lib/wizard/angular/example-component.ts index e0d3a81f8f..efbd934450 100644 --- a/packages/cli/src/lib/wizard/angular/example-component.ts +++ b/packages/cli/src/lib/wizard/angular/example-component.ts @@ -33,6 +33,12 @@ export async function createExampleComponent( clack.text({ message: "Where should we create the example component?", placeholder: appRootPath, + validate(value) { + if (!value) { + return "Please enter a path."; + } + return undefined; + }, }), ); } diff --git a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts index f43c10d6ed..e8df4972cc 100644 --- a/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts +++ b/packages/cli/src/lib/wizard/nuxt/nuxt-wizard.ts @@ -149,7 +149,7 @@ async function runNuxtWizardWithTelemetry( // 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") && + sdkSupportsDataCollection(installedSdkVersion, "^11") && (await askShouldReduceDataCollection()); await addDotEnvSentryBuildPluginFile(authToken); diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts index 597be6f9cf..c52ae2f25d 100644 --- a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -21,6 +21,7 @@ import { clack } from "../utils/clack/prompts.js"; import type { PackageManager } from "../utils/package-manager.js"; import { getConfigBody, + getDataCollectionBlock, getDefaultNuxtConfig, getNuxtModuleFallbackTemplate, getSentryConfigContents, @@ -281,7 +282,7 @@ export async function createConfigFiles( ); // Printed outside clack's gutter so that it can be copied/pasted directly clack.rawOutput( - `\n\n ${getConfigBody(dsn, configVariant, selectedFeatures)}\n\n`, + `\n\n ${getConfigBody(dsn, configVariant, selectedFeatures)}\n\n${getDataCollectionBlock(reduceDataCollection)}\n\n`, ); } }); diff --git a/packages/cli/src/lib/wizard/nuxt/templates.ts b/packages/cli/src/lib/wizard/nuxt/templates.ts index e85c3f61f7..df7967f08b 100644 --- a/packages/cli/src/lib/wizard/nuxt/templates.ts +++ b/packages/cli/src/lib/wizard/nuxt/templates.ts @@ -22,7 +22,8 @@ const DATA_COLLECTION_HINT = ` dataCollection: { * The active PII-reducing preset when the user opted in, the commented-out * hint otherwise. */ -function getDataCollectionBlock(reduceDataCollection: boolean): string { +/** The `dataCollection` preset, or a hint about it when not reduced. */ +export function getDataCollectionBlock(reduceDataCollection: boolean): string { return reduceDataCollection ? getDataCollectionSnippet(" ") : DATA_COLLECTION_HINT; diff --git a/packages/cli/src/lib/wizard/nuxt/utils.ts b/packages/cli/src/lib/wizard/nuxt/utils.ts index 4aabd45e28..331ddce8db 100644 --- a/packages/cli/src/lib/wizard/nuxt/utils.ts +++ b/packages/cli/src/lib/wizard/nuxt/utils.ts @@ -3,11 +3,11 @@ * version or by `future.compatibilityVersion: 4` in its config. */ -import { gte, minVersion } from "semver"; import { loadFile } from "magicast"; import { abortIfCancelled } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; import { debug } from "../utils/debug.js"; +import { getMajorVersion } from "../utils/semver.js"; /** * Whether the project uses Nuxt 4. @@ -19,12 +19,8 @@ export async function isNuxtV4( nuxtConfig: string, packageVersion: string | undefined, ): Promise { - if (!packageVersion) { - return false; - } - - const minVer = minVersion(packageVersion); - if (minVer && gte(minVer, "4.0.0")) { + // Compare majors so prereleases such as 4.0.0-rc.1 count as Nuxt 4. + if ((getMajorVersion(packageVersion) ?? 0) >= 4) { return true; } diff --git a/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts index da005d8728..75dbc915d4 100644 --- a/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts +++ b/packages/cli/test/lib/wizard/angular/angular-wizard-install.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { runAngularWizard } from "../../../../src/lib/wizard/angular/angular-wizard.js"; import { installPackage } from "../../../../src/lib/wizard/utils/clack/index.js"; +import { askShouldReduceDataCollection } from "../../../../src/lib/wizard/utils/data-collection.js"; /** Thrown by the mocked install to stop the flow right after it. */ const { STOP } = vi.hoisted(() => ({ STOP: new Error("stop after install") })); @@ -11,6 +12,14 @@ vi.mock("../../../../src/lib/wizard/telemetry.js", async (importOriginal) => ({ withTelemetry: (_options: unknown, fn: () => Promise) => fn(), })); +vi.mock( + "../../../../src/lib/wizard/utils/data-collection.js", + async (importOriginal) => ({ + ...(await importOriginal()), + askShouldReduceDataCollection: vi.fn().mockRejectedValue(STOP), + }), +); + vi.mock("../../../../src/lib/wizard/utils/node-version.js", () => ({ warnIfNodeVersionUnsupportedBySdkV11: vi.fn(), })); @@ -39,6 +48,7 @@ vi.mock( }, }), installPackage: vi.fn().mockRejectedValue(STOP), + featureSelectionPrompt: vi.fn().mockRejectedValue(STOP), }), ); @@ -62,4 +72,14 @@ describe("runAngularWizard", () => { ); }, ); + + it("asks about data collection when the installed SDK version is unknown", async () => { + vi.mocked(installPackage).mockResolvedValueOnce({}); + + await expect( + runAngularWizard({ telemetryEnabled: false, ignoreGitChanges: true }), + ).rejects.toBe(STOP); + + expect(askShouldReduceDataCollection).toHaveBeenCalled(); + }); }); diff --git a/packages/cli/test/lib/wizard/angular/example-component.test.ts b/packages/cli/test/lib/wizard/angular/example-component.test.ts index 70bf3bcc8d..98adbb6583 100644 --- a/packages/cli/test/lib/wizard/angular/example-component.test.ts +++ b/packages/cli/test/lib/wizard/angular/example-component.test.ts @@ -1,3 +1,4 @@ +import { text } from "@clack/prompts"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { createExampleComponent, @@ -50,6 +51,25 @@ describe("createExampleComponent", () => { vi.clearAllMocks(); }); + it("rejects an empty path when ./src/app is missing", async () => { + fsMocks.existsSyncMock.mockReturnValue(false); + vi.mocked(text).mockResolvedValueOnce("custom/app"); + + await createExampleComponent({ + url: "https://sentry.io", + orgSlug: "myOrg", + projectId: "123456789", + }); + fsMocks.existsSyncMock.mockReturnValue(true); + + const validate = vi.mocked(text).mock.calls[0]?.[0].validate; + expect(validate?.("")).toBe("Please enter a path."); + expect(validate?.("custom/app")).toBeUndefined(); + expect(fsMocks.mkdirSyncMock).toHaveBeenCalledWith("custom/app", { + recursive: true, + }); + }); + it("creates an example component file", async () => { const options = { url: "https://sentry.io", diff --git a/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts index 82c6d0fa66..4e5ac798c7 100644 --- a/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts +++ b/packages/cli/test/lib/wizard/nuxt/sdk-setup.test.ts @@ -1,6 +1,13 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + import { beforeEach, describe, expect, it, vi } from "vitest"; import { SemVer } from "semver"; -import { addNuxtOverrides } from "../../../../src/lib/wizard/nuxt/sdk-setup.js"; +import { + addNuxtOverrides, + createConfigFiles, +} from "../../../../src/lib/wizard/nuxt/sdk-setup.js"; import type { PackageManager } from "../../../../src/lib/wizard/utils/package-manager.js"; const { askShouldAddPackageOverrideMock } = vi.hoisted(() => ({ @@ -8,12 +15,18 @@ const { askShouldAddPackageOverrideMock } = vi.hoisted(() => ({ })); vi.mock("@clack/prompts", () => ({ - log: { warn: vi.fn() }, + log: { warn: vi.fn(), info: vi.fn() }, + confirm: vi.fn().mockResolvedValue(false), + isCancel: vi.fn().mockReturnValue(false), })); vi.mock("../../../../src/lib/wizard/utils/clack/index.js", async () => ({ ...(await vi.importActual("../../../../src/lib/wizard/utils/clack/index.js")), askShouldAddPackageOverride: askShouldAddPackageOverrideMock, + featureSelectionPrompt: vi.fn().mockResolvedValue({ + performance: true, + replay: false, + }), })); describe("addNuxtOverrides", () => { @@ -59,3 +72,30 @@ describe("addNuxtOverrides", () => { expect(askShouldAddPackageOverrideMock).not.toHaveBeenCalled(); }); }); + +describe("createConfigFiles", () => { + it("prints the dataCollection preset when the user keeps existing configs", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-config-")); + const originalCwd = process.cwd(); + const write = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + try { + writeFileSync(path.join(dir, "sentry.client.config.js"), ""); + writeFileSync(path.join(dir, "sentry.server.config.js"), ""); + process.chdir(dir); + + await createConfigFiles("https://key@o1.ingest.sentry.io/2", true); + + const printed = write.mock.calls.map(([chunk]) => String(chunk)); + expect(printed).toHaveLength(2); + for (const snippet of printed) { + expect(snippet).toContain("dataCollection: {"); + } + } finally { + process.chdir(originalCwd); + write.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/test/lib/wizard/nuxt/utils.test.ts b/packages/cli/test/lib/wizard/nuxt/utils.test.ts new file mode 100644 index 0000000000..77b55e9939 --- /dev/null +++ b/packages/cli/test/lib/wizard/nuxt/utils.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { isNuxtV4 } from "../../../../src/lib/wizard/nuxt/utils.js"; + +vi.mock("@clack/prompts", () => ({ + confirm: vi.fn(), + isCancel: vi.fn().mockReturnValue(false), +})); + +let dir: string; +let nuxtConfig: string; + +beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), "wizard-nuxt-utils-")); + nuxtConfig = path.join(dir, "nuxt.config.ts"); + writeFileSync(nuxtConfig, "export default defineNuxtConfig({});\n"); +}); + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +describe("isNuxtV4", () => { + it.each(["^4.0.0", "4.0.0-rc.1", "^4.2.0-beta.1"])( + "detects %s as Nuxt 4", + async (version) => { + expect(await isNuxtV4(nuxtConfig, version)).toBe(true); + }, + ); + + it("does not treat Nuxt 3 as Nuxt 4", async () => { + expect(await isNuxtV4(nuxtConfig, "^3.15.0")).toBe(false); + }); + + it("reads compatibilityVersion when the version is unknown", async () => { + writeFileSync( + nuxtConfig, + "export default defineNuxtConfig({ future: { compatibilityVersion: 4 } });\n", + ); + expect(await isNuxtV4(nuxtConfig, undefined)).toBe(true); + }); +}); 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 12/26] 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 13/26] 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 bee2d24538c2a4e9c779d8d65e3f91cef347ba09 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:26:20 +0000 Subject: [PATCH 14/26] fix(cli): build on the new wizard base: use buildProjectIssuesUrl and drop forEach The base removed wizard/utils/url.ts and enabled unicorn/no-array-for-each. - The Angular example component and the Nuxt example page now link to the project's issues with buildProjectIssuesUrl from lib/sentry-web-urls.ts, and drop the `url` option they no longer read. - setSentryCliRcDefaults loops with for...of instead of Array#forEach. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/lib/wizard/angular/angular-wizard.ts | 1 - packages/cli/src/lib/wizard/angular/example-component.ts | 8 +++++--- packages/cli/src/lib/wizard/nuxt/templates.ts | 7 +++---- .../cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts | 6 +++--- .../cli/test/lib/wizard/angular/example-component.test.ts | 3 --- packages/cli/test/lib/wizard/nuxt/templates.test.ts | 1 - 6 files changed, 11 insertions(+), 15 deletions(-) diff --git a/packages/cli/src/lib/wizard/angular/angular-wizard.ts b/packages/cli/src/lib/wizard/angular/angular-wizard.ts index 8002918919..1b6d4c86ad 100644 --- a/packages/cli/src/lib/wizard/angular/angular-wizard.ts +++ b/packages/cli/src/lib/wizard/angular/angular-wizard.ts @@ -280,7 +280,6 @@ Apologies for the inconvenience!`, "create-example-component", async () => await createExampleComponent({ - url: sentryUrl, orgSlug: selectedProject.organization.slug, projectId: selectedProject.id, }), diff --git a/packages/cli/src/lib/wizard/angular/example-component.ts b/packages/cli/src/lib/wizard/angular/example-component.ts index efbd934450..4368b9fb4e 100644 --- a/packages/cli/src/lib/wizard/angular/example-component.ts +++ b/packages/cli/src/lib/wizard/angular/example-component.ts @@ -11,10 +11,9 @@ import { showCopyPasteInstructions, } from "../utils/clack/index.js"; import { clack } from "../utils/clack/prompts.js"; -import { getIssueStreamUrl } from "../utils/url.js"; +import { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; interface ExampleComponentOptions { - url: string; orgSlug: string; projectId: string; } @@ -88,7 +87,10 @@ export async function createExampleComponent( export function getSentryExampleComponentCode( options: ExampleComponentOptions, ): string { - const issueStreamUrl = getIssueStreamUrl(options); + const issueStreamUrl = buildProjectIssuesUrl( + options.orgSlug, + options.projectId, + ); return `import { NgIf } from '@angular/common'; import { Component, OnInit } from '@angular/core'; diff --git a/packages/cli/src/lib/wizard/nuxt/templates.ts b/packages/cli/src/lib/wizard/nuxt/templates.ts index df7967f08b..ab207d7983 100644 --- a/packages/cli/src/lib/wizard/nuxt/templates.ts +++ b/packages/cli/src/lib/wizard/nuxt/templates.ts @@ -4,7 +4,7 @@ */ import { getDataCollectionSnippet } from "../utils/data-collection.js"; -import { getIssueStreamUrl } from "../utils/url.js"; +import { buildProjectIssuesUrl } from "../../sentry-web-urls.js"; type SelectedSentryFeatures = { performance: boolean; @@ -180,12 +180,11 @@ Feel free to delete this file. } export function getSentryExamplePageTemplate(options: { - url: string; org: string; projectId: string; }): string { - const { url, org, projectId } = options; - const issuesPageLink = getIssueStreamUrl({ url, orgSlug: org, projectId }); + const { org, projectId } = options; + const issuesPageLink = buildProjectIssuesUrl(org, projectId); return `