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 1/7] 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 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 2/7] 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 f0dcbadf2d9d0516a73126a9cda398da70c5eb70 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:32:44 +0000 Subject: [PATCH 3/7] feat(wizard): Add deprecated @sentry/wizard forwarder to sentry wizard `sentry wizard` replaces the standalone wizard, but `npx @sentry/wizard -i ` is in the Sentry UI and docs. Version 10 of `@sentry/wizard` keeps those commands working: its `sentry-wizard` bin prints a deprecation notice, then runs `sentry wizard` from the `sentry` package with the same arguments, and passes the exit code and signals through. A first SIGINT waits before it is passed on, since Ctrl-C already reached the CLI. The package depends on `sentry >=0.52.0`. pnpm can't link a workspace package whose -dev version is outside that range, so an override links the workspace CLI; `pnpm pack` leaves the published range as written. It releases from its own Craft workspace, `packages/wizard`, with the same config as `packages/logger`: CLI releases neither bump nor publish it, and it starts at 10.0.0 so npm's `latest` doesn't move back from 9.x. merge-jobs.yml packs it into the commit-SHA artifact on `release/wizard/**`, and the Release workflow gains a `wizard` product, now mapping each product to `packages/` directly instead of through a shell step. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .craft.yml | 9 +- .github/workflows/merge-jobs.yml | 11 +- .github/workflows/release.yml | 27 +-- AGENTS.md | 3 +- docs/README.md | 4 +- packages/wizard/README.md | 31 ++++ packages/wizard/bin/sentry-wizard.js | 96 ++++++++++ packages/wizard/package.json | 47 +++++ packages/wizard/test/sentry-wizard.test.ts | 195 +++++++++++++++++++++ packages/wizard/tsconfig.json | 15 ++ pnpm-lock.yaml | 17 ++ pnpm-workspace.yaml | 4 + 12 files changed, 431 insertions(+), 28 deletions(-) create mode 100644 packages/wizard/README.md create mode 100755 packages/wizard/bin/sentry-wizard.js create mode 100644 packages/wizard/package.json create mode 100644 packages/wizard/test/sentry-wizard.test.ts create mode 100644 packages/wizard/tsconfig.json diff --git a/.craft.yml b/.craft.yml index 2cda5cb1a1..d4e41ceca3 100644 --- a/.craft.yml +++ b/.craft.yml @@ -134,7 +134,10 @@ workspaces: end end # No preReleaseCommand: Craft bumps package.json through the npm target. - packages/logger: + # A package released on its own. Its tarball comes from the commit-SHA + # artifact that merge-jobs.yml uploads, which holds every such package; the + # name filters pick this workspace's own. + packages/logger: &standalone-package changelog: policy: auto releaseBranchPrefix: "release/{{workspaceName}}" @@ -144,3 +147,7 @@ workspaces: includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' - name: npm includeNames: '/^{{packageSimpleName}}-\d.*\.tgz$/' + # @sentry/wizard, the deprecated forwarder to `sentry wizard`. It has its own + # versions, from 10.0.0: npm's `latest` is the 9.x wizard, and the CLI's + # version would move it backwards. CLI releases don't bump or publish it. + packages/wizard: *standalone-package diff --git a/.github/workflows/merge-jobs.yml b/.github/workflows/merge-jobs.yml index 5156a9191c..ba24e1bbe8 100644 --- a/.github/workflows/merge-jobs.yml +++ b/.github/workflows/merge-jobs.yml @@ -2,7 +2,7 @@ name: Post-merge tasks on: push: - branches: ["main", "release/*", "release/logger/**"] + branches: ["main", "release/*", "release/logger/**", "release/wizard/**"] workflow_dispatch: jobs: @@ -38,12 +38,19 @@ jobs: working-directory: packages/logger run: pnpm pack --pack-destination dist + - name: Package wizard + working-directory: packages/wizard + run: pnpm pack --pack-destination dist + + # Craft's logger and wizard workspaces both read this artifact; each npm + # target picks its own tarball by name. - name: Archive artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: ${{ github.sha }} path: | ${{ github.workspace }}/packages/logger/dist/*.tgz + ${{ github.workspace }}/packages/wizard/dist/*.tgz - name: Publish Test Report uses: mikepenz/action-junit-report@cf701569b05ccdd861a76b8607a66d76f6fd4857 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4cf8b7c764..df7590052f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,8 @@ name: Release on: workflow_dispatch: inputs: + # Each product is the `.craft.yml` workspace `packages/`. The + # `cli` release also publishes @sentry/mcp-server at the same version. product: description: Product to release required: true @@ -11,6 +13,7 @@ on: options: - cli - logger + - wizard bump: description: "Version bump: auto (from commits), pre (next prerelease), or an explicit bump type" required: true @@ -61,34 +64,12 @@ jobs: with: run_install: false - - name: Resolve release workspace - id: release - env: - PRODUCT: ${{ inputs.product }} - run: | - # Each product maps to a `.craft.yml` workspace. The `cli` release - # also publishes @sentry/mcp-server at the same version. - case "$PRODUCT" in - cli) - workspace=packages/cli - ;; - logger) - workspace=packages/logger - ;; - *) - echo "::error::Unsupported product: $PRODUCT" - exit 1 - ;; - esac - - echo "workspace=$workspace" >> "$GITHUB_OUTPUT" - - name: Prepare release uses: getsentry/craft@v3 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: - workspace: ${{ steps.release.outputs.workspace }} + workspace: packages/${{ inputs.product }} # An exact version wins over the bump. Craft bumps from the # workspace's latest release tag, or from its package.json version # before the first tag. diff --git a/AGENTS.md b/AGENTS.md index ee494902c5..6f49d82c70 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,8 @@ toolkit/ │ ├── mcp-cloudflare/ # Web app + OAuth │ ├── mcp-server-evals/ # AI evaluation tests │ ├── mcp-server-mocks/ # MSW mocks -│ └── mcp-test-client/ # CLI test client +│ ├── mcp-test-client/ # CLI test client +│ └── wizard/ # Deprecated @sentry/wizard, forwards to `sentry wizard` └── docs/ # Toolkit contributor docs for CLI and MCP ``` diff --git a/docs/README.md b/docs/README.md index 56865b6332..520ff62aed 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,7 +35,9 @@ For package-specific rules, see the root [AGENTS.md](../AGENTS.md) and the [CLI AGENTS.md](../packages/cli/AGENTS.md). `packages/toolkit-core/` contains shared primitives used by both products. `packages/logger/` is the structured logger the CLI uses, published to npm as `@sentry/logger`; see its -[README](../packages/logger/README.md). +[README](../packages/logger/README.md). `packages/wizard/` is the deprecated +`@sentry/wizard` package, which only forwards to `sentry wizard`; see its +[README](../packages/wizard/README.md). ## Ownership diff --git a/packages/wizard/README.md b/packages/wizard/README.md new file mode 100644 index 0000000000..96f6a0e503 --- /dev/null +++ b/packages/wizard/README.md @@ -0,0 +1,31 @@ +# @sentry/wizard + +> **Deprecated. Use `npx sentry wizard`.** The Sentry wizard is now the +> `sentry wizard` command of the [Sentry CLI](https://cli.sentry.dev). It +> takes the same integrations and flags: +> +> ```shell +> npx sentry wizard -i nextjs +> ``` +> +> See the [`sentry wizard` docs](https://cli.sentry.dev/commands/wizard/). + +From version 10, this package only forwards to `sentry wizard`, so existing +`npx @sentry/wizard` commands keep working: + +```shell +npx @sentry/wizard -i nextjs --saas --org my-org --project my-project +``` + +It prints a deprecation notice on stderr, then runs `sentry wizard` from the +[`sentry`](https://www.npmjs.com/package/sentry) package it depends on, with +the same arguments. The exit code and signals pass through. The sign-up flags +`--signup`, `--promo-code` and `--coming-from` are gone: sign up at + first. Version 9 stays on npm for anyone who pins +it. + +## Development + +`bin/sentry-wizard.js` is the whole package, shipped as written. +`pnpm run test` runs it against a stand-in `sentry` package. It is released on +its own, from the `packages/wizard` Craft workspace, not with the CLI. diff --git a/packages/wizard/bin/sentry-wizard.js b/packages/wizard/bin/sentry-wizard.js new file mode 100755 index 0000000000..9155adc93d --- /dev/null +++ b/packages/wizard/bin/sentry-wizard.js @@ -0,0 +1,96 @@ +#!/usr/bin/env node +// `@sentry/wizard` 10 runs `sentry wizard` from the Sentry CLI, which replaced +// it. Arguments, stdio, the exit code, and signals pass through unchanged. +import { spawn } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { constants } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +const NOTICE = + "`@sentry/wizard` is deprecated. Use `npx sentry wizard` instead."; + +/** + * How long the first SIGINT waits before it is passed on. Ctrl-C signals the + * terminal's whole foreground process group, so the CLI has that one already, + * and a second SIGINT means "force quit" to it. A SIGINT sent to this process + * alone, such as `kill -INT`, still reaches the CLI after the wait. + */ +const INTERRUPT_GRACE_MS = 3000; + +/** + * Find the `sentry` package's bin script. Its `exports` don't include + * `package.json`, so look for the file where `require("sentry")` would. + * + * @returns {string | undefined} + */ +function findSentryBin() { + const require = createRequire(import.meta.url); + for (const nodeModules of require.resolve.paths("sentry") ?? []) { + const manifestPath = join(nodeModules, "sentry", "package.json"); + if (!existsSync(manifestPath)) { + continue; + } + /** @type {{ bin?: string | Record }} */ + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + const bin = + typeof manifest.bin === "string" + ? manifest.bin + : manifest.bin?.["sentry"]; + return bin === undefined ? undefined : resolve(dirname(manifestPath), bin); + } + return undefined; +} + +process.stderr.write(`${NOTICE}\n`); + +const sentryBin = findSentryBin(); +if (sentryBin === undefined) { + process.stderr.write( + "Could not find the `sentry` package. Run `npx sentry wizard` instead.\n", + ); + process.exit(1); +} + +const child = spawn( + process.execPath, + [sentryBin, "wizard", ...process.argv.slice(2)], + { stdio: "inherit" }, +); + +let interrupts = 0; +/** @type {NodeJS.Timeout | undefined} */ +let interruptFallback; +const onSigint = () => { + interrupts += 1; + clearTimeout(interruptFallback); + if (interrupts > 1) { + child.kill("SIGINT"); + return; + } + interruptFallback = setTimeout( + () => child.kill("SIGINT"), + INTERRUPT_GRACE_MS, + ); +}; +const onSigterm = () => child.kill("SIGTERM"); +process.on("SIGINT", onSigint); +process.on("SIGTERM", onSigterm); + +child.on("error", (error) => { + process.stderr.write(`Could not start the Sentry CLI: ${error.message}\n`); + process.exit(1); +}); + +child.on("exit", (code, signal) => { + clearTimeout(interruptFallback); + process.off("SIGINT", onSigint); + process.off("SIGTERM", onSigterm); + if (signal === null) { + process.exit(code ?? 1); + } + // End this process with the same signal, so callers see how the CLI ended. + process.kill(process.pid, signal); + // Only reached where the signal doesn't end the process, such as Windows. + process.exit(128 + constants.signals[signal]); +}); diff --git a/packages/wizard/package.json b/packages/wizard/package.json new file mode 100644 index 0000000000..f9371e49dd --- /dev/null +++ b/packages/wizard/package.json @@ -0,0 +1,47 @@ +{ + "name": "@sentry/wizard", + "version": "10.0.0-dev.0", + "description": "Deprecated: forwards to `sentry wizard` from the Sentry CLI. Use `npx sentry wizard` instead.", + "type": "module", + "packageManager": "pnpm@12.18.0", + "engines": { + "node": ">=20.0" + }, + "publishConfig": { + "access": "public" + }, + "license": "FSL-1.1-Apache-2.0", + "author": "Sentry", + "homepage": "https://github.com/getsentry/toolkit/tree/main/packages/wizard#readme", + "keywords": [ + "sentry", + "wizard" + ], + "bugs": { + "url": "https://github.com/getsentry/toolkit/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/getsentry/toolkit.git", + "directory": "packages/wizard" + }, + "bin": { + "sentry-wizard": "./bin/sentry-wizard.js" + }, + "files": [ + "bin/sentry-wizard.js" + ], + "scripts": { + "test": "vitest run", + "test:ci": "vitest run --reporter=default --reporter=junit --outputFile=tests.junit.xml", + "typecheck": "tsc" + }, + "dependencies": { + "sentry": ">=0.52.0" + }, + "devDependencies": { + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/wizard/test/sentry-wizard.test.ts b/packages/wizard/test/sentry-wizard.test.ts new file mode 100644 index 0000000000..c3c27c486e --- /dev/null +++ b/packages/wizard/test/sentry-wizard.test.ts @@ -0,0 +1,195 @@ +import { type ChildProcess, spawn } from "node:child_process"; +import { once } from "node:events"; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; + +const SOURCE_BIN = fileURLToPath( + new URL("../bin/sentry-wizard.js", import.meta.url), +); +const NOTICE = + "`@sentry/wizard` is deprecated. Use `npx sentry wizard` instead.\n"; + +// A stand-in for the `sentry` package's bin. It prints its arguments, then +// behaves as FAKE_SENTRY says: exit with a code, die from a signal, or wait +// and report the signals it gets. +const FAKE_SENTRY_BIN = ` +const [mode, value] = (process.env.FAKE_SENTRY ?? "exit:0").split(":"); +process.stdout.write(JSON.stringify(process.argv.slice(2)) + "\\n"); +if (mode === "exit") process.exit(Number(value)); +if (mode === "kill") process.kill(process.pid, value); +if (mode === "wait") { + for (const signal of ["SIGINT", "SIGTERM"]) { + process.on(signal, () => { + process.stdout.write(signal + "\\n"); + process.exit(Number(value)); + }); + } + process.stdout.write("ready\\n"); + setInterval(() => {}, 1000); +} +`; + +/** Install the forwarder, and the fake `sentry` unless `withSentry` is false. */ +function install(dir: string, withSentry = true): string { + const wizardDir = join(dir, "node_modules", "@sentry", "wizard"); + const bin = join(wizardDir, "bin", "sentry-wizard.js"); + mkdirSync(dirname(bin), { recursive: true }); + writeFileSync( + join(wizardDir, "package.json"), + JSON.stringify({ name: "@sentry/wizard", type: "module" }), + ); + copyFileSync(SOURCE_BIN, bin); + if (withSentry) { + const sentryDir = join(dir, "node_modules", "sentry"); + mkdirSync(join(sentryDir, "dist"), { recursive: true }); + writeFileSync( + join(sentryDir, "package.json"), + JSON.stringify({ name: "sentry", bin: { sentry: "./dist/bin.cjs" } }), + ); + writeFileSync(join(sentryDir, "dist", "bin.cjs"), FAKE_SENTRY_BIN); + } + return bin; +} + +type Run = { + child: ChildProcess; + stdout: () => string; + stderr: () => string; + done: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; +}; + +function run(bin: string, args: string[], fake = "exit:0"): Run { + // `pnpm run` sets NODE_PATH to its store, where Node would find the + // workspace CLI instead of the fake. + const { NODE_PATH: _nodePath, ...env } = process.env; + const child = spawn(process.execPath, [bin, ...args], { + env: { ...env, FAKE_SENTRY: fake }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString())); + child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString())); + const done = once(child, "close").then(([code, signal]) => ({ + code: code as number | null, + signal: signal as NodeJS.Signals | null, + })); + return { child, stdout: () => stdout, stderr: () => stderr, done }; +} + +async function waitFor(check: () => boolean): Promise { + while (!check()) { + await new Promise((resolve) => setTimeout(resolve, 20)); + } +} + +let root: string; +let bin: string; + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "sentry-wizard-test-")); + bin = install(join(root, "project")); +}); + +afterAll(() => { + rmSync(root, { recursive: true, force: true }); +}); + +describe("sentry-wizard", () => { + test("prints the deprecation notice and runs `sentry wizard` with the arguments unchanged", async () => { + const args = [ + "-i", + "nextjs", + "--saas", + "--org", + "x", + "--project", + "my app", + "-u", + ]; + const result = run(bin, args); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(result.stderr()).toBe(NOTICE); + expect(JSON.parse(result.stdout())).toEqual(["wizard", ...args]); + }); + + test("exits with the CLI's exit code", async () => { + const result = run(bin, ["-i", "nextjs", "--promo-code", "x"], "exit:21"); + + expect(await result.done).toEqual({ code: 21, signal: null }); + }); + + test.skipIf(process.platform === "win32")( + "ends with the signal that killed the CLI", + async () => { + const result = run(bin, [], "kill:SIGTERM"); + + expect(await result.done).toEqual({ code: null, signal: "SIGTERM" }); + }, + ); + + test.skipIf(process.platform === "win32")( + "passes SIGTERM on to the CLI", + async () => { + const result = run(bin, [], "wait:7"); + await waitFor(() => result.stdout().includes("ready")); + + result.child.kill("SIGTERM"); + + expect(await result.done).toEqual({ code: 7, signal: null }); + expect(result.stdout()).toContain("SIGTERM\n"); + }, + ); + + test.skipIf(process.platform === "win32")( + "passes a second SIGINT on to the CLI right away", + async () => { + const result = run(bin, [], "wait:130"); + await waitFor(() => result.stdout().includes("ready")); + + // The first one stands for Ctrl-C, which the terminal sends the CLI too. + result.child.kill("SIGINT"); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(result.stdout()).not.toContain("SIGINT"); + result.child.kill("SIGINT"); + + expect(await result.done).toEqual({ code: 130, signal: null }); + expect(result.stdout()).toContain("SIGINT\n"); + }, + ); + + test.skipIf(process.platform === "win32")( + "passes a lone SIGINT on to the CLI after a wait", + async () => { + const result = run(bin, [], "wait:130"); + await waitFor(() => result.stdout().includes("ready")); + const start = Date.now(); + + result.child.kill("SIGINT"); + + expect(await result.done).toEqual({ code: 130, signal: null }); + expect(result.stdout()).toContain("SIGINT\n"); + expect(Date.now() - start).toBeGreaterThanOrEqual(2900); + }, + 10_000, + ); + + test("fails when the `sentry` package is missing", async () => { + const result = run(install(join(root, "no-sentry"), false), []); + + expect(await result.done).toEqual({ code: 1, signal: null }); + expect(result.stderr()).toBe( + `${NOTICE}Could not find the \`sentry\` package. Run \`npx sentry wizard\` instead.\n`, + ); + }); +}); diff --git a/packages/wizard/tsconfig.json b/packages/wizard/tsconfig.json new file mode 100644 index 0000000000..d938054587 --- /dev/null +++ b/packages/wizard/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "noEmit": true, + "allowJs": true, + "checkJs": true + }, + // The package ships its bin script as written, with no build step. + "include": ["bin", "test"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 363032cd0d..573be46447 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -393,6 +393,7 @@ overrides: source-map-js: ^1.2.2 undici: ^7.30.1 zod: ^4.6.6 + '@sentry/wizard>sentry': workspace:* packageExtensionsChecksum: sha256-PIoL2jn0sFpFHgcMKW97dNeqBXVNxH6qFIzsWIBFOMY= @@ -1255,6 +1256,22 @@ importers: specifier: 'catalog:' version: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@22.20.3)(@vitest/coverage-v8@5.0.5)(jsdom@28.1.0(supports-color@10.1.0))(msw@2.15.0(@types/node@22.20.3)(typescript@7.0.2))(vite@8.3.8(@types/node@22.20.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + packages/wizard: + dependencies: + sentry: + specifier: workspace:* + version: link:../cli + devDependencies: + '@types/node': + specifier: 'catalog:' + version: 22.20.3 + typescript: + specifier: 'catalog:' + version: 7.0.2 + vitest: + specifier: 'catalog:' + version: 5.0.5(@opentelemetry/api@1.9.1)(@types/node@22.20.3)(@vitest/coverage-v8@5.0.5)(jsdom@28.1.0(supports-color@10.1.0))(msw@2.15.0(@types/node@22.20.3)(typescript@7.0.2))(vite@8.3.8(@types/node@22.20.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + packages: '@acemir/cssom@0.9.32': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 51d7f42ef8..10dd20e432 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -45,6 +45,10 @@ overrides: undici: ^7.30.1 # GHSA-mrhx-c7xc-m3w5: keep every zod copy at or above the patched release. zod: ^4.6.6 + # @sentry/wizard publishes `sentry: >=0.52.0`, which the CLI's -dev version + # never satisfies, so link the workspace CLI here instead. `pnpm pack` + # ignores overrides, so the tarball keeps the range. + "@sentry/wizard>sentry": "workspace:*" catalog: "@ast-grep/cli": ^0.51.2 From a3aeb487184f04ace97e7183eb07508c7ea1eee8 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:20:33 +0000 Subject: [PATCH 4/7] feat(wizard): translate old @sentry/wizard flags to sentry wizard `sentry wizard` now takes `[/] []` and `-f` instead of the old wizard's flags, so the forwarder translates them: `-i`/`--integration` becomes the integration, `--org` and `--project` become the `/` target (`/` for `--org` alone), `--force-install` and `--ignore-git-changes` become one `-f`, and `-u`/`--url` sets `SENTRY_URL` for the CLI instead of passing an argument. Every other old flag is dropped, along with its value, with a one-line notice that never prints the value. Positionals and `--help` pass through. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/wizard/README.md | 23 ++-- packages/wizard/bin/sentry-wizard.js | 127 ++++++++++++++++++++- packages/wizard/test/sentry-wizard.test.ts | 121 +++++++++++++++++--- 3 files changed, 248 insertions(+), 23 deletions(-) diff --git a/packages/wizard/README.md b/packages/wizard/README.md index 96f6a0e503..43f689c068 100644 --- a/packages/wizard/README.md +++ b/packages/wizard/README.md @@ -2,10 +2,10 @@ > **Deprecated. Use `npx sentry wizard`.** The Sentry wizard is now the > `sentry wizard` command of the [Sentry CLI](https://cli.sentry.dev). It -> takes the same integrations and flags: +> takes the org and project first, then the integration: > > ```shell -> npx sentry wizard -i nextjs +> npx sentry wizard my-org/my-project nextjs > ``` > > See the [`sentry wizard` docs](https://cli.sentry.dev/commands/wizard/). @@ -14,15 +14,24 @@ From version 10, this package only forwards to `sentry wizard`, so existing `npx @sentry/wizard` commands keep working: ```shell -npx @sentry/wizard -i nextjs --saas --org my-org --project my-project +# Runs `sentry wizard my-org/my-project nextjs` +npx @sentry/wizard -i nextjs --org my-org --project my-project ``` It prints a deprecation notice on stderr, then runs `sentry wizard` from the [`sentry`](https://www.npmjs.com/package/sentry) package it depends on, with -the same arguments. The exit code and signals pass through. The sign-up flags -`--signup`, `--promo-code` and `--coming-from` are gone: sign up at - first. Version 9 stays on npm for anyone who pins -it. +the old flags translated: + +- `-i`/`--integration ` becomes the integration argument. +- `--org --project ` becomes `/`, and `--org` + alone becomes `/`. +- `--force-install` and `--ignore-git-changes` become `-f`. +- `-u`/`--url ` sets `SENTRY_URL` for the run. + +Every other old flag is ignored with a notice, including `--project` without +`--org`, `--saas`, `--spotlight` (set `SENTRY_SPOTLIGHT=1` instead) and the +sign-up flags (sign up at first). The exit code +and signals pass through. Version 9 stays on npm for anyone who pins it. ## Development diff --git a/packages/wizard/bin/sentry-wizard.js b/packages/wizard/bin/sentry-wizard.js index 9155adc93d..07d3eea076 100755 --- a/packages/wizard/bin/sentry-wizard.js +++ b/packages/wizard/bin/sentry-wizard.js @@ -1,6 +1,7 @@ #!/usr/bin/env node // `@sentry/wizard` 10 runs `sentry wizard` from the Sentry CLI, which replaced -// it. Arguments, stdio, the exit code, and signals pass through unchanged. +// it. Old flags are translated to the command's syntax; stdio, the exit code, +// and signals pass through unchanged. import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; @@ -42,7 +43,121 @@ function findSentryBin() { return undefined; } +/** Old flags with a `sentry wizard` equivalent, by name. */ +const TRANSLATED = new Map([ + ["i", "integration"], + ["integration", "integration"], + ["u", "url"], + ["url", "url"], + ["org", "org"], + ["project", "project"], +]); + +/** Old flags that `-f` replaces. */ +const FORCE_FLAGS = new Set(["force-install", "ignore-git-changes"]); + +/** Old flags without an equivalent that take a value, which is dropped too. */ +const VALUE_FLAGS = new Set([ + "promo-code", + "coming-from", + "xcode-project-dir", + "app-target", + "hosted-test-target", +]); + +/** Old flags that take every value up to the next flag. */ +const ARRAY_FLAGS = new Set(["p", "platform"]); + +/** + * Translate `@sentry/wizard` arguments to `sentry wizard [/] + * [] [-f]`. Other arguments, such as a target or integration + * already written as positionals, pass through. Values are never printed: + * some old flags carried tokens. + * + * @param {readonly string[]} args + * @returns {{ args: string[], url: string | undefined, notices: string[] }} + */ +function translateArgs(args) { + /** @type {Map} */ + const values = new Map(); + /** @type {string[]} */ + const positionals = []; + /** @type {string[]} */ + const notices = []; + let force = false; + let help = false; + for (let index = 0; index < args.length; index += 1) { + const arg = args[index] ?? ""; + if (arg === "--") { + positionals.push(...args.slice(index + 1)); + break; + } + if (!arg.startsWith("-") || arg === "-") { + positionals.push(arg); + continue; + } + if (arg === "-h" || arg === "--help") { + help = true; + continue; + } + const equals = arg.indexOf("="); + const flag = equals === -1 ? arg : arg.slice(0, equals); + const name = flag.replace(/^--?/, ""); + let value = equals === -1 ? undefined : arg.slice(equals + 1); + const isNextValue = () => !(args[index + 1] ?? "-").startsWith("-"); + const equivalent = TRANSLATED.get(name); + if ( + value === undefined && + (equivalent !== undefined || + VALUE_FLAGS.has(name) || + name.startsWith("preSelectedProject.")) && + isNextValue() + ) { + index += 1; + value = args[index]; + } + if (ARRAY_FLAGS.has(name)) { + while (value === undefined && isNextValue()) { + index += 1; + } + } + if (FORCE_FLAGS.has(name)) { + force = true; + } else if (equivalent === undefined) { + notices.push(`Ignoring ${flag}: \`sentry wizard\` has no such option.`); + } else if (value === undefined) { + notices.push(`Ignoring ${flag}: it needs a value.`); + } else { + values.set(equivalent, value); + } + } + + const org = values.get("org"); + const project = values.get("project"); + if (org === undefined && project !== undefined) { + notices.push( + "Ignoring --project: it needs --org, so the wizard asks for the project.", + ); + } + const integration = values.get("integration"); + return { + args: [ + ...(org === undefined ? [] : [`${org}/${project ?? ""}`]), + ...positionals, + ...(integration === undefined ? [] : [integration]), + ...(force ? ["-f"] : []), + ...(help ? ["--help"] : []), + ], + url: values.get("url"), + notices, + }; +} + process.stderr.write(`${NOTICE}\n`); +const translated = translateArgs(process.argv.slice(2)); +for (const notice of translated.notices) { + process.stderr.write(`${notice}\n`); +} const sentryBin = findSentryBin(); if (sentryBin === undefined) { @@ -54,8 +169,14 @@ if (sentryBin === undefined) { const child = spawn( process.execPath, - [sentryBin, "wizard", ...process.argv.slice(2)], - { stdio: "inherit" }, + [sentryBin, "wizard", ...translated.args], + { + stdio: "inherit", + env: + translated.url === undefined + ? process.env + : { ...process.env, SENTRY_URL: translated.url }, + }, ); let interrupts = 0; diff --git a/packages/wizard/test/sentry-wizard.test.ts b/packages/wizard/test/sentry-wizard.test.ts index c3c27c486e..46d2678c63 100644 --- a/packages/wizard/test/sentry-wizard.test.ts +++ b/packages/wizard/test/sentry-wizard.test.ts @@ -18,12 +18,16 @@ const SOURCE_BIN = fileURLToPath( const NOTICE = "`@sentry/wizard` is deprecated. Use `npx sentry wizard` instead.\n"; -// A stand-in for the `sentry` package's bin. It prints its arguments, then +// A stand-in for the `sentry` package's bin. It prints its arguments and +// SENTRY_URL, then // behaves as FAKE_SENTRY says: exit with a code, die from a signal, or wait // and report the signals it gets. const FAKE_SENTRY_BIN = ` const [mode, value] = (process.env.FAKE_SENTRY ?? "exit:0").split(":"); -process.stdout.write(JSON.stringify(process.argv.slice(2)) + "\\n"); +process.stdout.write( + JSON.stringify({ args: process.argv.slice(2), url: process.env.SENTRY_URL }) + + "\\n", +); if (mode === "exit") process.exit(Number(value)); if (mode === "kill") process.kill(process.pid, value); if (mode === "wait") { @@ -70,7 +74,7 @@ type Run = { function run(bin: string, args: string[], fake = "exit:0"): Run { // `pnpm run` sets NODE_PATH to its store, where Node would find the // workspace CLI instead of the fake. - const { NODE_PATH: _nodePath, ...env } = process.env; + const { NODE_PATH: _nodePath, SENTRY_URL: _sentryUrl, ...env } = process.env; const child = spawn(process.execPath, [bin, ...args], { env: { ...env, FAKE_SENTRY: fake }, stdio: ["ignore", "pipe", "pipe"], @@ -105,26 +109,117 @@ afterAll(() => { }); describe("sentry-wizard", () => { - test("prints the deprecation notice and runs `sentry wizard` with the arguments unchanged", async () => { - const args = [ + test("prints the deprecation notice and translates -i, --org and --project", async () => { + const result = run(bin, [ "-i", "nextjs", - "--saas", "--org", - "x", + "my-org", "--project", - "my app", - "-u", - ]; - const result = run(bin, args); + "my-app", + ]); expect(await result.done).toEqual({ code: 0, signal: null }); expect(result.stderr()).toBe(NOTICE); - expect(JSON.parse(result.stdout())).toEqual(["wizard", ...args]); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "my-org/my-app", "nextjs"], + }); + }); + + test("reads --flag=value forms, and --org alone as an org target", async () => { + const result = run(bin, ["--integration=nextjs", "--org=my-org"]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "my-org/", "nextjs"], + }); + }); + + test("turns --force-install and --ignore-git-changes into one -f", async () => { + const result = run(bin, [ + "--force-install", + "-i", + "nextjs", + "--ignore-git-changes", + ]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "nextjs", "-f"], + }); + }); + + test.each([ + ["-u", "https://sentry.example.com"], + ["--url", "https://sentry.example.com"], + ["--url=https://sentry.example.com"], + ])("sets SENTRY_URL for %s instead of passing it on", async (...urlArgs) => { + const result = run(bin, [...urlArgs, "-i", "nextjs"]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "nextjs"], + url: "https://sentry.example.com", + }); + }); + + test("drops other old flags and their values, with a notice for each", async () => { + const result = run(bin, [ + "--project", + "my-app", + "--saas", + "--spotlight", + "--debug", + "--disable-telemetry", + "--promo-code", + "secret-code", + "--skip-connect", + "--quiet", + "--uninstall", + "-p", + "ios", + "android", + "-i", + "nextjs", + ]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "nextjs"], + }); + expect(result.stderr()).toBe( + NOTICE + + [ + "--saas", + "--spotlight", + "--debug", + "--disable-telemetry", + "--promo-code", + "--skip-connect", + "--quiet", + "--uninstall", + "-p", + ] + .map( + (flag) => + `Ignoring ${flag}: \`sentry wizard\` has no such option.\n`, + ) + .join("") + + "Ignoring --project: it needs --org, so the wizard asks for the project.\n", + ); + }); + + test("passes positionals and --help through", async () => { + const result = run(bin, ["my-org/my-app", "nextjs", "--help"]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "my-org/my-app", "nextjs", "--help"], + }); }); test("exits with the CLI's exit code", async () => { - const result = run(bin, ["-i", "nextjs", "--promo-code", "x"], "exit:21"); + const result = run(bin, [], "exit:21"); expect(await result.done).toEqual({ code: 21, signal: null }); }); From ae8e7164104db87ebe25e15c0b6a7716a728c922 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:03:43 +0000 Subject: [PATCH 5/7] feat(wizard): pass -f/--force through and map --spotlight to SENTRY_SPOTLIGHT `-f` and `--force` are `sentry wizard`'s own flag, so the forwarder passes them on as one `-f` instead of dropping them, together with `--force-install` and `--ignore-git-changes`. `--spotlight` now sets `SENTRY_SPOTLIGHT=1` for the CLI, the way `--url` sets `SENTRY_URL`, instead of being ignored. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/wizard/README.md | 7 ++-- packages/wizard/bin/sentry-wizard.js | 32 +++++++++------ packages/wizard/test/sentry-wizard.test.ts | 45 ++++++++++++++++++---- 3 files changed, 62 insertions(+), 22 deletions(-) diff --git a/packages/wizard/README.md b/packages/wizard/README.md index 43f689c068..a81156d8bd 100644 --- a/packages/wizard/README.md +++ b/packages/wizard/README.md @@ -25,12 +25,13 @@ the old flags translated: - `-i`/`--integration ` becomes the integration argument. - `--org --project ` becomes `/`, and `--org` alone becomes `/`. -- `--force-install` and `--ignore-git-changes` become `-f`. +- `--force-install`, `--ignore-git-changes`, `-f` and `--force` become `-f`. - `-u`/`--url ` sets `SENTRY_URL` for the run. +- `--spotlight` sets `SENTRY_SPOTLIGHT=1` for the run. +- Positional arguments and `--help` pass through. Every other old flag is ignored with a notice, including `--project` without -`--org`, `--saas`, `--spotlight` (set `SENTRY_SPOTLIGHT=1` instead) and the -sign-up flags (sign up at first). The exit code +`--org`, `--saas` and the sign-up flags (sign up at first). The exit code and signals pass through. Version 9 stays on npm for anyone who pins it. ## Development diff --git a/packages/wizard/bin/sentry-wizard.js b/packages/wizard/bin/sentry-wizard.js index 07d3eea076..c40abeb70c 100755 --- a/packages/wizard/bin/sentry-wizard.js +++ b/packages/wizard/bin/sentry-wizard.js @@ -53,8 +53,13 @@ const TRANSLATED = new Map([ ["project", "project"], ]); -/** Old flags that `-f` replaces. */ -const FORCE_FLAGS = new Set(["force-install", "ignore-git-changes"]); +/** Flags that become `-f`, including `-f` itself. */ +const FORCE_FLAGS = new Set([ + "f", + "force", + "force-install", + "ignore-git-changes", +]); /** Old flags without an equivalent that take a value, which is dropped too. */ const VALUE_FLAGS = new Set([ @@ -70,12 +75,13 @@ const ARRAY_FLAGS = new Set(["p", "platform"]); /** * Translate `@sentry/wizard` arguments to `sentry wizard [/] - * [] [-f]`. Other arguments, such as a target or integration - * already written as positionals, pass through. Values are never printed: - * some old flags carried tokens. + * [] [-f]`, plus the CLI's environment variables for `--url` and + * `--spotlight`. Other arguments, such as a target or integration already + * written as positionals, pass through. Values are never printed: some old + * flags carried tokens. * * @param {readonly string[]} args - * @returns {{ args: string[], url: string | undefined, notices: string[] }} + * @returns {{ args: string[], env: Record, notices: string[] }} */ function translateArgs(args) { /** @type {Map} */ @@ -86,6 +92,7 @@ function translateArgs(args) { const notices = []; let force = false; let help = false; + let spotlight = false; for (let index = 0; index < args.length; index += 1) { const arg = args[index] ?? ""; if (arg === "--") { @@ -123,6 +130,8 @@ function translateArgs(args) { } if (FORCE_FLAGS.has(name)) { force = true; + } else if (name === "spotlight") { + spotlight = true; } else if (equivalent === undefined) { notices.push(`Ignoring ${flag}: \`sentry wizard\` has no such option.`); } else if (value === undefined) { @@ -140,6 +149,7 @@ function translateArgs(args) { ); } const integration = values.get("integration"); + const url = values.get("url"); return { args: [ ...(org === undefined ? [] : [`${org}/${project ?? ""}`]), @@ -148,7 +158,10 @@ function translateArgs(args) { ...(force ? ["-f"] : []), ...(help ? ["--help"] : []), ], - url: values.get("url"), + env: { + ...(url === undefined ? {} : { SENTRY_URL: url }), + ...(spotlight ? { SENTRY_SPOTLIGHT: "1" } : {}), + }, notices, }; } @@ -172,10 +185,7 @@ const child = spawn( [sentryBin, "wizard", ...translated.args], { stdio: "inherit", - env: - translated.url === undefined - ? process.env - : { ...process.env, SENTRY_URL: translated.url }, + env: { ...process.env, ...translated.env }, }, ); diff --git a/packages/wizard/test/sentry-wizard.test.ts b/packages/wizard/test/sentry-wizard.test.ts index 46d2678c63..5636a8c5bd 100644 --- a/packages/wizard/test/sentry-wizard.test.ts +++ b/packages/wizard/test/sentry-wizard.test.ts @@ -18,15 +18,17 @@ const SOURCE_BIN = fileURLToPath( const NOTICE = "`@sentry/wizard` is deprecated. Use `npx sentry wizard` instead.\n"; -// A stand-in for the `sentry` package's bin. It prints its arguments and -// SENTRY_URL, then -// behaves as FAKE_SENTRY says: exit with a code, die from a signal, or wait +// A stand-in for the `sentry` package's bin. It prints its arguments, +// SENTRY_URL and SENTRY_SPOTLIGHT, then behaves as FAKE_SENTRY says: exit with a code, die from a signal, or wait // and report the signals it gets. const FAKE_SENTRY_BIN = ` const [mode, value] = (process.env.FAKE_SENTRY ?? "exit:0").split(":"); process.stdout.write( - JSON.stringify({ args: process.argv.slice(2), url: process.env.SENTRY_URL }) + - "\\n", + JSON.stringify({ + args: process.argv.slice(2), + url: process.env.SENTRY_URL, + spotlight: process.env.SENTRY_SPOTLIGHT, + }) + "\\n", ); if (mode === "exit") process.exit(Number(value)); if (mode === "kill") process.kill(process.pid, value); @@ -74,7 +76,12 @@ type Run = { function run(bin: string, args: string[], fake = "exit:0"): Run { // `pnpm run` sets NODE_PATH to its store, where Node would find the // workspace CLI instead of the fake. - const { NODE_PATH: _nodePath, SENTRY_URL: _sentryUrl, ...env } = process.env; + const { + NODE_PATH: _nodePath, + SENTRY_URL: _sentryUrl, + SENTRY_SPOTLIGHT: _sentrySpotlight, + ...env + } = process.env; const child = spawn(process.execPath, [bin, ...args], { env: { ...env, FAKE_SENTRY: fake }, stdio: ["ignore", "pipe", "pipe"], @@ -149,6 +156,30 @@ describe("sentry-wizard", () => { }); }); + test.each([["-f"], ["--force"], ["-f", "--force", "--force-install"]])( + "passes %s through as one -f, with no notice", + async (...forceArgs) => { + const result = run(bin, ["-i", "nextjs", ...forceArgs]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(result.stderr()).toBe(NOTICE); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "nextjs", "-f"], + }); + }, + ); + + test("sets SENTRY_SPOTLIGHT=1 for --spotlight instead of passing it on", async () => { + const result = run(bin, ["--spotlight", "-i", "nextjs"]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(result.stderr()).toBe(NOTICE); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "nextjs"], + spotlight: "1", + }); + }); + test.each([ ["-u", "https://sentry.example.com"], ["--url", "https://sentry.example.com"], @@ -168,7 +199,6 @@ describe("sentry-wizard", () => { "--project", "my-app", "--saas", - "--spotlight", "--debug", "--disable-telemetry", "--promo-code", @@ -191,7 +221,6 @@ describe("sentry-wizard", () => { NOTICE + [ "--saas", - "--spotlight", "--debug", "--disable-telemetry", "--promo-code", From 8a4c9262818ffdcb89c6ee20f43dec1696d390fd Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:58:07 +0000 Subject: [PATCH 6/7] fix(wizard): find the sentry package under Yarn Plug'n'Play `require.resolve.paths()` returns null under Yarn PnP, so the forwarder never found `sentry` and exited with "Could not find the `sentry` package" from `yarn sentry-wizard` or `yarn dlx @sentry/wizard`. Resolve `sentry`'s entry point instead, which PnP supports, and walk up to its package.json. The test stand-in now mirrors the real package's `exports`. --- packages/wizard/bin/sentry-wizard.js | 39 ++++++++++++++-------- packages/wizard/test/sentry-wizard.test.ts | 9 ++++- 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/packages/wizard/bin/sentry-wizard.js b/packages/wizard/bin/sentry-wizard.js index c40abeb70c..de18ecca58 100755 --- a/packages/wizard/bin/sentry-wizard.js +++ b/packages/wizard/bin/sentry-wizard.js @@ -21,26 +21,37 @@ const INTERRUPT_GRACE_MS = 3000; /** * Find the `sentry` package's bin script. Its `exports` don't include - * `package.json`, so look for the file where `require("sentry")` would. + * `package.json`, so resolve its entry point and walk up to its manifest. + * Resolving works in `node_modules` installs and under Yarn Plug'n'Play. * * @returns {string | undefined} */ function findSentryBin() { - const require = createRequire(import.meta.url); - for (const nodeModules of require.resolve.paths("sentry") ?? []) { - const manifestPath = join(nodeModules, "sentry", "package.json"); - if (!existsSync(manifestPath)) { - continue; + let dir; + try { + dir = dirname(createRequire(import.meta.url).resolve("sentry")); + } catch { + return undefined; + } + for (;;) { + const manifestPath = join(dir, "package.json"); + if (existsSync(manifestPath)) { + /** @type {{ name?: string, bin?: string | Record }} */ + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + if (manifest.name === "sentry") { + const bin = + typeof manifest.bin === "string" + ? manifest.bin + : manifest.bin?.["sentry"]; + return bin === undefined ? undefined : resolve(dir, bin); + } + } + const parent = dirname(dir); + if (parent === dir) { + return undefined; } - /** @type {{ bin?: string | Record }} */ - const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); - const bin = - typeof manifest.bin === "string" - ? manifest.bin - : manifest.bin?.["sentry"]; - return bin === undefined ? undefined : resolve(dirname(manifestPath), bin); + dir = parent; } - return undefined; } /** Old flags with a `sentry wizard` equivalent, by name. */ diff --git a/packages/wizard/test/sentry-wizard.test.ts b/packages/wizard/test/sentry-wizard.test.ts index 5636a8c5bd..e0bebf746c 100644 --- a/packages/wizard/test/sentry-wizard.test.ts +++ b/packages/wizard/test/sentry-wizard.test.ts @@ -59,8 +59,15 @@ function install(dir: string, withSentry = true): string { mkdirSync(join(sentryDir, "dist"), { recursive: true }); writeFileSync( join(sentryDir, "package.json"), - JSON.stringify({ name: "sentry", bin: { sentry: "./dist/bin.cjs" } }), + // Like the real package, its `exports` don't include package.json. + JSON.stringify({ + name: "sentry", + main: "./dist/index.cjs", + exports: { ".": { require: "./dist/index.cjs" } }, + bin: { sentry: "./dist/bin.cjs" }, + }), ); + writeFileSync(join(sentryDir, "dist", "index.cjs"), ""); writeFileSync(join(sentryDir, "dist", "bin.cjs"), FAKE_SENTRY_BIN); } return bin; From de0a28c5bcf1da3ef0558580c460f84d423a9676 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:58:09 +0000 Subject: [PATCH 7/7] fix(wizard): ship the FSL license text in the package `@sentry/wizard` is FSL-1.1-Apache-2.0 like the CLI, which requires distributing the license with the software. Add the CLI's LICENSE.md and list it in `files`, as the other published packages do. --- packages/wizard/LICENSE.md | 105 +++++++++++++++++++++++++++++++++++ packages/wizard/package.json | 3 +- 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 packages/wizard/LICENSE.md diff --git a/packages/wizard/LICENSE.md b/packages/wizard/LICENSE.md new file mode 100644 index 0000000000..6e9bafc7ac --- /dev/null +++ b/packages/wizard/LICENSE.md @@ -0,0 +1,105 @@ +# Functional Source License, Version 1.1, Apache 2.0 Future License + +## Abbreviation + +FSL-1.1-Apache-2.0 + +## Notice + +Copyright 2025 Functional Software, Inc. dba Sentry + +## Terms and Conditions + +### Licensor ("We") + +The party offering the Software under these Terms and Conditions. + +### The Software + +The "Software" is each version of the software that we make available under +these Terms and Conditions, as indicated by our inclusion of these Terms and +Conditions with the Software. + +### License Grant + +Subject to your compliance with this License Grant and the Patents, +Redistribution and Trademark clauses below, we hereby grant you the right to +use, copy, modify, create derivative works, publicly perform, publicly display +and redistribute the Software for any Permitted Purpose identified below. + +### Permitted Purpose + +A Permitted Purpose is any purpose other than a Competing Use. A Competing Use +means making the Software available to others in a commercial product or +service that: + +1. substitutes for the Software; + +2. substitutes for any other product or service we offer using the Software + that exists as of the date we make the Software available; or + +3. offers the same or substantially similar functionality as the Software. + +Permitted Purposes specifically include using the Software: + +1. for your internal use and access; + +2. for non-commercial education; + +3. for non-commercial research; and + +4. in connection with professional services that you provide to a licensee + using the Software in accordance with these Terms and Conditions. + +### Patents + +To the extent your use for a Permitted Purpose would necessarily infringe our +patents, the license grant above includes a license under our patents. If you +make a claim against any party that the Software infringes or contributes to +the infringement of any patent, then your patent license to the Software ends +immediately. + +### Redistribution + +The Terms and Conditions apply to all copies, modifications and derivatives of +the Software. + +If you redistribute any copies, modifications or derivatives of the Software, +you must include a copy of or a link to these Terms and Conditions and not +remove any copyright notices provided in or with the Software. + +### Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR +PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. + +IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE +SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, +EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. + +### Trademarks + +Except for displaying the License Details and identifying us as the origin of +the Software, you have no right under these Terms and Conditions to use our +trademarks, trade names, service marks or product names. + +## Grant of Future License + +We hereby irrevocably grant you an additional license to use the Software under +the Apache License, Version 2.0 that is effective on the second anniversary of +the date we make the Software available. On or after that date, you may use the +Software under the Apache License, Version 2.0, in which case the following +will apply: + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/packages/wizard/package.json b/packages/wizard/package.json index f9371e49dd..06e8f60588 100644 --- a/packages/wizard/package.json +++ b/packages/wizard/package.json @@ -29,7 +29,8 @@ "sentry-wizard": "./bin/sentry-wizard.js" }, "files": [ - "bin/sentry-wizard.js" + "bin/sentry-wizard.js", + "LICENSE.md" ], "scripts": { "test": "vitest run",